实现效果如下:
当用户输入某个关键词,自动补全用户可能要搜索的关键词。
实现步骤:
一、创建索引时,指定字段类型为:completion,并指定分词器为ik_max_word
http://47.108.200.157:9200/test_completion_index
{
"mappings": {
"properties": {
"id": {
"type": "keyword"
},
"name": {
"type": "keyword",
"fields": {
"suggest": {
"type": "completion",
"analyzer": "ik_max_word"
}
},
"copy_to": "all"
},
"all": {
"type": "keyword"
}
}
}
}
二、插入测试数据
http://47.108.200.157:9200/test_completion_index/_doc/4
{
"name":"中华人民共和国国防部检查室"
}
http://47.108.200.157:9200/test_completion_index/_doc/1
{
"name":"中华人民共和国"
}
http://47.108.200.157:9200/test_completion_index/_doc/2
{
"name":"中华人民共和国国防部"
}
三、查询数据,指定查询的字段:name.suggest,指定匹配的返回数据条数为3。
其中“my_suggest_query”为自定义的查询名称。
{
"suggest": {
"my_suggest_query": {
"prefix": "中华",
"completion": {
"field": "name.suggest",
"size": 3
}
}
}
}
响应结果:
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 0,
"relation": "eq"
},
"max_score": null,
"hits": []
},
"suggest": {
"my_suggest_query": [
{
"text": "中华",
"offset": 0,
"length": 2,
"options": [
{
"text": "中华人民共和国",
"_index": "test_completion_index",
"_type": "_doc",
"_id": "1",
"_score": 1.0,
"_source": {
"name": "中华人民共和国"
}
},
{
"text": "中华人民共和国国防部",
"_index": "test_completion_index",
"_type": "_doc",
"_id": "2",
"_score": 1.0,
"_source": {
"name": "中华人民共和国国防部"
}
},
{
"text": "中华人民共和国国防部检查室",
"_index": "test_completion_index",
"_type": "_doc",
"_id": "4",
"_score": 1.0,
"_source": {
"name": "中华人民共和国国防部检查室"
}
}
]
}
]
}
}