【问题标题】:What's the strategy for creating index for this query?为这个查询创建索引的策略是什么?
【发布时间】:2017-11-15 02:31:48
【问题描述】:

我对每个线程都有一个评论模型,

const CommentSchema = new mongoose.Schema({
    author: { type: ObjectID, required: true, ref: 'User' },
    thread: { type: ObjectID, required: true, ref: 'Thread' },
    parent: { type: ObjectID, required: true, ref: 'Comment' },
    text: { type: String, required: true },
}, {
    timestamps: true,
});

除了通过_id进行单个查询外,我想通过这种方式查询数据库:

范围查询

const query = {
    thread: req.query.threadID,
    _id: { $gt: req.query.startFrom }
};

CommentModel.find(query).limit(req.query.limit);

我的目的是找到与线程相关的 cmets,然后获取部分结果。看来此查询按预期工作。我的问题是:

  1. 这是满足我要求的正确方法吗?

  2. 如何正确索引字段?这是一个复合索引还是我需要单独索引每个字段?我检查了explain() 的结果,似乎只要其中一个查询字段包含索引,inputStage.stage 将始终有IXSCAN 而不是COLLSCAN?这是检查查询性能的关键信息吗?

  3. 是不是每次需要根据一个字段进行查找,都需要为这些字段做一个索引?假设我要搜索作者发布到特定线程的所有 cmets。

这样的代码:

const query = {
    thread: req.query.threadID,
    author: req.query.authorID,
};

我是否需要为此要求创建复合索引?

【问题讨论】:

    标签: mongodb indexing mongoose


    【解决方案1】:

    如果要按多个字段查询,则必须创建复合索引

    例如

    const query = {
        thread: req.query.threadID,
        author: req.query.authorID,
    };
    

    如果您想使用此查询,则必须创建复合索引,例如:

    db.comments.createIndex( { "thread": 1, "author": 1 } );
    

    也就是说,索引支持对 item 字段以及 item 和 stock 字段的查询:

    db.comments.find( { thread: "threadName" } )
    db.comments.find( { thread: "threadName", author: "authorName" } 
    

    但不支持这个

    db.comments.find( { author: "authorName", thread: "threadName" } 
    

    如果您为{ "thread": 1, "author": 1, "parent": 1 } 创建索引,那么为波纹管有序查询支持索引

    thread 字段,

    thread 字段和author 字段,

    thread 字段和author 字段和parent 字段。

    但是不支持下面的顺序

    author 字段,

    parent 字段,或

    authorparent 字段。

    For more read this

    【讨论】:

    • 感谢您的回答!我的问题是复合索引中的一个字段是一个已经是索引的 ObjectID 呢?我需要将它们添加为复合索引还是只需将另一个添加为单独的索引?谢谢:)
    • 据我所知,当您使用单个索引字段和复合索引字段组合应用查询时,如果您已经添加了一个单一索引,然后添加了一个复合索引,那么这将无法用作复合索引。所以你必须将它们添加为复合索引。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    相关资源
    最近更新 更多