MongoDB之索引

1.  索引

    1.  默认id索引

        创建集合的时候,会自动在id字段上创建一个唯一索引。该索引不能被删除

    2.  索引名称

        默认名称:索引键和索引中每个键的方向

          在**{ item : 1, quantity: -1 }上创建的索引名称为item_1_quantity_-1**

        自定义名称         

db.products.createIndex(
  { item: 1, quantity: -1 } ,
  { name: "query for inventory" }
)            

    3.  索引类型

        1.  单列索引(在文档的单个字段上创建索引)

            1.  在单个字段上创建索引

                db.student.createIndex({name:1});  在集合student上创建字段name的升序索引

                db.student.createIndex({name:-1});  在集合student上创建字段name的降序索引

            2.  在嵌入式字段上创建索引

                db.student.insert({"name" : "lihaijie","age":{"shisui":30,"xusui":31}});

                db.student.createIndex({"age.shisui":1})  在嵌入式字段上创建索引  

                db.student.find({"age.shisui":30}).explain();  分析可以看到走的是字段索引

            3.  在内嵌文档上创建索引

                db.student.insert({"name" : "lihaijie","age":{"shisui":30,"xusui":31}});

                db.student.createIndex({"age":1})  在内嵌文档上创建索引 

                db.student.find({"age":{ "shisui" : 30, "xusui" : 31 }});  查询条件必须精确才能使用内嵌文档的索引                    

        2.  复合索引(在文档的多个字段上创建索引)

            1.  创建复合索引

                db.student.createIndex({name:1,age:-1});

            2.  排序顺序

                复合索引的顺序很重要

                db.student.find().sort({name:1,age:-1})  使用索引

                db.student.find().sort({name:-1,age:1})  使用索引

                db.student.find().sort({name:1,age:1})  不使用索引

                db.student.find().sort({name:-1,age:-1})  不使用索引

            3.  前缀

                db.student.createIndex({ "item": 1, "location": 1, "stock": 1 });  创建索引

                有效的索引前缀:

                  { item: 1 }

                  { item: 1, location: 1 }                  

                无效的索引前缀:             

                  the location 字段,

                  the stock 字段,

                  the location stock 字段

            4.  复合索引的最佳方式

                精确匹配的字段放最前面

                排序条件放中间

                范围匹配的字段放最后面                                          

        3.  多键索引(索引存储在数组中的内容)

            1.  创建多键索引

                { "_id" : ObjectId("63058a20754135915078aca0"), "name" : "yangjianbo", "love" : [ 300, 128, 66, 102, 89, 58, 38, 30, 20 ] }

                db.student.createIndex({love:1})                       

        4.  地理空间索引

            1.  创建2dsphere索引

                db.collection.createIndex( { <location field> : "2dsphere" } )  

        5.  文本索引

            1.  创建文本索引

                db.student.createIndex({"name":"text"})  在name字段上创建text索引

                一个集合最多可以有一个text索引

        6.  Hashed索引

            Hashed索引使用hashing函数来计算索引字段值的哈希

            1.  创建哈希索引

                db.collection.createIndex( { _id: "hashed" } )   

    4.  索引属性

        1.  唯一索引

            开启unique选项,索引对应字段具有唯一性,对应字段拒绝重复值。除唯一性约束外,在功能上,索引的unique特性可与其他特性交替使用。

            1.  创建唯一索引

                db.student.createIndex({"class":1},{unique:true});  在单个字段上创建唯一索引

                db.student.createIndex({"class":1,"name":1},{unique:true});  复合索引上使用唯一约束            

        2.  部分索引

            对集合中的文档子集创建索引,设置了partial特性的索引将占用更低的存储,并降低mongodb创建索引和维护索引的性能开销。

            1.  创建部分索引               

db.restaurants.createIndex(
   { cuisine: 1, name: 1 },
   { partialFilterExpression: { rating: { $gt: 5 } } }
)

            2.  使用运算符

                $eq

                $exists: true

                $gt,$gte,$lt,$lte

                $type                                              

                $and 只在顶层操作符

            3.  限制

                _id索引不能是部分索引

                分片索引不能是部分索引

        3.  稀疏索引

            索引的 sparse 特性确保只对存在索引字段的文档创建索引。创建索引时将会跳过那些没有对应字段值的文档。

            1.  创建稀疏索引

                db.addresses.createIndex( { "xmpp_id": 1 }, { sparse: true } )

            2.  默认情况下是稀疏索引

                2dsphere,2d,文本索引都是稀疏索引

        4.  TTL索引

            索引的TTL特性,允许MongoDB在一定时间后自动从集合中移除文档。这非常适合某些类型的信息,比如机器生成的事件数据、日志和会话信息

            TTL索引是一种特殊的单字段索引,MongoDB可以使用它在一定的时间或特定的时钟时间后自动从集合中删除文档。 

            1.  创建TTL索引

                db.student.createIndex({"company":1},{expireAfterSeconds:60})

            2.  行为

                1.  TTL索引会在指定的秒数之后使文档过期

                2.  如果索引字段是一个数组,并且有多个日期值,以最低日期值来计算阈值

                3.  索引字段不是date或者日期值的字段或数组,文档不会过期

                4.  如果文档不包含索引字段,文档不会过期

                5.  删除过期文档的后台任务每60秒运行一次

            3.  限制

                1.  TTL索引是单字段索引。复合索引不支持TTL

                2.  _id字段不支持TTL索引

                3.  如果某个字段已经存在非TTL单字段索引,则无法再同一字段上创建TTL索引

2.  管理索引                                    

    1.  查看集合所有索引

        db.student.getIndexes();

    2.  查看数据库的所有索引

db.getCollectionNames().forEach(function(collection) {
   indexes = db[collection].getIndexes();
   print("Indexes for " + collection + ":");
   printjson(indexes);
}); 

    3.  删除指定索引

        db.collection.dropIndex()

        db.collection.dropIndexes()  支持数组

    4.  删除集合中所有索引

        db.collections.dropIndexes();    

        2.  查看集合总索引大小

            db.student.totalIndexSize();  单位字节

        3.  读取当前集合的所有index信息

            db.student.reIndex();

    5.  重建索引

3.  衡量索引

    1.  使用$indexStats度量索引使用

        db.student.aggregate([{$indexStats:{}}])  获取集合中每个索引的使用情况的统计信息

    2.  使用explain()返回查询计划

        db.student.find({"class":1}).explain(true)

        返回的结果:使用的索引,扫描的文档数量以及查询处理所用的时间(以毫秒为单位)

    3.  使用hint()控制索引使用

        db.student.find({"class":1}).hint({_id:1}).explain()

4.  索引策略

    1.  创建索引来支持查询

    2.  使用索引对查询结果进行排序

    3.  确保索引适合RAM

    4.  创建以确保选择性的查询                                  

posted @ 2022-08-29 17:49  奋斗史  阅读(331)  评论(0)    收藏  举报