给mapping添加completion类型的字段,completion字段中保存的是一个个的字符串集合,搜索时按照给定的词条进行匹配。
1.创建索引
PUT /test
{
"mappings" : {
"properties":{
"suggestion":{
"type":"completion",
"analyzer":"ik_max_word"
}
}
}
}
2.填入数据
post /test/_doc
{
"suggestion":["中间"]
}
post /test/_doc
{
"suggestion":["中国大陆"]
}
post /test/_doc
{
"suggestion":["中国台湾"]
}
3.查询
GET /test/_search
{
"suggest": {
"testSuggest": {
"text": "中",
"completion": {
"field": "suggestion",
"skip_duplicates":true,
"size":10
}
}
}
}
4.结果
在suggest字段的options中会返回补全的text,后端拿到该数据后返回给前端即可
"suggest" : {
"testSuggest" : [
{
"text" : "中",
"offset" : 0,
"length" : 1,
"options" : [
{
"text" : "中国台湾",
"_index" : "test",
"_type" : "_doc",
"_id" : "FlKziogBKMqiB156c3Do",
"_score" : 1.0,
"_source" : {
"suggestion" : [
"中国台湾"
]
}
},
{
"text" : "中国大陆",
"_index" : "test",
"_type" : "_doc",
"_id" : "FVKziogBKMqiB156a3Di",
"_score" : 1.0,
"_source" : {
"suggestion" : [
"中国大陆"
]
}
},
{
"text" : "中间",
"_index" : "test",
"_type" : "_doc",
"_id" : "FFKziogBKMqiB156ZHCC",
"_score" : 1.0,
"_source" : {
"suggestion" : [
"中间"
]
}
}
]
}
]
}