ES 实现自动补全功能

发布时间:2025-12-10 11:35:56 浏览次数:11

新建索引

PUT /hot_search_index{"mappings": {"properties": {"title":{"type": "text","analyzer": "ik_max_word", "fields": {"keyword":{"type":"completion"}}}}}}

新建一个 热点搜索索引 hot_search_index,包含一个字段 title,使用 ik_max_word 分词,它有一个子字段,类型是 completion

插入数据

插入三条数据:

  • 台铁丧生司机曾躲过另一列车事故。
  • 台湾铁路事故。
  • 专家解释国内疫情不严重为何打疫苗。
  • POST /hot_search_index/_doc{"title":"台铁丧生司机曾躲过另一列车事故"}POST /hot_search_index/_doc{"title":"台湾铁路事故"}POST /hot_search_index/_doc{"title":"专家解释国内疫情不严重为何打疫苗"}

    搜索

    普通分词查询

    POST /hot_search_index/_search{"query": {"match": {"title": "列车"}}}

    自动补全,搜索以“”开头的,能1和2搜出两条数据。

    POST /hot_search_index/_search{"suggest": {"song-suggest": {"prefix": "台","completion": {"field": "title.keyword"}}}}
    需要做网站?需要网络推广?欢迎咨询客户经理 13272073477