• mongodb索引


    Note:mongodb的索引算法主要是btree和hash算法,mongodb默认采用的是btree索引算法。

    1、索引

    (a)索引提高查询速度,降低写入速度,权衡常用的查询字段,不必在太多列上建索引
    
    (b)在mongodb中,索引可以按字段升序/降序来创建,便于排序
    
    (c)默认是用btree来组织索引文件,2.4版本以后,也允许建立hash索引.

    2、索引分类

    普通索引({field:1/-1})
    唯一索引({filed.subfield:1/-1}, {unique:true})
    稀疏索引({field:1/-1},{sparse:true})
    哈希索引({file:'hashed'})

    3、常用索引命令:

    #查看查询计划
    db.collection.find(query).explain();
        "cursor" : "BasicCursor", ----说明没有索引发挥作用
        "nscannedObjects" : 1000 ---理论上要扫描多少行
        cursor" : "BtreeCursor sn_1", 用到的btree索引
    eg:db.shop.find({age:33}).explain();
    
    
    #查看当前索引状态
    db.collection.getIndexes();
    eg:db.shop.getIndexes();
    
    #创建普通的单列索引,1是升续 2是降序
    db.collection.ensureIndex({field:1/-1});  
    eg:db.shop.ensureIndex({age:1});
    
    #删除单个索引
    db.collection.dropIndex({filed:1/-1});
    eg:db.shop.dropIndex({age:1});
    
    #删除所有索引
    db.collection.dropIndexes();
    eg:db.shop.dropIndexes();
    
    #创建多列索引  
    db.collection.ensureIndex({field1:1/-1, field2:1/-1});
    eg:db.shop.ensureIndex({age:1,name:1});
    
    #创建子文档索引
    db.collection.ensureIndex({filed.subfield:1/-1});
    eg:db.test.ensureIndex({"feature.age":1})
    #根据子文档索引查找
    eg:db.test.find({"feature.age":22})
    
    #创建唯一索引
    db.collection.ensureIndex({filed.subfield:1/-1}, {unique:true});
    eg:db.test.ensureIndex({name:1},{unique:true})
    
    #创建稀疏索引
    db.collection.ensureIndex({field:1/-1},{sparse:true});
    eg:db.test.ensureIndex({name:1},{sparse:true})
    稀疏索引的特点:如果针对field做索引,针对不含field列的文档,将不建立索引.
    与之相对,普通索引,会把该文档的field列的值认为NULL,并建索引.
    应用场景:小部分文档含有某列时.
    
    #创建哈希索引(2.4新增的)
    db.collection.ensureIndex({file:'hashed'});
    eg:db.test.ensureIndex({name:'hashed'});
    哈希索引速度比普通索引快,但是,无法对范围查询进行优化.
    适宜于:随机性强的散列
    
    #重建索引
    db.collection.reIndex()
    eg:db.test.reIndex();
    一个表经过很多次修改后,导致表的文件产生空洞,索引文件也如此.
    可以通过索引的重建,减少索引文件碎片,并提高索引的效率.
    类似mysql中的optimize table

    后续有应用,将继续补充,同时欢迎大家留言,一起学习、进步。

  • 相关阅读:
    软件设计师考试知识点总结
    HTML和CSS
    JavaScript核心知识点
    操作系统--页面置换算法(缺页数计算)
    中标麒麟系统远程桌面连接
    数据结构 图
    数据结构 二叉树
    MATLAB 大数据剔除坏值
    PTA 邻接表存储图的广度优先遍历(20 分)
    PTA 邻接矩阵存储图的深度优先遍历
  • 原文地址:https://www.cnblogs.com/ywjfx/p/10135346.html
Copyright © 2020-2023  润新知