我有一个查询扫描集合以查找结果,我想创建一个索引(或者其他东西)以提高执行速度。
以下是查询的SQL等价物
active=true
AND
exclude_from_search=false
AND
(
full_name_lc like '%buttor%
OR
user_name_lc like '%button%'
OR
first_name_lc like '%button%'
OR last_name_lc like '%button%'
)
AND
group !='Star'
以下是MongoDB查询:
db.user.find({
"active":true,
"exclude_from_search":false,
$or:[
{"full_name_lc":{$regex:"button"}},
{"user_name_lc":{$regex:"button"}},
{"first_name_lc":{$regex:"button"}},
{"last_name_lc":{$regex:"button"}}
],
"group":{$ne:"Star"}
})
提前谢谢你。
答案 0 :(得分:1)
也许制作复合索引就足够了。
db.user.ensureIndex({active : 1, exclude_from_search : 1, group : 1}, {name : "aeg"});
db.user.find({
"active":true,
"exclude_from_search":false,
$or:[
{"full_name_lc":{$regex:"button"}},
{"user_name_lc":{$regex:"button"}},
{"first_name_lc":{$regex:"button"}},
{"last_name_lc":{$regex:"button"}}
],
"group":{$ne:"Star"}
}).explain();
{
"cursor" : "BtreeCursor aeg",
"isMultiKey" : false,
"n" : 0,
"nscannedObjects" : 0,
"nscanned" : 0,
"nscannedObjectsAllPlans" : 0,
"nscannedAllPlans" : 0,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 0,
"indexBounds" : {
"active" : [
[
true,
true
]
],
"exclude_from_search" : [
[
false,
false
]
],
"group" : [
[
{
"$minElement" : 1
},
"Star"
],
[
"Star",
{
"$maxElement" : 1
}
]
]
},
"server" : "xxx",
"filterSet" : false
}
答案 1 :(得分:0)
这是一个众所周知的问题 - 如果你在两边使用野外搜索(...像'%some_string%')你没有其他选择而不是FULL TABLE SCAN(这是一个众所周知的问题 - 你无法创建在这种情况下使用的索引,您将不得不重新考虑逻辑)