使用ElasticSearch实现检索词补全功能

需求说明
系统是基于ES进行检索,在输入检索内容时,需要自动补全后续内容,例如输入【危害】,会自动提示【危害国家安全、危害民众安全】等信息;
这里使用ElasticSearch提供的Completion Suggester功能;
创建字典索引
需要创建个字典索引,用于获取检索补全字段,字典索引存入的内容为和检索内容相关的信息;

PUT /word_suggest
{
  
}

配置字典索引
由于检索内容为中文,需要配置索引为ik分词,同时需要指定一个completion字段,该字段就是用于检索补全字段的

POST /word_suggest/_doc/_mapping
{
  "properties":{
    "ay": {
      "type": "text",
      "analyzer": "ik_smart"
    },
    "ay_suggest": {
      "type": "completion",
      "analyzer": "ik_smart",
      "search_analyzer": "ik_smart"
    }
  }
}

查找检索补全字段

POST /word_suggest/_doc/_search
{ "size": 0,
  "suggest": {
    "word-suggest": {
      "prefix": "妨害",
      "completion": {
        "size":5,
        "field": "ay_suggest"
      }
    }
  }
}

注意,size是指返回检索词补全词的数量
返回信息

{
  "took" : 2,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : 0,
    "max_score" : 0.0,
    "hits" : [ ]
  },
  "suggest" : {
    "word-suggest" : [
      {
        "text" : "妨害",
        "offset" : 0,
        "length" : 2,
        "options" : [
          {
            "text" : "妨害传染病防治罪",
            "_index" : "word_suggest",
            "_type" : "_doc",
            "_id" : "XSLBU2wB395bxDYHz0KK",
            "_score" : 1.0,
            "_source" : {
              "ay_suggest" : "妨害传染病防治罪",
              "ay" : "妨害传染病防治罪"
            }
          },
          {
            "text" : "妨害作证罪",
            "_index" : "word_suggest",
            "_type" : "_doc",
            "_id" : "UCLBU2wB395bxDYHy0JQ",
            "_score" : 1.0,
            "_source" : {
              "ay_suggest" : "妨害作证罪",
              "ay" : "妨害作证罪"
            }
          },
          {
            "text" : "妨害信用卡管理罪",
            "_index" : "word_suggest",
            "_type" : "_doc",
            "_id" : "I5PBU2wB0JRN9nVotC93",
            "_score" : 1.0,
            "_source" : {
              "ay_suggest" : "妨害信用卡管理罪",
              "ay" : "妨害信用卡管理罪"
            }
          },
          {
            "text" : "妨害公务罪",
            "_index" : "word_suggest",
            "_type" : "_doc",
            "_id" : "SJPBU2wB0JRN9nVoxC9t",
            "_score" : 1.0,
            "_source" : {
              "ay_suggest" : "妨害公务罪",
              "ay" : "妨害公务罪"
            }
          },
          {
            "text" : "妨害动植物防疫、检疫罪",
            "_index" : "word_suggest",
            "_type" : "_doc",
            "_id" : "apPBU2wB0JRN9nVo0S8I",
            "_score" : 1.0,
            "_source" : {
              "ay_suggest" : "妨害动植物防疫、检疫罪",
              "ay" : "妨害动植物防疫、检疫罪"
            }
          }
        ]
      }
    ]
  }
}

你可能感兴趣的:(使用ElasticSearch实现检索词补全功能)