首页 > 代码库 > Mongodb索引和执行计划 hint 慢查询
Mongodb索引和执行计划 hint 慢查询
查询索引
- 索引存放在system.indexes集合中
- > show tables
- address
- data
- person
- system.indexes
- 默认会为所有的ID建上索引 而且无法删除
- > db.system.indexes.find()
- { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "mydb.person" }
- { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "mydb.address" }
- { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "mydb.data" }
- 单独查询一个集合的索引
- > db.person.getIndexes();
- [
- {
- "v" : 1,
- "key" : {
- "_id" : 1
- },
- "name" : "_id_",
- "ns" : "mydb.person"
- }
- ]
- >
创建索引
- > db.person.find();
- { "_id" : ObjectId("593011c8a92497992cdfac10"), "name" : "xhj", "age" : 30, "address" : DBRef("address", ObjectId("59314b07e693aae7a5eb72ab")) }
- { "_id" : ObjectId("59301270a92497992cdfac11"), "name" : "zzj", "age" : 2 }
- { "_id" : ObjectId("593015fda92497992cdfac12"), "name" : "my second child", "age" : "i do not know" }
- { "_id" : ObjectId("592ffd872108e8e79ea902b0"), "name" : "zjf", "age" : 30, "address" : { "province" : "河南省", "city" : "南阳市", "building" : "桐柏县" } }
- 1升序 -1降序
- > db.person.ensureIndex({age:1});
- {
- "createdCollectionAutomatically" : false,
- "numIndexesBefore" : 1,
- "numIndexesAfter" : 2,
- "ok" : 1
- }
- 可以在集合上创建索引
- > db.person.ensureIndex({address:1});
- {
- "createdCollectionAutomatically" : false,
- "numIndexesBefore" : 2,
- "numIndexesAfter" : 3,
- "ok" : 1
- }
- 复合索引
- > db.person.ensureIndex({name:1,address:1});
- {
- "createdCollectionAutomatically" : false,
- "numIndexesBefore" : 3,
- "numIndexesAfter" : 4,
- "ok" : 1
- }
- 唯一索引:
- > db.person.ensureIndex({name:1},{unique:true});
- {
- "createdCollectionAutomatically" : false,
- "numIndexesBefore" : 4,
- "numIndexesAfter" : 5,
- "ok" : 1
- }
复合索引使用前缀匹配,所以创建复合索引的时候,要把经常会有的部分查询作为前缀。
删除索引:
- 删除一个索引
- > db.person.dropIndex({name:1});
- { "nIndexesWas" : 5, "ok" : 1 }
- 删除所有索引
- > db.person.dropIndexes();
- {
- "nIndexesWas" : 4,
- "msg" : "non-_id indexes dropped for collection",
- "ok" : 1
- }
查看执行计划的方法:explain ()
winningPlan是最终的执行计划 其中的indexBounds索引计划
- 在age上建立索引
- > db.person.ensureIndex({age:1});
- {
- "createdCollectionAutomatically" : false,
- "numIndexesBefore" : 1,
- "numIndexesAfter" : 2,
- "ok" : 1
- }
- > db.person.getIndexes();
- [
- {
- "v" : 1,
- "key" : {
- "_id" : 1
- },
- "name" : "_id_",
- "ns" : "mydb.person"
- },
- {
- "v" : 1,
- "key" : {
- "age" : 1
- },
- "name" : "age_1",
- "ns" : "mydb.person"
- }
- ]
- 查看执行计划 indexBounds可以看到走了age的索引
- > db.person.find({age:30}).explain();
- {
- "queryPlanner" : {
- "plannerVersion" : 1,
- "namespace" : "mydb.person",
- "indexFilterSet" : false,
- "parsedQuery" : {
- "age" : {
- "$eq" : 30
- }
- },
- "winningPlan" : {
- "stage" : "FETCH",
- "inputStage" : {
- "stage" : "IXSCAN",
- "keyPattern" : {
- "age" : 1
- },
- "indexName" : "age_1",
- "isMultiKey" : false,
- "direction" : "forward",
- "indexBounds" : {
- "age" : [
- "[30.0, 30.0]"
- ]
- }
- }
- },
- "rejectedPlans" : [ ]
- },
- "serverInfo" : {
- "host" : "localhost.localdomain",
- "port" : 27017,
- "version" : "3.0.6",
- "gitVersion" : "1ef45a23a4c5e3480ac919b28afcba3c615488f2"
- },
- "ok" : 1
- }
- 没有走索引的计划是这样的
- > db.person.find({name:‘zjf‘}).explain();
- {
- "queryPlanner" : {
- "plannerVersion" : 1,
- "namespace" : "mydb.person",
- "indexFilterSet" : false,
- "parsedQuery" : {
- "name" : {
- "$eq" : "zjf"
- }
- },
- "winningPlan" : {
- "stage" : "COLLSCAN",
- "filter" : {
- "name" : {
- "$eq" : "zjf"
- }
- },
- "direction" : "forward"
- },
- "rejectedPlans" : [ ]
- },
- "serverInfo" : {
- "host" : "localhost.localdomain",
- "port" : 27017,
- "version" : "3.0.6",
- "gitVersion" : "1ef45a23a4c5e3480ac919b28afcba3c615488f2"
- },
- "ok" : 1
- }
强制索引 hint()方法:
- > db.person.ensureIndex({name:1,age:1});
- {
- "createdCollectionAutomatically" : false,
- "numIndexesBefore" : 3,
- "numIndexesAfter" : 4,
- "ok" : 1
- }
- > db.person.getIndexes();
- [
- {
- "v" : 1,
- "key" : {
- "_id" : 1
- },
- "name" : "_id_",
- "ns" : "mydb.person"
- },
- {
- "v" : 1,
- "key" : {
- "age" : 1
- },
- "name" : "age_1",
- "ns" : "mydb.person"
- },
- {
- "v" : 1,
- "key" : {
- "name" : 1
- },
- "name" : "name_1",
- "ns" : "mydb.person"
- },
- {
- "v" : 1,
- "key" : {
- "name" : 1,
- "age" : 1
- },
- "name" : "name_1_age_1",
- "ns" : "mydb.person"
- }
- ]
- //如果不加hint 默认走age上的索引。
- > db.person.find({age:{$gt:0}}).explain();
- {
- "queryPlanner" : {
- "plannerVersion" : 1,
- "namespace" : "mydb.person",
- "indexFilterSet" : false,
- "parsedQuery" : {
- "age" : {
- "$gt" : 0
- }
- },
- "winningPlan" : {
- "stage" : "FETCH",
- "inputStage" : {
- "stage" : "IXSCAN",
- "keyPattern" : {
- "age" : 1
- },
- "indexName" : "age_1",
- "isMultiKey" : false,
- "direction" : "forward",
- "indexBounds" : {
- "age" : [
- "(0.0, inf.0]"
- ]
- }
- }
- },
- "rejectedPlans" : [ ]
- },
- "serverInfo" : {
- "host" : "localhost.localdomain",
- "port" : 27017,
- "version" : "3.0.6",
- "gitVersion" : "1ef45a23a4c5e3480ac919b28afcba3c615488f2"
- },
- "ok" : 1
- }
- //使用hint
- > db.person.find({age:{$gt:0}}).hint({name:1,age:1}).explain();
- {
- "queryPlanner" : {
- "plannerVersion" : 1,
- "namespace" : "mydb.person",
- "indexFilterSet" : false,
- "parsedQuery" : {
- "age" : {
- "$gt" : 0
- }
- },
- "winningPlan" : {
- "stage" : "KEEP_MUTATIONS",
- "inputStage" : {
- "stage" : "FETCH",
- "filter" : {
- "age" : {
- "$gt" : 0
- }
- },
- "inputStage" : {
- "stage" : "IXSCAN",
- "keyPattern" : {
- "name" : 1,
- "age" : 1
- },
- "indexName" : "name_1_age_1",
- "isMultiKey" : false,
- "direction" : "forward",
- "indexBounds" : {
- "name" : [
- "[MinKey, MaxKey]"
- ],
- "age" : [
- "[MinKey, MaxKey]"
- ]
- }
- }
- }
- },
- "rejectedPlans" : [ ]
- },
- "serverInfo" : {
- "host" : "localhost.localdomain",
- "port" : 27017,
- "version" : "3.0.6",
- "gitVersion" : "1ef45a23a4c5e3480ac919b28afcba3c615488f2"
- },
- "ok" : 1
- }
查看执行情况:
- db.person.find({name:‘zjf‘}).explain(‘executionStats‘);
- {
- "queryPlanner" : {
- "plannerVersion" : 1,
- "namespace" : "mydb.person",
- "indexFilterSet" : false,
- "parsedQuery" : {
- "name" : {
- "$eq" : "zjf"
- }
- },
- "winningPlan" : {
- "stage" : "FETCH",
- "inputStage" : {
- "stage" : "IXSCAN",
- "keyPattern" : {
- "name" : 1
- },
- "indexName" : "name_1",
- "isMultiKey" : false,
- "direction" : "forward",
- "indexBounds" : {
- "name" : [
- "[\"zjf\", \"zjf\"]"
- ]
- }
- }
- },
- "rejectedPlans" : [
- {
- "stage" : "FETCH",
- "inputStage" : {
- "stage" : "IXSCAN",
- "keyPattern" : {
- "name" : 1,
- "age" : 1
- },
- "indexName" : "name_1_age_1",
- "isMultiKey" : false,
- "direction" : "forward",
- "indexBounds" : {
- "name" : [
- "[\"zjf\", \"zjf\"]"
- ],
- "age" : [
- "[MinKey, MaxKey]"
- ]
- }
- }
- }
- ]
- },
- "executionStats" : {
- "executionSuccess" : true,
- "nReturned" : 1,
- "executionTimeMillis" : 0,
- "totalKeysExamined" : 1,
- "totalDocsExamined" : 1,
- "executionStages" : {
- "stage" : "FETCH",
- "nReturned" : 1,
- "executionTimeMillisEstimate" : 0,
- "works" : 3,
- "advanced" : 1,
- "needTime" : 0,
- "needFetch" : 0,
- "saveState" : 0,
- "restoreState" : 0,
- "isEOF" : 1,
- "invalidates" : 0,
- "docsExamined" : 1,
- "alreadyHasObj" : 0,
- "inputStage" : {
- "stage" : "IXSCAN",
- "nReturned" : 1,
- "executionTimeMillisEstimate" : 0,
- "works" : 2,
- "advanced" : 1,
- "needTime" : 0,
- "needFetch" : 0,
- "saveState" : 0,
- "restoreState" : 0,
- "isEOF" : 1,
- "invalidates" : 0,
- "keyPattern" : {
- "name" : 1
- },
- "indexName" : "name_1",
- "isMultiKey" : false,
- "direction" : "forward",
- "indexBounds" : {
- "name" : [
- "[\"zjf\", \"zjf\"]"
- ]
- },
- "keysExamined" : 1,
- "dupsTested" : 0,
- "dupsDropped" : 0,
- "seenInvalidated" : 0,
- "matchTested" : 0
- }
- }
- },
- "serverInfo" : {
- "host" : "localhost.localdomain",
- "port" : 27017,
- "version" : "3.0.6",
- "gitVersion" : "1ef45a23a4c5e3480ac919b28afcba3c615488f2"
- },
- "ok" : 1
- }
Mongodb的索引使用的是B-树。
hash索引:
散列索引使用索引字段的值的散列值来维护条目。
散列索引的重要特征是hash后的键值是均匀分布的,索引最适合的是做分片键。
db.collection.createIndex( { _id: "hashed" } )
MongoDB支持任何单个字段的散列索引。 散列函数折叠嵌入文档并计算整个值的散列值,但不支持多键(即数组)索引。
您不得创建具有散列索引字段或在散列索引上指定唯一约束的复合索引; 但是,您可以在同一字段上创建散列索引和升序/降序(即非散列)索引:MongoDB将使用范围查询的标量索引。
警告
MongoDB散列索引在浮动之前将浮点数截断为64位整数。 例如,散列索引将为保持值为2.3,2.2和2.9的字段存储相同的值。 为了防止冲突,不要使用不能可靠地转换为64位整数(然后返回到浮点)的浮点数的散列索引。 MongoDB散列索引不支持大于253的浮点值。
散列索引支持等值查询。
索引大小
为了达到更快的处理效果,请确保您的索引能完整地和内存相适应,这样可以避免从磁盘上读取索引。
可以使用帮助函数 db.collection.totalIndexSize() 来检查索引的大小,返回的数值单位是字节:
> db.collection.totalIndexSize()
4294976499
上述例子展示了一个几乎4.3GB的索引。为了确保索引与内存相适应,您不仅需要有那么多足够可用的内存用于索引,还要有足够的内存用于剩下的 working set 。
稀疏索引
稀疏索引(或者称间隙索引)就是只包含有索引字段的文档的条目,跳过索引键不存在的文档
创建间隙索引示例:
db.addresses.createIndex( { "xmpp_id": 1 }, { sparse: true } )
这个示例,哪些不包含xmpp_id的键(列)的文档将不会被索引
间隙索引不会被使用到的情形
如果一个间隙索引会导致查询或者排序操作得到一个不完整结果集的时候,MongoDB将不会使用这个索引,hint提示除外
如果集合中有大量的数据都不包含该键值,那么应该使用稀疏索引。
覆盖索引:
整个结果集都是从索引中获取。
慢查询分析:
慢查询分析流程:
1.用慢查询日志(system.profile)找到超过200ms的语句
2.然后再通过.explain()解析影响行数,分析为什么超过200ms
3.决定是不是需要添加索引
开启慢查询:
db.setProfilingLevel(1,200)
参数:
- 0:关闭,不收集任何数据。
- 1:收集慢查询数据,默认是100毫秒。
- 2:收集所有数据
查看结果:
db.system.profile.find()
Mongodb索引和执行计划 hint 慢查询