在mongodb中计算全文搜索的相关结果

在mongodb中计算全文搜索的相关结果,mongodb,full-text-search,Mongodb,Full Text Search,我正试图从mongo获得更相关的结果,比如说我有这个系列 { "text" : "mitsubishi lancer 2011"} { "text" : "mitsubishi lancer 2011"} { "text" : "mitsubishi lancer 2011 in good conditions"} { "text" : "lancer 2011"} { "text" : "mitsubishi lancer 2014"} { "text" : "lancer 2016"} 然

我正试图从mongo获得更相关的结果,比如说我有这个系列

{ "text" : "mitsubishi lancer 2011"}
{ "text" : "mitsubishi lancer 2011"}
{ "text" : "mitsubishi lancer 2011 in good conditions"}
{ "text" : "lancer 2011"}
{ "text" : "mitsubishi lancer 2014"}
{ "text" : "lancer 2016"}
然后进行此查询

db.post.find({$text: {$search: "mitsubishi lancer 2011"}}, {score: {$meta: "textScore"}}).sort({score:{$meta:"textScore"}})
我得到这个结果

{ "text" : "mitsubishi lancer 2011", "score" : 2 }
{ "text" : "mitsubishi lancer 2011", "score" : 2 }
{ "text" : "mitsubishi lancer 2011 in good conditions", "score" : 1.7999999999999998 }
{ "text" : "lancer 2011", "score" : 1.5 }
{ "text" : "mitsubishi lancer 2014", "score" : 1.3333333333333333 }
{ "text" : "lancer 2016", "score" : 0.75 }
我如何知道前两个有我搜索的所有文本


谁来计算分数?

评分算法是MongoDB的内部算法,可能会随着时间的推移而改变,因此准确的数值应该无关紧要。如果您愿意,您可以通过查看来尝试了解发生了什么(尽管我不建议这样做)

最终分数取决于搜索词(或者更确切地说是词干)的出现次数、匹配之间的距离、匹配质量(完全匹配与部分匹配)、语言设置以及您可以选择的权重。这些都是很重要的东西,很难记录下来。然而,有一篇博文很好地解释了一些方面: 此外,一旦您尝试使用不同的搜索词和索引数据组合进行各种查询,事情就会变得更加清楚

最后,如果你想知道是否有一个完美的匹配,我能想到的唯一方法是这样做:

db.getCollection('test').aggregate(
{
    // do the normal filtering query
    $match: {
        $text: {
            $search: "mitsubishi lancer 2011"
        }
    }
}, {
    // select what's relevant in the output and add an indicator "perfectmatch"
    $project: {
        "text": 1,
        "score": {
            $meta: "textScore"
        },
        "perfectmatch": {
            $cond: [
                { $eq: [ "$text", "mitsubishi lancer 2011" ] }, // this would check for a perfect match using the exact full string, for individual token matching you would need to do tokenize your query and do a series of other checks here.
                true,
                false
            ]
        }
    }
}, {
    // if you want to have the results sorted by "best match first"
    $sort: {
        "score": -1
    }
})