mongodb - 有没有办法优化mongo中的自动完成关键字查询

标签 mongodb

我正在为我的 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 a LIKE 'prefix%' expression). This only works if you don't have i (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/

相关文章:

javascript - 如何立即执行 mongoose 查询并使用 Promise.all 等待它们?

mongodb - AWS DocumentDB 是否支持在单个查询中加入 3 个以上的集合?

mongodb - mongodb 中相同的查询具有不同的执行时间

java - 如何在mongo查询java驱动程序中执行$or和 "and"?

ruby-on-rails - 以 Rails 形式处理 MongoMapper EmbeddedDocument

javascript - MapReduce 的误解。

python - 如果元素不存在(无重复),则将元素推送到数组

mongodb - 左连接 mongodb laravel

linux - 编辑 .conf 文件以将新 Ip 添加到 bindIp 后无法启动 mongodb

node.js - Mongoose 4 个套接字关闭