MongoDB没有使用我的索引 [英] MongoDB not using my index

查看:797
本文介绍了MongoDB没有使用我的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含数百万条记录的日志集合。创建新索引需要永远。因此,最好使用现有索引。

I have a logs collection with millions of records. Creating a new index takes "forever". So it would be preferred to use existing indexes.

现在我想得到某些错误代码的出现次数。我使用这个查询,功能上它工作正常:

Now I want to get the number of occurances of certain error codes. I use this query, and functionally it works fine:

db.getCollection('logs.res').aggregate([
    {
       $match:{    
           timeStamp: {
               $gte: new Date('2017-05-01').getTime(), // timeStamp is Number
               $lt : new Date('2017-05-02').getTime()  // of ms since epoch
           },
           'objData.@.ErrorCode': {
               $ne: null
           }
        }
    },
    {
        $group: {
            _id: '$objData.@.ErrorCode',
            count: {$sum: 1}
        }
    },
    {
        $sort: { count: -1}
    }
]);

问题是,执行此操作一天需要10秒左右。我假设将使用以下索引: timeStamp_-1_objData。@。ErrorCode_1

The problem is that it takes well near 10 seconds just to execute this for a day. I had assumed the following index would be used: timeStamp_-1_objData.@.ErrorCode_1:

{
    "timeStamp" : -1,
    "objData.@.ErrorCode" : 1
}

然而,MongoDB似乎坚持使用一些 timeStamp:1 索引(其他一些索引与查询无关),并扫描alllllll结果以查看某些响应是否附加了 ErrorCode ,即使此信息应该在索引中。

However, MongoDB seems adamant to use some timeStamp: 1 index (with some other indexes unrelated to the query), and scan alllllll the results to see if some responses might have an ErrorCode attached, even though this information should be in the index.

这是 explain()


  • 有没有办法使用 timeStamp_-1_objData。@。ErrorCode_1 索引加快提升速度?

  • 为什么使用此索引? 我可能是误入歧途如何在此查询中使用索引。

  • Is there a way to use the timeStamp_-1_objData.@.ErrorCode_1 index to speed this up?
  • Why isn't it using this index? I'm probably misunderstanding how indexes are used in this query.

在OSX上运行MongoDB 3.2.7 。

Running MongoDB 3.2.7 on OSX.

注意:我也试过 $ empty:true 而不是 $ ne:null 。它会产生相同的结果,但有些人说如果要使用复合索引,则不能使用 $ empty 。关于Stack Overflow的许多问题都是旧的(mongo 2.x)。

note: I've also tried $empty: true in stead of $ne: null. It yields the same results, but some say you cannot use $empty if you want to use a compound index. Many questions on Stack Overflow are old (mongo 2.x) though.

推荐答案

获胜计划是 CACHED PLAN
您可以尝试清除缓存计划。

Winning plan is CACHED PLAN. You can try clearing the cache plan.

db.getCollection('logs.res').getPlanCache().clear()

如果在清理缓存后,Mongo仍在使用错误的索引。您可以尝试设置查询计划或使用提示强制索引

If after you clean the cache, Mongo is still using the wrong index. You can try setting the query plan or use "hint" to force your index

这篇关于MongoDB没有使用我的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆