1、简介
它就像是一本书的目录,如果没有它,我们就需要对整个书籍进行查找来获取需要的结果,即所说的全盘扫描;
而有了目录(索引)之后就可以通过它帮我们定位到目标所在的位置,快速的获取我们想要的结果。
2、演示
第一步,向用户集合users中插入100W条数据
var insertUsers = function() { var start = new Date().getTime(); for (var i = 1; i <= 1000000; i++) { db.users.insert({ "userid": i, "username": "wjg" + i, "age": Math.floor(Math.random() * 100), //年龄为0~99的随机整数 "createdate": new Date() }) } var end = new Date().getTime(); print("插入100W条数据共耗时" + (end - start) / 1000 + "秒"); }</div>
LZ的渣渣I3和4G内存总共耗时了484.623秒,约8分多钟。任务管理器里边可以很清楚的看到当时CPU、内存和磁盘使用率都普遍的增高。
第二步:查询用户名为“wjg465413”的文档对象
db.users.find({username:"wjg465413"}).explain("allPlansExecution") { "queryPlanner" : { "plannerVersion" : 1, "namespace" : "test.users", "indexFilterSet" : false, "parsedQuery" : { "username" : { "$eq" : "wjg465413" } }, "winningPlan" : { "stage" : "COLLSCAN", "filter" : { "username" : { "$eq" : "wjg465413" } }, "direction" : "forward" }, "rejectedPlans" : [ ] }, "executionStats" : { "executionSuccess" : true, "nReturned" : 1, "executionTimeMillis" : 865, "totalKeysExamined" : 0, "totalDocsExamined" : 1000000, "executionStages" : { "stage" : "COLLSCAN", "filter" : { "username" : { "$eq" : "wjg465413" } }, "nReturned" : 1, "executionTimeMillisEstimate" : 770, "works" : 1000002, "advanced" : 1, "needTime" : 1000000, "needFetch" : 0, "saveState" : 7813, "restoreState" : 7813, "isEOF" : 1, "invalidates" : 0, "direction" : "forward", "docsExamined" : 1000000 }, "allPlansExecution" : [ ] }, "serverInfo" : { "host" : "Jack", "port" : 27017, "version" : "3.0.3", "gitVersion" : "b40106b36eecd1b4407eb1ad1af6bc60593c6105" }, "ok" : 1 }</div>
说明:这里的explain方法相当于查询计划,它会返回给你查询过程的详细信息。它的参数有三种模式:“queryPlanner”(查询计划[默认])、“executionStats”(执行状态)和“allPlansExecution”(所有执行计划),这里我们只关注它返回给我们的以下几个信息。
"executionTimeMillis" : 865 //执行的毫秒数 注:如果你是第一次执行,可能会花费更长的时间 "totalDocsExamined" : 1000000 //共检查的文档数</div>
第三步:在用户名“username”字段上加上索引
db.users.createIndex({ "username" : 1 })</div>
重新执行上次的查询操作
db.users.find({username:"wjg465413"}).explain("allPlansExecution") { "queryPlanner" : { "plannerVersion" : 1, "namespace" : "test.users", "indexFilterSet" : false, "parsedQuery" : { "username" : { "$eq" : "wjg465413" } }, "winningPlan" : { "stage" : "FETCH", "inputStage" : { "stage" : "IXSCAN", "keyPattern" : { "username" : 1 }, "indexName" : "username_1", "isMultiKey" : false, "direction" : "forward", "indexBounds" : { "username" : [ "[\"wjg465413\", \"wjg465413\"]" ] } } }, "rejectedPlans" : [ ] }, "executionStats" : { "executionSuccess" : true, "nReturned" : 1, "executionTimeMillis" : 53, "totalKeysExamined" : 1, "totalDocsExamined" : 1, "executionStages" : { "stage" : "FETCH", "nReturned" : 1, "executionTimeMillisEstimate" : 0, "works" : 2, "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" : { "username" : 1 }, "indexName" : "username_1", "isMultiKey" : false, "direction" : "forward", "indexBounds" : { "username" : [ "[\"wjg465413\", \"wjg465413\"]" ] }, "keysExamined" : 1, "dupsTested" : 0, "dupsDropped" : 0, "seenInvalidated" : 0, "matchTested" : 0 } }, "allPlansExecution" : [ ] }, "serverInfo" : { "host" : "Jack", "port" : 27017, "version" : "3.0.3", "gitVersion" : "b40106b36eecd1b4407eb1ad1af6bc60593c6105" }, "ok" : 1 }</div>
可以看到两次的查询计划有很大的差别,我们还是着重看下那两个属性值。
"executionTimeMillis" : 53 //执行的毫秒数 "totalDocsExamined" : 1 //共检查的文档数</div>
加过索引之后查询这个文档所耗费的时间仅仅为53毫秒,并且扫描一次直接定位,性能提升了16倍。可见合理使用索引的重要性!
注:“_id”字段是Mongo为我们默认添加的索引,而且是唯一索引,保证了数据的唯一性,不可以移除。另外,使用limit(1)限制查询结果的数量也可以提高查询速度
3、索引的类型
a)、单一索引:可以在数据集上任意一个字段上建立索引,包括普通的属性键、内嵌文档以及内嵌文档中的属性键。
db.users.createIndex({ "username" : 1 }) //普通属性键的索引 //假设class是一个内嵌的文档 db.users.createIndex({ "class" : 1 }) //内嵌文档的索引 db.users.createIndex({ "class.classname" : 1 }) //内嵌文档中的属性键索引</div>
索引方向:1表示升序,-1表示降序
b)、复合索引:以多个属性键为基础而建立得索引
db.users.createIndex({ "username" : 1, "age" : -1, "userid" : 1 }) //在“username”、“age”和“userid”上建立复合索引</div>
索引前缀:通过建立上边的复合索引之后,Mongo就相当于同时拥有了三个索引一样,分别是{"username" : 1},{"username" : 1, "age" : -1}和{"username" : 1, "age" : -1, "userid" : 1},但是像{"age" : -1},{"userid" : 1}或者{"age" : -1, "userid" : 1}这三个索引并不会起作用。所以它会使用包含了前缀(首个)的索引的作为复合索引
c)、多键索引:为数组中的多个值建立索引以实现高效查询。