zoukankan      html  css  js  c++  java
  • 【赵强老师】MongoDB中的索引(下)

    (四)索引的类型三:复合索引(Compound Index)

    MongoDB支持复合索引,即将多个键组合到一起创建索引。该方式称为复合索引,或者也叫组合索引,该方式能够满足多键值匹配查询使用索引的情形。其次复合索引在使用的时候,也可以通过前缀法来使用索引。MongoDB中的复合索引与关系型数据库基本上一致。在关系型数据库中复合索引使用的一些原则同样适用于MongoDB。

    在前面的内容中,我们已经在emp集合上创建了一个复合索引,如下:

    db.emp.createIndex({"deptno":1,"sal":-1})
    
    

    下面使用不同的过滤条件查询文档,查看相应的执行计划:

    (1)仅使用deptno作为过滤条件

    db.emp.find({"deptno":10}).explain()
    
    

    (2)使用deptno、sal作为过滤条件

    db.emp.find({"deptno":10,"sal":3000}).explain()
    
    

    (3)使用deptno、sal作为过滤条件,但把sal放在前面

    db.emp.find({"sal":3000,"deptno":10}).explain()
    
    

    (4)仅使用sal作为过滤条件

    db.emp.find({"sal":3000}).explain()
    
    

    (五)复合索引与排序

    复合索引创建时按升序或降序来指定其排列方式。对于单键索引,其顺序并不是特别重要,因为MongoDB可以在任一方向遍历索引。对于复合索引,按何种方式排序能够决定该索引在查询中能否被使用到。

    db.emp.createIndex({"deptno":1,"sal":-1})
    
    

    在前面的内容中,我们已经在deptno上按照升序、sal上按照降序建立了复合索引,下面测试不同的排序的下,是否执行了索引:

    使用了索引的情况:
    db.emp.find().sort({"deptno":1,"sal":-1}).explain()
    db.emp.find().sort({"deptno":-1,"sal":1}).explain()
    
    没有使用索引的情况:
    db.emp.find().sort({"deptno":1,"sal":1}).explain()
    db.emp.find().sort({"deptno":-1,"sal":-1}).explain()
    
    交换两个列的位置,再进行测试。
    
    

    (六)复合索引与索引前缀

    索引前缀指的是复合索引的子集,假如存在如下索引:

    db.emp.createIndex({"deptno":1,"sal":-1,"job":1})
    
    那么就存在以下的索引前缀:
    {"deptno":1}
    {"deptno":1,"sal":-1}
    
    

    在MongoDB中,下列查询过滤条件情形中,索引将会被使用到:

    db.emp.find().sort({deptno:1,sal:-1,job:1}).explain()
    db.emp.find().sort({deptno:1,sal:-1}).explain()
    db.emp.find().sort({deptno:1}).explain()
    
    

    下列查询过滤条件情形中,索引将不会被使用到:

    db.emp.find().sort({deptno:1,job:1}).explain()
    db.emp.find().sort({sal:-1,job:1}).explain()
    
    

    (七)小结

    • 复合索引是基于多个键(列)上创建的索引
    • 复合索引在创建的时候可以为其每个键(列)来指定排序方法
    • 索引键列的排序方法影响查询在排序时候的操作,方向一致或相反的才能被匹配
    • 复合索引与前缀索引通常在匹配的情形下才能被使用

  • 相关阅读:
    redis 键命令
    redis 数据类型
    java向word写入数据
    Eclipse发布到tomcat提示java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
    Unable to locate Spring NamespaceHandler for XMLschemanamespace http://dubbo.apache.org/schema/dubbo
    5.Dubbo之Spring XML配置
    6.Dubbo之XML配置详解。
    7.Dubbo之最佳实践
    RESTful API实践
    Jav程序执行Linux命令
  • 原文地址:https://www.cnblogs.com/collen7788/p/14158454.html
Copyright © 2011-2022 走看看