2017-09-08 50 views
0

我想从蒙戈更相关的结果全文搜索相关的结果,让我们说,我有这个收藏计算在MongoDB中

{ "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 } 

我怎么知道前两个有我搜索的所有文本?

谁计算得分?

回答

1

评分算法是MongoDB的内部函数,应该可能会随着时间的推移而改变,所以精确值应该没有关系。如果你愿意的话,你可以试着去了解发生了什么事情(尽管我不推荐这么做)。

最终得分取决于您搜索的词语(或者他们的词干)的出现次数,比赛之间的距离,比赛质量(完全匹配还是部分),语言设置和权重,您可以configure 。这些都是很难记录的很重要的东西。然而,有一篇博客文章很好地解释了一些方面:https://blog.codecentric.de/en/2013/01/text-search-mongodb-stemming/ 此外,一旦您尝试使用搜索词和索引数据的不同组合的各种查询,事情会变得更加清晰。

最后,如果你想找出是否有一个完美的比赛,我能想到的唯一办法,使这项工作是这样的:

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 
    } 
})