What's the strategy for creating index for thi

2019-09-14 17:31发布

问题:

I have a comment model for each thread,

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,
});

Besides a single query via _id, I want to query the database via this way:

Range query

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

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

My intention here is to find comments which related to a thread then get part of the result. It seems this query works as expected. My questions are:

  1. Is this the right way to fulfill my requirement?

  2. How to proper index the fields? Is this a compound index or I need to separate indexing each field? I checked the result of explain(), it seems as long as one of the query fields contains an index, the inputStage.stage will always have IXSCAN rather than COLLSCAN? Is this the key information to check the performace of the query?

  3. Does it mean that every time I need to find based on one field, I need to make an index for these fields? Let's say that I want to search all the comments that are posted by an author to a specific thread.

Code like this:

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

Do I need to create a compound index for this requirement?

回答1:

If you want to query by multiple fields then you have to create compound index.

for example

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

if you want to use this query then you have to create compound index like :

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

Then that is, the index supports queries on the item field as well as both item and stock fields:

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

but not supports this one

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

say if you create index for { "thread": 1, "author": 1, "parent": 1 } then for bellow ordered query support index

the thread field,

the thread field and the author field,

the thread field and the author field and the parent field.

But not support for bellow order

the author field,

the parent field, or

the author and parent fields.

For more read this