默认情况下,Elasticsearch根据相关性评分(_score)对匹配的搜索结果进行排序,相关性评分衡量每个文档与查询的匹配程度。虽然每种查询类型可以计算不同的相关性得分,但得分计算也取决于查询子句是在查询还是过滤器上下文中运行。
在ElasticSearch 2.X~5.X中默认使用的是TF/IDF算法计算相关性,5.X以后默认使用BM25算法。在7.X版本中不再使用TF/IDF算法。目前,我使用的版本为7.10.1,只支持BM25算法和boolean算法。
BM25
目前ES默认的相似性度量算法为BM25,具体公式为:

该公式为文档ddd对于查询QQQ的相似性评分:
- nnn 为查询分词总数(例如查询
this is a test的话就是有4个分词this,is,a,test) - NNN 为文档总数
- qiq_{i}qi 为查询的第iii个分词
- n(qi)n(q_{i})n(qi) 为包含qiq_{i}qi的文档数
- fif_{i}fi 为分词qiq_{i}qi在文档ddd中出现的频率
- k1k_{1}k1 为调节因子,默认为
1.2 - bbb 为调节因子,默认为
0.75 - dldldl 为文档ddd的长度
- avgdlavgdlavgdl 为所有文档长度的平均值
测试
为了证明公式的准确性,我将公式用python代码实现。
首先ES中添加4条文档:
curl -X DELETE "localhost:9200/my_index?pretty"
curl -X PUT "localhost:9200/my_index?pretty" -H 'Content-Type: application/json' -d'
{ "settings": { "number_of_shards": 1 }}
'
curl -X POST "localhost:9200/my_index/my_type/_bulk?pretty" -H 'Content-Type: application/json' -d'
{ "index": { "_id": 1 }}
{ "title": "The quick brown fox" }
{ "index": { "_id": 2 }}
{ "title": "The quick brown fox jumps over the lazy dog" }
{ "index": { "_id": 3 }}
{ "title": "The quick brown fox jumps over the quick dog" }
{ "index": { "_id": 4 }}
{ "title": "Brown fox brown dog" }
'
每个文档的title字段值分别为如下所示:
The quick brown fox
The quick brown fox jumps over the lazy dog
The quick brown fox jumps over the quick dog
Brown fox brown dog
查询如下所示:
curl -X GET "localhost:9200/my_index/my_type/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"match_phrase": {
"title":"quick"
}
}
}
'
得到结果:
"title" : "The quick brown fox jumps over the quick dog"
"_score" : 0.4425555,
"title" : "The quick brown fox"
"_score" : 0.423274,
"title" : "The quick brown fox jumps over the lazy dog"
"_score" : 0.30818442,
如下代码为该查询和第一条匹配文档(The quick brown fox jumps over the quick dog)的相关度计算。nq代表n(qi)n(q_{i})n(qi)(包含qiq_{i}qi的文档数);N代表NNN(文档总数);fi代表fif_{i}fi(分词qiq_{i}qi在文档ddd中出现的频率);dl和avdl代表dldldl和avgdlavgdlavgdl;k1和b代表k1k_{1}k1和bbb
import math
nq = [3]
N = 4
fi = [2]
dl = 9
avdl = (9+4+9+4)/4
k1 = 1.2
b = 0.75
def SCORE():
rtn_score = 0.0
for i in range(len(nq)):
rtn_score = rtn_score + IDF(i)*R(i)
return rtn_score
def IDF(i):
return math.log((N-nq[i]+0.5)/(nq[i]+0.5)+1)
def R(i):
return (fi[i]*(k1+1))/(fi[i]+k1*(1-b+b*(dl/avdl)))
print(SCORE())
经计算得结果0.4425554618936116与ES计算结果相同。
本文介绍了ElasticSearch中的默认相似性度量算法BM25,并提供了相关性的数学公式。通过测试,验证了使用Python实现的BM25公式与ElasticSearch的计算结果一致。
1917

被折叠的 条评论
为什么被折叠?



