【问题标题】:MongoDB full text search and multiple words sorted by relevanceMongoDB全文搜索和按相关性排序的多个单词
【发布时间】:2014-08-26 04:26:50
【问题描述】:

我有以下全文搜索查询示例:

db.collection.find({ $text: { $search: "dog cat" } })

这将返回包含dog OR cat 的文档,但我想按相关性对结果进行排序:

  • 应首先列出包含所有搜索词的结果,
  • 紧随其后的是仅包含一个搜索词的词。

当然,我正在寻找一种同样适用于 3 个或更多搜索词的解决方案。

我发现有一个aggreagation pipeline in MongoDB,可能是太晚了,我的大脑被炸了,但我不知道在这种情况下我该如何使用它。

--- Node.js 和 MongoJS 中的解决方案 ---

为了将所有内容保存在一个地方以供将来参考,Tug Grall 的解决方案在 Node.js / MongoJS 中实现:

.get(function(req, res) {
    db.docs.find({ $text: { $search: req.query.q } }, {score : { $meta: "textScore" } })
    .sort( { score: { $meta: "textScore" } }, function(err, results) {
        if (err) {
            res.send(err);
        } else {
            res.json(results);
        }
    } );
});

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    在 MongoDB 2.6.x 中,您可以在查询中直接在排序中使用 $meta textScore:

    db.docs.find( { $text : {$search : "dog cat"}  } , 
                  {score : { $meta: "textScore" } }   
                 ).sort( { score: { $meta: "textScore" } } )
    

    结果按相关性排序:

     db.docs.find( { $text : {$search : "dogs cat"}  } , 
                    {score : { $meta: "textScore" } }   
                   ).sort( { score: { $meta: "textScore" } } )
    
      { "_id" : "3", "text" : "I like dogs and cats", "score" : 1.3333333333333333 }
      { "_id" : "4", "text" : "I like dogs. But I do not like cats", "score" : 1.25 }
      { "_id" : "1", "text" : "I like dogs", "score" : 0.75 }
      { "_id" : "2", "text" : "I like cats", "score" : 0.75 }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-09
      • 2011-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-02
      相关资源
      最近更新 更多