是的,AWS DocumentDB 支持 MongoDB 的 2dsphere 索引。你可以按照以下步骤在 AWS DocumentDB 中创建和使用 2dsphere 索引:
import pymongo
# 创建连接
client = pymongo.MongoClient('', ssl=True, ssl_cert_reqs='CERT_NONE')
# 选择数据库
db = client['']
# 选择集合
collection = db['']
create_index()
方法在集合中创建 2dsphere 索引。以下是一个创建 2dsphere 索引的示例代码:# 创建 2dsphere 索引
collection.create_index([("location", "2dsphere")])
在上面的示例中,location
是你的集合中包含地理位置数据的字段名称。
# 执行地理空间查询
result = collection.find({
"location": {
"$near": {
"$geometry": {
"type": "Point",
"coordinates": [longitude, latitude]
},
"$maxDistance": 1000
}
}
})
# 遍历结果
for doc in result:
print(doc)
在上面的示例中,longitude
和 latitude
是查询点的经度和纬度坐标,$maxDistance
是查询的最大距离。
这就是使用 AWS DocumentDB 创建和使用 2dsphere 索引的解决方法。你可以根据自己的需求进行调整和扩展。