搜索建議是搜索的一個重要組成部分,一個搜索建議的實現一般須要考慮建議詞的來源、匹配、排序、聚合、關聯的文檔數和拼寫糾錯等,本文介紹一個基於Elasticsearch實現的搜索建議。html
電商網站的搜索是最基礎最重要的功能之一,搜索框上面的良好體驗能爲電商帶來更高的收益,咱們先來看看淘寶、京東、亞馬遜網站的搜索建議。數據庫
在淘寶的搜索框輸入【衛衣】時,下方的搜索建議包括建議詞以及相關的標籤:
緩存
在京東的搜索框輸入【衛衣】時,下方搜索建議右方顯示建議詞關聯的商品數量:
bash
在亞馬遜的搜索框輸入【衛衣】時,搜索建議上部分能支持在特定的分類下進行搜索:
elasticsearch
經過上述對比能夠看出,不一樣的電商對於搜索建議的側重點略有不一樣,但核心的問題包括:ide
在咱們的搜索建議實現裏,主要考慮了建議詞的來源、匹配、排序、關聯的商品數量和拼寫糾錯。post
POST /suggestion/_search
{
"from" : 0,
"size" : 10,
"query" : {
"bool" : {
"must" : {
"bool" : {
"should" : [ {
"prefix" : {
"keyword" : "衛衣"
}
}, {
"prefix" : {
"keyword.keyword_ik" : "衛衣"
}
}, {
"prefix" : {
"keyword.keyword_pinyin" : "衛衣"
}
}, {
"prefix" : {
"keyword.keyword_first_py" : "衛衣"
}
} ]
}
},
"filter" : {
"range" : {
"count" : {
"from" : 5,
"to" : null,
"include_lower" : true,
"include_upper" : true
}
}
}
}
},
"sort" : [ {
"weight" : {
"order" : "desc"
}
}, {
"count" : {
"order" : "desc"
}
} ]
}
複製代碼
POST /suggestion/_search
{
"size" : 0,
"suggest" : {
"keyword_suggestion" : {
"text" : "adidss",
"term" : {
"field" : "keyword",
"size" : 1
}
}
}
}
複製代碼