Heim > Fragen und Antworten > Hauptteil
类似于lbs的服务,需要按照用户位置的距离排序。
集合的结构:
{
"_id" : ObjectId("574bbae4d009b5364abaebe5"),
"cityid" : 406,
"location" : {
"type" : "Point",
"coordinates" : [
118.602355,
24.89083
]
},
"shopid" : "a"
}
差不多5万条数据。
索引:
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "pingan-test.shop_actinfo_collection_0530"
},
{
"v" : 1,
"key" : {
"location" : "2dsphere"
},
"name" : "location_2dsphere",
"ns" : "pingan-test.shop_actinfo_collection_0530",
"2dsphereIndexVersion" : 3
},
{
"v" : 1,
"key" : {
"shopid" : 1,
"cityid" : 1
},
"name" : "shopid_1_cityid_1",
"ns" : "pingan-test.shop_actinfo_collection_0530"
}
]
查询的条件是:
{'cityid': 2, 'location': {'$near': {'$geometry': {'type': 'Point', 'coordinates': [122.0, 31.0]}}}, 'shopid': {'$in': ['a','b']}}
当使用pymongo查询的时候,迭代会消耗大概300ms的时间,这个难以接受。
results = collection.find(body, {'shopid': 1, '_id':0},).batch_size(20).limit(20)
shops = list(results)
第一步获取一个游标,几乎没有消耗时间;
第二部对这个有标进行迭代消耗300~400ms时间。
应该如何优化?
高洛峰2017-04-17 18:03:47
这样建索引固然能够解决问题,这里要强调经常被大家忽略的一点:过滤性强的条件放前面
因为不知道你的数据如何分布,所以没法判断你的索引是不是满足这个最佳实践。但是看起来,除非shopid
在不同城市有重复(我怀疑通常不会这么设计),否则cityid
根本没有作用,不用放在索引里,徒增写压力。