MongoDB$near查询速度很慢



One mongodb collection

{
    "_id" : ObjectId("574bbae4d009b5364abaebe5"),
    "cityid" : 406,
    "location" : {
        "type" : "Point",
        "coordinates" : [
            118.602355,
            24.89083
        ]
    },
    "shopid" : "a"
}

大约有 50, 000 行;

和索引:

[
    {
        "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"
    }
]

我查询这个集合,如下所示:

 body = {'cityid': 2, 'location': {'$near': {'$geometry': {'type': 'Point', 'coordinates': [122.0, 31.0]}}}, 'shopid': {'$in': ['a','b']}}
results = collection.find(body, {'shopid': 1, '_id':0},).batch_size(20).limit(20)
shops = list(results)

问题是它运行大约 400 毫秒。但是,如果我们不关心位置,只需要30ms。

为什么以及如何修复?请。

您有一个关于 shopid 和 cityid 的索引,但您搜索的是 cityid。由于索引首先按 shopid 排序,因此不能用于按 cityid 进行搜索。如果将索引更改为 cityid: 1, shopid: 1,则会看到性能改进,因为查询将能够使用该索引进行搜索。

毕竟

,我明白了。我只是创建一个索引来cityid: 1, shopid: 1, "location" : "2dsphere" ,然后,世界和平。

再次感谢@tiramisu。

最新更新