搜索補全功能使用的是es的completion suggester實現 官方文檔地址:https://www.elastic.co/guide/en/elasticsearch/reference/current/search-suggesters-completion.htmlhtml
先設置mapping:app
POST /index/completion/_mapping { "properties":{ "title": { "type": "text", "analyzer": "ik_sync_smart" }, "title_suggest": { "type": "completion", "analyzer": "ik_sync_smart", "search_analyzer": "ik_sync_smart" } } }
重點是title_suggest,這個字段就是以後咱們搜索補全的字段,須要設置type爲completion,analyzer按狀況設置分析器elasticsearch
索引數據:ide
POST /index/completion/_bulk { "index" : { } } { "title": "背景天安門廣場大學", "title_suggest": "背景天安門廣場大學"} { "index" : { } } { "title": "北京天安門","title_suggest": "北京天安門"} { "index" : { } } { "title": "北京鳥巢","title_suggest": "北京鳥巢"} { "index" : { } } { "title": "奧林匹克公園","title_suggest": "奧林匹克公園"} { "index" : { } } { "title": "奧林匹克森林公園","title_suggest": "奧林匹克森林公園"} { "index" : { } } { "title": "北京奧林匹克公園","title_suggest": "北京奧林匹克公園"} { "index" : { } } { "title": "北京奧林匹克公園","title_suggest": {"input": "我愛中國","weight": 100}}
索引的時候能夠對suggest字段,增長weight增長排序權重ui
搜索補全:code
POST /index/completion/_search { "size": 0, "suggest": { "blog-suggest": { "prefix": "北京", "completion": { "field": "title_suggest" } } } } 返回: { "took": 27, "timed_out": false, "_shards": { "total": 3, "successful": 3, "skipped": 0, "failed": 0 }, "hits": { "total": 0, "max_score": 0, "hits": [] }, "suggest": { "blog-suggest": [ { "text": "北京", "offset": 0, "length": 2, "options": [ { "text": "北京天安門", "_index": "jzbsearch", "_type": "completion", "_id": "AWK9FJDeGCbNhyb_l9I6", "_score": 1, "_source": { "title": "北京天安門", "title_suggest": "北京天安門" } }, { "text": "北京奧林匹克公園", "_index": "jzbsearch", "_type": "completion", "_id": "AWK9FJDeGCbNhyb_l9I-", "_score": 1, "_source": { "title": "北京奧林匹克公園", "title_suggest": "北京奧林匹克公園" } }, { "text": "北京鳥巢", "_index": "jzbsearch", "_type": "completion", "_id": "AWK9FJDeGCbNhyb_l9I7", "_score": 1, "_source": { "title": "北京鳥巢", "title_suggest": "北京鳥巢" } } ] } ] } }
參考連接: https://elasticsearch.cn/article/142 https://www.elastic.co/guide/en/elasticsearch/reference/current/search-suggesters-completion.htmlhtm