使用工具robomongo
1.创建索引
db.getCollection('message')..ensureIndex({"name":1})
2.查看已有索引
db.getCollection('message').getIndexes()
3.explain()
db.getCollection('message').find({'retraceId':'aabbcc'}).explain('executionStats')
1) queryPlanner
{
"plannerVersion" : 1,
"namespace" : "local.message",
"indexFilterSet" : false, //针对该query是否有indexfilter
"parsedQuery" : {
"retraceId" : {
"$eq" : "aabbcc"
}
},
"winningPlan" : {
"stage" : "FETCH",//最优执行计划的stage,这里返回是FETCH,可以理解为通过返回的index位置去检索具体的文档
"inputStage" : {
"stage" : "IXSCAN",//此处是IXSCAN,表示进行的是index scanning
"keyPattern" : {
"retraceId" : 1.0
},
"indexName" : "retraceId_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"retraceId" : []
},
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"retraceId" : [
"[\"aabbcc\", \"aabbcc\"]"
]
}
}
},
"rejectedPlans" : []
}
2 对executionStats返回逐层分析
第一层,executionTimeMillis
最为直观explain返回值是executionTimeMillis值,指的是我们这条语句的执行时间,这个值当然是希望越少越好。
其中有3个executionTimeMillis,分别是:
executionStats.executionTimeMillis
该query的整体查询时间。
executionStats.executionStages.executionTimeMillisEstimate
该查询根据index去检索document获得2001条数据的时间。
executionStats.executionStages.inputStage.executionTimeMillisEstimate
该查询扫描2001行index所用时间。
第二层,index与document扫描数与查询返回条目数
这个主要讨论3个返回项,nReturned、totalKeysExamined、totalDocsExamined,分别代表该条查询返回的条目、索引扫描条目、文档扫描条目。
这些都是直观地影响到executionTimeMillis,我们需要扫描的越少速度越快。
对于一个查询,我们最理想的状态是:
nReturned=totalKeysExamined=totalDocsExamined
第三层,stage状态分析
那么又是什么影响到了totalKeysExamined和totalDocsExamined?是stage的类型。类型列举如下:
COLLSCAN:全表扫描
IXSCAN:索引扫描
FETCH:根据索引去检索指定document
SHARD_MERGE:将各个分片返回数据进行merge
SORT:表明在内存中进行了排序
LIMIT:使用limit限制返回数
SKIP:使用skip进行跳过
IDHACK:针对_id进行查询
SHARDING_FILTER:通过mongos对分片数据进行查询
COUNT:利用db.coll.explain().count()之类进行count运算
COUNTSCAN:count不使用Index进行count时的stage返回
COUNT_SCAN:count使用了Index进行count时的stage返回
SUBPLA:未使用到索引的$or查询的stage返回
TEXT:使用全文索引进行查询时候的stage返回
PROJECTION:限定返回字段时候stage的返回
对于普通查询,我希望看到stage的组合(查询的时候尽可能用上索引):
Fetch+IDHACK
Fetch+ixscan
Limit+(Fetch+ixscan)
PROJECTION+ixscan
SHARDING_FITER+ixscan
COUNT_SCAN
不希望看到包含如下的stage:
COLLSCAN(全表扫描),SORT(使用sort但是无index),不合理的SKIP,SUBPLA(未用到index的$or),COUNTSCAN(不使用index进行count)