使用pymongo的地理空间索引示例

2024-10-06 11:27:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在考虑使用MongoDB而不是自定义地理空间数据库,但是我很难理解pymongo如何使用球坐标。 具体地说,我不确定$maxDistance(以及类似的设置是否有任何效果)。 例如,如果我执行此代码:

db = pymongo.MongoClient().geo_example
db.places.create_index([("location", pymongo.GEOSPHERE)])

cities = [{"location": {'type': 'Point', 'coordinates': [57, 2]}, "name": "Aberdeen"},
          {"location": {'type': 'Point', 'coordinates': [52, 13]}, "name": "Berlin"},
          {"location": {'type': 'Point', 'coordinates': [44, 26]}, "name": "Bucharest"},
          {"location": {'type': 'Point', 'coordinates': [40, 14]}, "name": "Napoli"},
          {"location": {'type': 'Point', 'coordinates': [48, 2]}, "name": "Paris"},
          {"location": {'type': 'Point', 'coordinates': [35, -70]}, "name": "Tokyo"},
          {"location": {'type': 'Point', 'coordinates': [47, 8]}, "name": "Zurich"}]

try:
    result = db.places.insert_many(cities)
    for doc in db.places.find( {"location":{'$nearSphere':  [57, 2], "$maxDistance": 1}}).limit(3):
        pprint.pprint(doc)
except BulkWriteError as bwe:
    print(bwe.details)

我希望答案只是阿伯丁,相反,即使最大距离大于1米,我仍然能得到最近的3个。我想我做错了什么。 任何关于pymongo使用的帮助以及更好的示例(比文档中的更好)都会非常有用。 谢谢


Tags: namedbdocmongodbtypelocation地理point
1条回答
网友
1楼 · 发布于 2024-10-06 11:27:38

您使用的是较旧的查询形式,其中以弧度指定距离。如果更改为new format,则maxDistance以米为单位指定

此外,由于在时间迷雾中丢失的原因,地理空间数据按长/纬度顺序排序,因此所有坐标都需要反转。我已经修改了您的代码,使其使用正确的坐标方向,并使用新的查询格式。我还为集合输入了一个drop命令(这是示例代码)。这让我困惑,也可能让你困惑。多次运行 程序的所有部分将反复插入相同的点。毫不犹豫 每个查询将返回与您运行程序的次数相同的结果。最后,我添加了一个GEOSPHERE索引,文档中说您需要这个索引,即使您的程序没有它也可以正常运行。我怀疑如果没有这一点,随着位置数量的增加,您将看到性能的几何下降

import pymongo
import pprint
from pymongo.errors import BulkWriteError

db = pymongo.MongoClient().geo_example
db.places.drop()
db.places.create_index([("location", pymongo.GEOSPHERE)])

cities = [{"location": {'type': 'Point', 'coordinates': [2, 57]}, "name": "Aberdeen"},
          {"location": {'type': 'Point', 'coordinates': [13, 52]}, "name": "Berlin"},
          {"location": {'type': 'Point', 'coordinates': [26, 44]}, "name": "Bucharest"},
          {"location": {'type': 'Point', 'coordinates': [14, 40]}, "name": "Napoli"},
          {"location": {'type': 'Point', 'coordinates': [2, 48]}, "name": "Paris"},
          {"location": {'type': 'Point', 'coordinates': [-70, 35]}, "name": "Tokyo"},
          {"location": {'type': 'Point', 'coordinates': [8, 47]}, "name": "Zurich"}]

try:
    result = db.places.insert_many(cities)
    db.places.create_index([("location", pymongo.GEOSPHERE)])
    for doc in db.places.find({"location":{
                                "$nearSphere": {
                                     "$geometry": {
                                        "type": "Point",
                                        "coordinates": [2,57]
                                      },
                                     "$maxDistance": 1}}}):
        pprint.pprint(doc)
except BulkWriteError as bwe:
    print(bwe.details)

相关问题 更多 >