推荐工具
RoboMongo
推荐书目
50 Tips and Tricks for MongoDB Developers
Related Blogs
Snail in a Turtleneck
mikulch
V2EX  ›  MongoDB

关于 MongoDB/mysql 数据库复合索引原理的一个小问题。

  •  
  •   mikulch · Nov 7, 2016 · 4045 views
    This topic created in 3550 days ago, the information mentioned may be changed or developed.

    最近买了一本 MongoDB 权威指南第二版,看到大概第五章左右。

    书里面提到一个概念, MongoDB 中建立了复合索引如{username:1,age:1,email:1}以后,

    使用{usernam:lily,age:20}的查询可以被索引优化,而使用{age:20}或者{age:20,email:[email protected]}的查询却不能被索引所优化。

    总而言之,必须使用索引前缀或者完全使用索引覆盖的查询才能被优化。

    想了一晚上,实在想不明白为什么。

    有没有高人帮忙用简明易懂的话告诉我一下其中的原理。

    谢谢了!

    6 replies    2016-11-07 16:41:39 +08:00
    mikulch
        1
    mikulch  
    OP
       Nov 7, 2016
    顺便为啥我昨晚 1 点发的帖子被吞了??

    ???
    yidinghe
        2
    yidinghe  
    PRO
       Nov 7, 2016 via Android
    我猜原因是,索引的原理是二叉树,复合索引的 key 不过是各个 key 拼起来而已,所以查找的时候的 key 如果是按照索引规则来的(哪怕只是前缀),也能在树中进行查找,否则就不行了。
    rahuahua
        3
    rahuahua  
       Nov 7, 2016
    看看 B(各种变形)的数据结构,然后想想在你建的索引下{age:20}这个查询能不能做到快速查询
    rahuahua
        4
    rahuahua  
       Nov 7, 2016
    @rahuahua 更正下
    看看 B 树(以及各种变形)的数据结构,然后想想在你建的索引下{age:20}这个查询能不能做到快速查询
    ihuotui
        5
    ihuotui  
       Nov 7, 2016
    @yidinghe 是的
    pippo
        6
    pippo  
       Nov 7, 2016
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5424 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 08:42 · PVG 16:42 · LAX 01:42 · JFK 04:42
    ♥ Do have faith in what you're doing.