【问题标题】:Searching in MongoDB在 MongoDB 中搜索
【发布时间】:2014-10-20 10:04:21
【问题描述】:

假设您需要在 MongoDB 中实现搜索。 您的文档集合如下所示:

{text: "This is some Text }
{text: "this is another text hehe"}

现在您要实现不区分大小写的搜索,该搜索将返回所有包含搜索词的文档。例如,如果您搜索“文本”,它将返回两个文档。如果你搜索“hehe”,它只会返回第二个文档。

我知道你可以像这样使用 $regex 来做到这一点:

db.comments.find({text: {$regex: /.*SEARCH_TERM.*/i}});

SEARCH_TERM 是我们要查找的术语。

我想知道是否有更好的方法来做到这一点,因为通过正则表达式搜索似乎是个坏主意。没有索引或任何这种方式。

我的想法是你可以以某种方式标记文档中的文本,所以你会有这样的文档:

{text: ["This", "is", "some", "Text"]}
{text: ["this", "is", "another", "text", "hehe"]}

然后索引这些数组。有没有更好的方法来做到这一点?

【问题讨论】:

    标签: mongodb full-text-search nosql


    【解决方案1】:

    也许全文搜索就是你的答案 http://docs.mongodb.org/manual/core/index-text/ http://docs.mongodb.org/manual/reference/operator/query/text/

    来自这些参考的代码 sn-ps:

    1 - db.comments.ensureIndex( { comments: "text" } )
    

    以下代码搜索包含词 Thisanother 但不包含词 hehe 的 cmets:

    2- db.comments.find( { $text: { $search: "This another -hehe" } } )
    

    【讨论】:

      【解决方案2】:

      做一个 Map Reduce 可能会很有趣:

      mapper=function(){
          var words=this.text.match(/\S+\s*/g);
          for (w in words){
              emit(this._id, {'words':words})
          }
      }
      
      reducer=function(k,v){return {'words':this[0].words}}
      

      这应该会为您提供一个将单词分开的集合。可能有一种方法可以通过聚合来做到这一点。

      【讨论】:

        猜你喜欢
        • 2012-11-29
        • 2019-03-18
        • 1970-01-01
        • 2013-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-14
        相关资源
        最近更新 更多