【问题标题】:MongoDB index is not being used未使用 MongoDB 索引
【发布时间】:2018-06-22 10:31:39
【问题描述】:

我有一组问题的索引已修改。

{
  "v" : 1,
  "key" : {
      "modified" : 1
  },
  "name" : "modified_1",
  "ns" : "app23568387.questions",
  "background" : true,
  "safe" : null
}

但是当我查询带有修改字段的问题时,mongo 不使用这个索引。

db.questions.find({modified: ISODate("2016-07-20T20:58:20.662Z")}).explain(true);

返回

{
  "cursor" : "BasicCursor",
  "isMultiKey" : false,
  "n" : 0,
  "nscannedObjects" : 19315626,
  "nscanned" : 19315626,
  "nscannedObjectsAllPlans" : 19315626,
  "nscannedAllPlans" : 19315626,
  "scanAndOrder" : false,
  "indexOnly" : false,
  "nYields" : 384889,
  "nChunkSkips" : 0,
  "millis" : 43334,
  "allPlans" : [ 
      {
          "cursor" : "BasicCursor",
          "isMultiKey" : false,
          "n" : 0,
          "nscannedObjects" : 19315626,
          "nscanned" : 19315626,
          "scanAndOrder" : false,
          "indexOnly" : false,
          "nChunkSkips" : 0
      }
  ],
  "server" : "c387.candidate.37:10387",
  "filterSet" : false,
  "stats" : {
      "type" : "COLLSCAN",
      "works" : 19624020,
      "yields" : 384889,
      "unyields" : 384889,
      "invalidates" : 3,
      "advanced" : 0,
      "needTime" : 19315627,
      "needFetch" : 0,
      "isEOF" : 1,
      "docsTested" : 19315626,
      "children" : []
  }
}

当我使用hint() 时,mongo 会抛出错误bad hint。 我有另一个具有完全相同索引的文件夹集合,并且查询使用索引。 (为explain()返回"cursor" : "BtreeCursor modified_1"

问题和文件夹之间有什么区别?即使getIndexes() 返回它,索引是否有可能“损坏”?如果是这样,我该怎么做才能解决它?

【问题讨论】:

  • 您能否使用.explain("allPlansExecution") 运行该查询,然后使用整个解释计划输出更新您的问题。基本部分是已选择计划和已拒绝计划部分,因为这些部分将向我们展示 为什么 MongoDB 没有选择 modified_1 索引。此外,这个:“当我使用hint() 时,mongo 会抛出错误错误提示”表明没有您提供给hint() 方法的名称的索引。
  • @glytching 我用结果更新了问题。 (因为我们的数据库版本是 2.6,我必须通过 true。)modified_1 不在 allPlans 中。这是否意味着,即使返回getIndexes,索引也不存在?
  • @Satoko MongoDB 2.6 已被弃用超过 2 年。考虑至少升级到 3.2 版,看看问题是否仍然存在

标签: mongodb indexing


【解决方案1】:

您的索引似乎没有完全在后台构建。您可以使用 db.currentOp() 命令检查这一点:

https://docs.mongodb.com/v3.0/reference/method/db.currentOp/#currentop-index-creation

同时检查 mongod.log 以查看索引构建过程中的任何错误。

修复的简单方法是删除索引并重新创建它

【讨论】:

  • 这是可能的。 (a) bad hint 响应和 (2) 该索引由 getIndexes() 返回的声明之间的不一致强烈表明索引创建过程存在问题。一个相关的建议:如果 OP 正在查询具有最终一致性的副本集并且查询命中辅助节点,那么问题可能是索引没有在 secondary 上成功构建.
  • @glytching 是的。我一直只使用辅助来运行查询。我在主服务器上尝试了explain(),它返回了"cursor" : "BtreeCursor modified_1"。后来主要和次要被切换,导致索引再次建立(?)。现在两者都有并使用索引进行查询。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-25
  • 2022-09-28
  • 2018-02-06
  • 2012-12-09
  • 1970-01-01
相关资源
最近更新 更多