【问题标题】:slow Mongodb $near search with additional criteria带有附加条件的慢 Mongodb $near 搜索
【发布时间】:2012-10-20 16:52:25
【问题描述】:

我有一个集合,数据是这样的:

{
    "_id" : ObjectId("4e627655677c27cf24000000"),
    "gps" : {
        "lng" : 116.343079,
        "lat" : 40.034283
    },
    "lat" : 1351672296
}

我建立了一个复合索引:

{
    "v" : 1,
    "key" : {
        "gps" : "2d",
        "lat" : 1
    },
    "ns" : "test.user",
    "name" : "gps__lat_1"
}

像下面这样的纯 $near 查询可以非常快(

>db.user.find({"gps":{"$near":{"lng":116.343079,"lat":40.034283}}}).explain()
{
    "cursor" : "GeoSearchCursor",
    "nscanned" : 100,
    "nscannedObjects" : 100,
    "n" : 100,
    "millis" : 23,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "isMultiKey" : false,
    "indexOnly" : false,
    "indexBounds" : {

    }
}

但是带有“lat”条件的查询非常慢(900ms+):

>db.user.find({"gps":{"$near":{"lng":116.343079,"lat":40.034283}},"lat":{"$gt":1351413167}}).explain()
{
    "cursor" : "GeoSearchCursor",
    "nscanned" : 3,
    "nscannedObjects" : 3,
    "n" : 3,
    "millis" : 665,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "isMultiKey" : false,
    "indexOnly" : false,
    "indexBounds" : {

    }
}    

谁能解释一下?太好了!

【问题讨论】:

  • 您能否提供 explain() 的输出,以便我们了解它为什么慢?
  • 没有看到 explain() 输出的内容,很难确定发生了什么。
  • Stackflow.com 告诉我必须为代码提供更多上下文,所以我删除了它们。现在我通过编辑提供它们。顺便说一句,我刚刚发现带有提示({lat:1})的查询得到了错误的结果,它不起作用。
  • 我用 { $maxDistance : 10 } 再次尝试相同的查询,它有效。
  • 但是它仍然不能解释一个查询变得非常慢的附加条件。也许 Mongodb 在进行地理搜索之前扫描集合以过滤数据?

标签: mongodb geo


【解决方案1】:

我将我的 Mongodb 更新到 2.2.0,问题消失了。

127.0.0.1/test> db.user.find({gps:{$near:[116,40]},lat:{$gt:1351722342}}).explain()
{
    "cursor" : "BasicCursor",
    "isMultiKey" : false,
    "n" : 0,
    "nscannedObjects" : 0,
    "nscanned" : 0,
    "nscannedObjectsAllPlans" : 0,
    "nscannedAllPlans" : 0,
    "scanAndOrder" : false,
    "indexOnly" : false,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "millis" : 0,
    "indexBounds" : {

    },
    "server" : "zhangshenjiamatoMacBook-Air.local:27017"
}

【讨论】:

    【解决方案2】:

    从上面的解释来看,geoIndex 似乎根本没有被使用 - 而且,上面的查询似乎没有返回任何结果!

    如果您的查询使用 2d 索引,则说明应包含:

    “光标”:“地理搜索光标”

    您能否检查升级到 2.2.0 是否真的解决了您的问题? :)

    孙达

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-02
      • 2013-08-29
      • 1970-01-01
      • 1970-01-01
      • 2013-06-24
      • 2021-09-23
      • 1970-01-01
      相关资源
      最近更新 更多