当前位置: 移动技术网 > IT编程>数据库>MongoDB > MongoDB的索引

MongoDB的索引

2017年12月08日  | 移动技术网IT编程  | 我要评论

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 + "秒");
}

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
}

说明:这里的explain方法相当于查询计划,它会返回给你查询过程的详细信息。它的参数有三种模式:“queryplanner”(查询计划[默认])、“executionstats”(执行状态)和“allplansexecution”(所有执行计划),这里我们只关注它返回给我们的以下几个信息。

"executiontimemillis" : 865 //执行的毫秒数 注:如果你是第一次执行,可能会花费更长的时间
"totaldocsexamined" : 1000000  //共检查的文档数

第三步:在用户名“username”字段上加上索引

db.users.createindex({ "username" : 1 }) 

重新执行上次的查询操作

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
}

可以看到两次的查询计划有很大的差别,我们还是着重看下那两个属性值。

 "executiontimemillis" : 53  //执行的毫秒数

 "totaldocsexamined" : 1  //共检查的文档数

加过索引之后查询这个文档所耗费的时间仅仅为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 })  //内嵌文档中的属性键索引

索引方向:1表示升序,-1表示降序

b)、复合索引:以多个属性键为基础而建立得索引

db.users.createindex({ "username" : 1, "age" : -1, "userid" : 1 })  //在“username”、“age”和“userid”上建立复合索引

索引前缀:通过建立上边的复合索引之后,mongo就相当于同时拥有了三个索引一样,分别是{"username" : 1},{"username" : 1, "age" : -1}和{"username" : 1, "age" : -1, "userid" : 1},但是像{"age" : -1},{"userid" : 1}或者{"age" : -1, "userid" : 1}这三个索引并不会起作用。所以它会使用包含了前缀(首个)的索引的作为复合索引

c)、多键索引:为数组中的多个值建立索引以实现高效查询。

注:ⅰ、不允许在多个数组上建立复合索引

  ⅱ、不能指定片键作为多键索引

  ⅲ、哈希索引不能是多键

  ⅳ、多键索引不支持覆盖查询

d)、地理空间索引和查询:mongo提供了两种曲面类型的索引:2dsphere索引和2d索引。查询类型包括:包含(inclusion),交叉(intersection)和接近(proximity)

e)、文本索引:用来支持查询包含了字符串或者字符串数组的文档

db.users.createindex({"username" : "text"})

注:文本索引不支持排序并且一个复合文本索引不能再包含其他任何索引了

f)、哈希索引:它可以在使用了哈希片键进行分片的数据集上进行索引,支持相等查询,但是不支持范围查询

 db.users.createindex({"username" : "hashed"})

4、索引特性

a)、ttl(time-to-live)索引:是一种具有生命周期的索引,它允许为每一个文档设置一个超时时间

 db.users.createindex({ "createdate" : 1 },{ "expireaftersecs" : 60*60*24 }) 

说明:在“createdate”字段上建立一个ttl索引,当这个自段存在并且是日期类型,当服务器时间比“createdate”字段的时间晚60*60*24秒,即24小时时,文档就会被删除

b)、唯一索引:确保集合的每一个文档的指定键都有唯一值

db.users.createindex({"username" : 1}, {"unique" : true})

c)、稀疏索引:mongo里边的null会被看做值,如果有一个可能存在也可能不存在的字段,我们可以使用稀疏索引

db.users.createindex({"age" : 1},{"sparse" : true})

4、索引操作

a)、查看所有索引

db.users.getindexes()

b)、移除索引

db.users.dropindex({"createdate1" : 1 })

c)、移除所有索引

db.users.dropindexes()

d)、重建索引

db.users.reindex()

说明:该操作会先删除所有索引,包括“_id”,然后重新创建所有索引

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网