1. 程式人生 > 其它 >Elasticsearch 論壇實戰-使用most_fields策略進行cross-fields search弊端揭祕

Elasticsearch 論壇實戰-使用most_fields策略進行cross-fields search弊端揭祕

技術標籤:Elasticsearch實戰elasticsearch

Elasticsearch實戰

cross-fields搜尋 一個唯一標識,跨了多個field。比如一個人,標識,是姓名;一個建築,它的標識是地址。姓名可以散落在多個field中,比如first_name和last_name中,地址可以散落在country,province,city中。

跨多個field搜尋一個標識,比如搜尋一個人名,或者一個地址,就是cross-fields搜尋

初步來說,如果要實現,可能用most_fields比較合適。因為best_fields是優先搜尋單個field最匹配的結果,cross-fields本身就不是一個field的問題了。

準備資料

POST /forum/post/_bulk
{ "index": { "_id": "1"} }
{ "first_name" : "Peter", "last_name" : "Smith" }
{ "index": { "_id": "2"} }
{ "first_name" : "Smith", "last_name" : "Williams" }
{ "index": { "_id": "3"} }
{ "first_name" : "Jack", "last_name" : "Ma" }
{ "index": { "_id": "4"} }
{ "first_name" : "Robbin", "last_name" : "Li" }
{ "index": { "_id": "5"} }
{ "first_name" : "Tonny", "last_name" : "Peter Smith" }

查詢

GET /forum/post/_search
{
  "query": {
    "multi_match": {
      "query": "Peter Smith",
      "type": "most_fields",  
      "fields": ["first_name","last_name"]
    }
  }
}

#! Deprecation: [types removal] Specifying types in search requests is deprecated.

{
"took" : 6,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 3,
"relation" : "eq"
},
"max_score" : 2.3258216,
"hits" : [
{
"_index" : "forum",
"_type" : "post",
"_id" : "1",
"_score" : 2.3258216,
"_source" : {
"first_name" : "Peter",
"last_name" : "Smith"
}
},
{
"_index" : "forum",
"_type" : "post",
"_id" : "5",
"_score" : 1.7770997,
"_source" : {
"first_name" : "Tonny",
"last_name" : "Peter Smith"
}
},
{
"_index" : "forum",
"_type" : "post",
"_id" : "2",
"_score" : 1.3862942,
"_source" : {
"first_name" : "Smith",
"last_name" : "Williams"
}
}
]
}
}

問題

Peter Smith,匹配author_first_name,匹配到了Smith,這時候它的分數很高,為什麼啊???
因為IDF分數高,IDF分數要高,那麼這個匹配到的term(Smith),在所有doc中的出現頻率要低,author_first_name field中,Smith就出現過1次
Peter Smith這個人,doc 1,Smith在author_last_name中,但是author_last_name出現了兩次Smith,所以導致doc 1的IDF分數較低

不要有過多的疑問,一定是這樣嗎?這個恐怕只有ES評分演算法核心人員才清楚了……

弊端

問題1:只是找到儘可能多的field匹配的doc,而不是某個field完全匹配的doc

問題2:most_fields,沒辦法用minimum_should_match去掉長尾資料,就是匹配的特別少的結果

問題3:TF/IDF演算法,比如Peter Smith和Smith Williams,搜尋Peter Smith的時候,由於first_name中很少有Smith的,所以query在所有document中的頻率很低,得到的分數很高,可能Smith Williams反而會排在Peter Smith前面

歡迎諮詢公眾號《小馬JAVA》