我有以下全文搜索查询示例:
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);
}
} );
});
最佳答案
在 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 }
关于node.js - MongoDB全文搜索和按相关性排序的多个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25498042/