【问题标题】:Calculate distance in MongoDB map-reduce在 MongoDB map-reduce 中计算距离
【发布时间】:2014-02-26 14:09:13
【问题描述】:

我有一个带有地理索引的 MongoDB 集合:

> db.coll.getIndexes()
[
    // ...
    {
        "v" : 1,
        "key" : {
            "location" : "2dsphere"
        },
        "ns" : "test.coll",
        "dropDups" : false,
        "name" : "location_2dsphere",
        "background" : false
    }
]

db.coll.findOne({location: {'$exists': true}}, {'location': 1})
{
    "_id" : ObjectId("52cd72ae2ac170aa3eaace6e"),
    "location" : [
        55.4545177559,
        11.5767419669
    ]
}

我正在运行 map reduce,它看起来像这样:

var map = function() {
     var value = 0;

     // ... various calculations on the value here

     var distance = 0; // < This is the problematic part
     if (distance < 1000) {
         val += distance;  // for example
     }

     emit(this._id, value)
}
var reduce = function(id, val) {
    return {id: val}
}

db.coll.mapReduce(map, reduce, {out: {inline: 1}})

有没有办法在map函数中计算location和X点之间的距离?

我正在寻找类似 @​​987654321@ 的东西,但不知何故与 map-reduce 相结合。

例如:

db.runCommand({geoNear: "coll", near: [-74, 40.74], spherical: true})

返回每个文档的距离。但我找不到将它与 map-reduce 命令结合使用的方法。

【问题讨论】:

  • 另外,你已经尝试了什么?
  • 用纯 js 做并不是最优的,因为 mongo 已经支持距离计算...
  • 至于“我尝试过的”,我在集合上运行geonear 查询和map-reduce。寻找一种方法来结合 2.
  • @YuriPrezument 你也可以在mapReduce 中限定what你正在尝试做的事情,而不是仅仅问“我可以使用它吗”,也许有人可能会建议“你正在尝试做什么”。到目前为止,我们还看不到这一点。请注意,您在近距离投票名单上,因此最好确定您想要什么。

标签: mongodb mapreduce distance


【解决方案1】:

大圆公式是要走的路http://en.wikipedia.org/wiki/Great-circle_distance

我在 mongo 和 js 中遇到了类似的问题。并想出了这个功能。希望对您有所帮助。

function find(point, latlng, radius){
       var dist = parseInt(radius) * 0.868976 / 60; // convert miles to rad

    if((point[0] <= latlng[0] + dist && point[1] >= latlng[1]- dist) 
    && (point[0] <= latlng[0]+ dist && point[1] >= latlng[1]- dist)){

        dx = latlng[0] - point[0];
        dy = latlng[1] - point[1];
        dx *= dx;
        dy *= dy;
        ds = dx + dy;
        rs = dist * dist;
        is =  ds <= rs;

        return is;
    }
}

我是这样称呼的:

find([-79,5], [40,20], 5);

【讨论】:

  • 很好,谢谢!我已经用另一种方式解决了它(而不是在 Python 中进行距离计算),但这似乎是一个很好的解决方案。
【解决方案2】:

我知道这是一个较晚的添加,但对于来到这里的其他人来说,了解一套可用于执行地理相关功能的 Javascript 库可能会很好。

https://github.com/manuelbieh/Geolib

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-30
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多