Eug*_*nov 21 indexing hint mongodb
如果我使用explain()从shell运行mongo查询,获取所用索引的名称,然后再次运行相同的查询,但是使用hint()指定要使用的相同索引 - 来自explain plan的"millis"字段是显着下降
例如
没有提示:
>>db.event.find({ "type" : "X", "active" : true, "timestamp" : { "$gte" : NumberLong("1317498259000") }, "count" : { "$gte" : 0 } }).limit(3).sort({"timestamp" : -1 }).explain();
{
"cursor" : "BtreeCursor my_super_index",
"nscanned" : 599,
"nscannedObjects" : 587,
"n" : 3,
"millis" : 24,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : true,
"indexOnly" : false,
"indexBounds" : { ... }
}
Run Code Online (Sandbox Code Playgroud)
提示提供:
>>db.event.find({ "type" : "X", "active" : true, "timestamp" : { "$gte" : NumberLong("1317498259000") }, "count" : { "$gte" : 0 } }).limit(3).sort({"timestamp" : -1 }).hint("my_super_index").explain();
{
"cursor" : "BtreeCursor my_super_index",
"nscanned" : 599,
"nscannedObjects" : 587,
"n" : 3,
"millis" : 2,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : true,
"indexOnly" : false,
"indexBounds" : { ... }
}
Run Code Online (Sandbox Code Playgroud)
唯一的区别是"millis"字段
有谁知道为什么会这样?
更新:"选择使用哪个索引"并没有解释它,因为据我所知,mongo为每个X(100?)运行选择索引,所以它应该与下一个提示一样快(X-1)运行
Glo*_*ior 20
Mongo使用算法来确定在没有提供提示时使用哪个索引,然后缓存用于下次1000个调用的类似查询的索引
但是每当你解释一个mongo查询时,它总会运行索引选择算法,因此与没有提示的explain()相比,带有提示的explain()总是花费更少的时间.
在这里回答类似的问题 了解mongo db解释
从扫描对象的数量可以看出,Mongo两次都进行了相同的搜索.您还可以看到使用的索引是相同的(看看"cursor"条目),两者都已经使用了my_super_index索引.
"提示"只告诉Mongo使用它在第一个查询中已自动执行的特定索引.
第二次搜索更简单,因为所有数据可能已经在缓存中.