我正在尝试编写脚本来执行此处提到的基本2dsphere索引操作 2dsphere使用pymongo。
我找不到任何例子来解决这个问题,这是我到目前为止的尝试:
from pymongo import GEOSPHERE
client=MongoClient('localhost',27017)
db=client['dbtest']
points=db['points']
points.create_index([("loc",GEOSPHERE)])
points.insert({"loc":[2 5]})
points.insert({"loc":[30,5]})
more points.insert
for doc in points.find({"loc" : {"$near": { "$geometry" : {"type":"Point","coordinates":[1,2]},"$maxDistance":20}}}):
print doc
它提供错误pymongo.errors.OperationFailure: database error: can't find special index: 2d for: { loc: { $near: { $geometry: { type: "Point", coordinates: [ 1, 2 ] }, $maxDistance: 20 } } }
答案 0 :(得分:9)
2dsphere(pymongo.GEOSPHERE)索引类型仅适用于MongoDB 2.4及更高版本。您还需要使用GeoJSON格式作为积分。最后,MongoDB的地理查询运算符是顺序敏感的,因此在使用$ maxDistance等选项时,您必须使用SON。以下是使用$near的示例:
>>> c = pymongo.MongoClient()
>>> points = c.dbtest.points
>>> points.ensure_index([("loc", pymongo.GEOSPHERE)])
u'loc_2dsphere'
>>> points.insert({'loc': {'type': 'Point', 'coordinates': [40, 5]}})
ObjectId('51b0e508fba522160ce84c3a')
>>> for doc in points.find({"loc" : SON([("$near", { "$geometry" : SON([("type", "Point"), ("coordinates", [40, 5])])}), ("$maxDistance", 10)])}):
... doc
...
{u'loc': {u'type': u'Point', u'coordinates': [40, 5]}, u'_id': ObjectId('51b0e508fba522160ce84c3a')}
答案 1 :(得分:4)
在最新版本中,我认为$maxDistance
必须位于$near
运算符中:
from bson.son import SON
from pymongo import MongoClient
db = MongoClient()
latitude = 10
longitude = 20
max_distance = 1000 #meters
query = {'loc': {'$near': SON([('$geometry', SON([('type', 'Point'), ('coordinates', [longitude, latitude])])), ('$maxDistance', max_distance)])}}
for doc in db.database_name.collection_name.find(query):
print(doc)
答案 2 :(得分:0)
鉴于您的集合是geoid的名称,并且您的geojson对象被命名为geometry ...
import pymongo
geoid.create_index([("geometry", pymongo.GEOSPHERE)])
应该这样做!