一、算法介绍
Elasticsearch采取的是TF/IDF算法来评估score的,而score决定了排序。每次搜索score分数越大的越靠前。
1、TF
1.1、概念
Term Frequency简称TF,就是搜索文本中的各个词条在要搜索的field文本中出现的次数,次数越多就越相关。
1.2、举例
比如:
doc1:hello world,I love you
doc2:hello,I love you,too
搜索:hello world,es首先会进行分词建立倒排索引,分词成:hello和world两个单词。
发现doc1匹配了两次,doc2中只匹配了一次(hello),所以doc1的score最大,优先被匹配,会排到doc2前面。
2、IDF
2.1、概念
Inverse Document Frequency简称IDF,就是搜索文本中的各个词条在整个index的所有document中出现的次数,出现的次数越多,越不相关。
2.2、举例
比如
doc1:hello,love you
doc2:hi world,I love you
搜索hello world,es分词器会将其分词成hello和world两个单词
首先hello和world在doc1和doc2中各出现了一次,其次再比如说index有10000条document,hello这个词在10000个document中出现了2000次。world这个词在10000个document中出现了100次。那么doc2更相关,因为他的次数出现的少。
3、补充
3.1、说明
Field-Length Norm:搜索的field对应的内容越长,相关度越弱。
3.2、举例
比如
doc1:{ "title": "hello java", "content": "xxxxxxxxxx1万个单词" }
doc2:{ "title": "Hi java", "content": "xxxxxxxxxx1万个单词,Hi world" }
搜索hello world,es分词器会将其分词成hello和world两个单词
首先hello和world在doc1和doc2中各出现了一次,其次假设在整个index中出现的次数也是一样多的(不像IDF那个案例中那么明显的不一致),则doc1更相关。因为title的内容比content的内容短太多了(短了一万多个单词)。所以doc1会排到doc2前面。
二、Demo演示
1、数据准备
PUT /product/_doc/1
{
"name": "xiaomi shouji",
"desc": "niubi quanwangtong",
"tags": ["niubi", "quanwangtong", "xiaomi", "shouji"]
}
PUT /product/_doc/2
{
"name": "huawei shouji",
"desc": "4G 5G",
"tags": ["shouji"]
}
PUT /product/_doc/3
{
"name": "xiaomi shouhuan",
"desc": "quanzidong",
"tags": ["shengdian", "xiaomi", "shouji"]
}
2、进行搜索
GET /product/_search
{
"query": {
"match": {
"tags": "shouji"
}
}
}
结果是id:2 -> 3 -> 1
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 3,
"relation" : "eq"
},
"max_score" : 0.8847681,
"hits" : [
{
"_index" : "product",
"_type" : "_doc",
"_id" : "2",
"_score" : 0.8847681,
"_source" : {
"name" : "huawei shouji",
"desc" : "4G 5G",
"tags" : [
"shouji"
]
}
},
{
"_index" : "product",
"_type" : "_doc",
"_id" : "3",
"_score" : 0.59321976,
"_source" : {
"name" : "xiaomi shouhuan",
"desc" : "quanzidong",
"tags" : [
"shengdian",
"xiaomi",
"shouji"
]
}
},
{
"_index" : "product",
"_type" : "_doc",
"_id" : "1",
"_score" : 0.50930655,
"_source" : {
"name" : "xiaomi shouji",
"desc" : "niubi quanwangtong",
"tags" : [
"niubi",
"quanwangtong",
"xiaomi",
"shouji"
]
}
}
]
}
}
3、结果分析
先看TF:出现的次数都一样。
再看IDF:很明显id=2的最短,所以分数相对较高,其次是id=3的较短,最后是id=1的。所以TF都一样,IDF对比结果是2 -> 3 -> 1
微信公众号