2017-06-13 42 views
0

我會爲每個線程的註釋模型,爲此查詢創建索引的策略是什麼?

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

我的本意這裏是找到與線程相關的註釋,然後獲得結果的一部分。看起來這個查詢按預期工作。我的問題是:

  1. 這是否符合我的要求?

  2. 如何正確索引字段?這是一個複合索引,或者我需要單獨索引每個字段?我檢查了explain()的結果,似乎只要其中一個查詢字段包含索引,inputStage.stage將始終有IXSCAN而不是COLLSCAN?這是檢查查詢性能的關鍵信息嗎?

  3. 這是否意味着每次我需要根據一個字段來查找時,我需要爲這些字段進行索引?假設我想搜索作者發佈到特定線程的所有評論。

這樣的代碼:

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

我需要爲此創造需求的複合索引?

回答

1

如果要查詢多個字段,則必須創建複合索引

例如

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

如果要使用此查詢,那麼你必須創建這樣的複合索引:

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

然後就是,指數支持在查詢有關該項目現場以及作爲產品和庫存字段:

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

+0

感謝您的回答!我的問題是複合索引中的一個字段是一個已經是索引的ObjectID?我是否需要將它們添加爲複合索引,或者我只需要將另一個添加爲單獨的索引?謝謝:) –

+0

據我所知,如果在應用查詢後,您已經添加了一個單一索引,然後添加了一個複合索引使用單個索引字段和複合索引字段組合,那麼這將不起復合索引的作用。所以你必須將它們添加爲複合索引。 –