我已经创建了我的收集提供了以下指标:MongoDB的查询不会对复合索引使用前缀文本字段
db.myCollection.createIndex({
user_id: 1,
name: 'text'
})
如果我尝试看看包含这两个字段的查询的执行计划,这样:
db.getCollection('campaigns').find({
user_id: ObjectId('xxx')
,$text: { $search: 'bla' }
}).explain('executionStats')
我得到如下结果:
...
"winningPlan" : {
"stage" : "TEXT",
"indexPrefix" : {
"user_id" : ObjectId("xxx")
},
"indexName" : "user_id_1_name_text",
"parsedTextQuery" : {
"terms" : [
"e"
],
"negatedTerms" : [],
"phrases" : [],
"negatedPhrases" : []
},
"inputStage" : {
"stage" : "TEXT_MATCH",
"inputStage" : {
"stage" : "TEXT_OR",
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"user_id" : 1.0,
"_fts" : "text",
"_ftsx" : 1
},
"indexName" : "user_id_1_name_text",
"isMultiKey" : true,
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 1,
"direction" : "backward",
"indexBounds" : {}
}
}
}
}
...
正如documentation指出, MongoDB可以使用索引前缀来执行索引查询。
由于user_id
是该指数的前缀之上,我预计,只有user_id
查询将使用索引,但如果我尝试以下方法:
db.myCollection.find({
user_id: ObjectId('xxx')
}).explain('executionStats')
我得到:
...
"winningPlan" : {
"stage" : "COLLSCAN",
"filter" : {
"user_id" : {
"$eq" : ObjectId("xxx")
}
},
"direction" : "forward"
},
...
因此,它根本没有使用索引并执行完整的集合扫描。
所以,基本上这里的解决方案,因为我需要两个查询,将有2个索引:1个单独包含'user_id',另一个包含'{user_id,name}'? –
@HenriqueBarcelos是的,你需要'user_id'上的单独索引。这可能是另一个非稀疏复合索引的前缀。 – Stennie