我正在尝试编写一个脚本来执行此处提到的基本 2dsphere 索引操作2dsphere http://docs.mongodb.org/manual/core/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 } } }
The 2dsphere http://docs.mongodb.org/manual/core/2dsphere/(pymongo.GEOSPHERE) 索引类型仅适用于 MongoDB 2.4 及更高版本。您还会想要使用GeoJSON http://docs.mongodb.org/manual/core/2dsphere/#store-geojson-objects您的点的格式。最后,MongoDB 的地理查询运算符对顺序敏感,因此您必须使用SON http://api.mongodb.org/python/current/api/bson/son.html#bson.son.SON当使用像 $maxDistance 这样的选项时。这是一个使用的示例$near http://docs.mongodb.org/manual/reference/operator/near/#op._S_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')}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)