1、首先创建mapping,注意,在需要建议的field创建一个内部fields,suggest,类型是completion ,因为处理的是中文,所以加了ik中文分词器。
{
"mappings": {
"book": {
"properties": {
"bookAuthor": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
},
"suggest": {
"type": "completion",
"analyzer": "ik_max_word"
}
}
}
}
2、添加数据以后,就可以suggest了
GET book/book/_search
{
"suggest":{
"mysuggest":{
"prefix":"三",
"completion":{
"field":"bookAuthor.suggest"
}
}
}
}
3、这是我es中的响应,注意返回的text字段,就是建议器给出的建议,如果要做搜索提示,可以将多个text封装起来返回给前台展示。
{
"took": 115,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 0,
"max_score": 0,
"hits": []
},
"suggest": {
"mysuggest": [
{
"text": "三",
"offset": 0,
"length": 1,
"options": [
{
"text": "三戒大师",
"_index": "book",
"_type": "book",
"_id": "AWUyRthtLhso7IaOhgG4",
"_score": 1,
"_source": {
"bookAuthor": "三戒大师"
}
},
{
"text": "三毛",
"_index": "book",
"_type": "book",
"_id": "AWUyRthtLhso7IaOhf9W",
"_score": 1,
"_source": {
"bookAuthor": "三毛"
}
]
}
]
}
}