美文网首页我爱编程
「Mongo」索引优先级的问题

「Mongo」索引优先级的问题

作者: HughDong | 来源:发表于2018-05-13 22:28 被阅读0次

    在MongoDB复合索引的情况下,写在前面的字段优先级更高,直接影响查询速度。

    我的数据库结构是集合 test 中有爬虫数据,字段结构基本相同。

    { 
        "_id" : ObjectId(), 
        "source" : "hhnsh",      // 区分数据来源
        "date" : "2001-01-01",   // 通过日期排序
        "title" : "",
        "url" : "", 
        "content" : "", 
        "category" : "", 
        "file" : []
    }
    

    其中A来源有6w+条,BC来源2000+条,DE来源40条。
    在查询的过程中遇到的问题是:查询200条,按时间降序的情况下,ABCDE来源的查询速度递减
    查询语句:

    db.test.find({source:'A'}).sort({date:-1}).skip(0).limit(200)
    

    查询速度却差距很大,排查的过程中重建了数据库索引也没有效果,最后在索引的问题上又看了文档,发现MongoDB的索引是有优先级的区分,修改索引字段的顺序后速度都正常了。

    原先建立的索引 db.test.createIndex({date:-1,source:-1}) 下的查询速度:

    GET /details/A 200  90.984 ms - 1468581
    GET /details/B 200 118.387 ms - 968471
    GET /details/B 200 118.387 ms - 968471
    GET /details/D 200 390.227 ms - 176346
    GET /details/D 200 361.100 ms - 340138
    GET /details/E 304 408.459 ms - -
    
    

    更改顺序后创建索引 db.test.createIndex({source:-1,date:-1}) 下的查询速度:

    GET /details/A 304 53.698 ms - -
    GET /details/B 304 40.173 ms - -
    GET /details/C 200 38.075 ms - 1079150
    GET /details/D 304 9.126 ms - -
    GET /details/E 304 14.450 ms - -
    

    官方文档中是这样说的:

    MongoDB also supports user-defined indexes on multiple fields, i.e. compound indexes.
    The order of fields listed in a compound index has significance. For instance, if a compound index consists of { userid: 1, score: -1 }, the index sorts first by userid and then, within each userid value, sorts by score.
    MongoDB还支持多个字段上定义的索引,即复合索引。
    字段的顺序列在一个复合指数的意义。
    例如,如果一个复合指数由{ userid:1,score:1 },该指数排序首先userid,然后在每个用户id值,排序sorce。

    相关文章

      网友评论

        本文标题:「Mongo」索引优先级的问题

        本文链接:https://www.haomeiwen.com/subject/wgsrdftx.html