我正在为我的 mongo 数据库帖子集合创建一个自动完成服务,用户可以在其中开始键入帖子的标题。它应该返回标题中包含该关键字的所有帖子,并按名为“总计”的字段排序。
我有一个名为“lower”的字段,它是我们要搜索的标题字段的小写版本,并且在其上设置了索引。由于我正在寻找任何关键字匹配项,因此我正在对 lowerCaseTitle 进行正则表达式搜索,以查找出现在标题中任何位置的单词,而不仅仅是开头。
我查看了执行计划,它看起来像是扫描了每个项目(完整的帖子集合有 10061 个项目)。我试着暗示“lower_1”索引和“total_-1”索引,它们看起来很相似,但如果我将查询的限制数设置为 50,总索引似乎更好,并且 nscanned 数越小。我可以做些什么来优化吗?对于这种全文搜索,我想不出任何简单的方法。
"cursor" : "BtreeCursor lower_1",
"nscanned" : 10061,
"nscannedObjects" : 2,
"n" : 2,
"scanAndOrder" : true,
"millis" : 154,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : false,
"indexOnly" : false,
"indexBounds" : {
"lower" : [
[
"",
{
}
]
]
}
最佳答案
I am doing a regex search against lowerCaseTitle for words that appear anywhere in the title, not just in the beginning.
来自documentation :
For simple prefix queries (also called rooted regexps) like
/^prefix/,
the database will use an index when available and appropriate (much like most SQL databases that use indexes for aLIKE 'prefix%'
expression). This only works if you don't havei
(case-insensitivity) in the flags.
换句话说,不,MongoDB 不支持快速搜索子字符串。
但是,您可以执行以下操作来支持以给定字符串开头的单词:
BlogPost {
Title : "This is furiously interesting post"
TitleSearch : [ "this", "is", "furiously", "interesting", "post" ]
}
现在,使用 TitleSearch
索引并使用有根正则表达式,搜索 'inter'
将返回样本,同样搜索 'furious'
,但不适用于 'eresting'
。
关于mongodb - 有没有办法优化mongo中的自动完成关键字查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9926217/