实现效果如下:
    当用户输入某个关键词,自动补全用户可能要搜索的关键词。
    image.png
    实现步骤:
    一、创建索引时,指定字段类型为:completion,并指定分词器为ik_max_word

    1. http://47.108.200.157:9200/test_completion_index
    2. {
    3. "mappings": {
    4. "properties": {
    5. "id": {
    6. "type": "keyword"
    7. },
    8. "name": {
    9. "type": "keyword",
    10. "fields": {
    11. "suggest": {
    12. "type": "completion",
    13. "analyzer": "ik_max_word"
    14. }
    15. },
    16. "copy_to": "all"
    17. },
    18. "all": {
    19. "type": "keyword"
    20. }
    21. }
    22. }
    23. }

    二、插入测试数据

    1. http://47.108.200.157:9200/test_completion_index/_doc/4
    2. {
    3. "name":"中华人民共和国国防部检查室"
    4. }
    5. http://47.108.200.157:9200/test_completion_index/_doc/1
    6. {
    7. "name":"中华人民共和国"
    8. }
    9. http://47.108.200.157:9200/test_completion_index/_doc/2
    10. {
    11. "name":"中华人民共和国国防部"
    12. }

    三、查询数据,指定查询的字段:name.suggest,指定匹配的返回数据条数为3。
    其中“my_suggest_query”为自定义的查询名称。

    1. {
    2. "suggest": {
    3. "my_suggest_query": {
    4. "prefix": "中华",
    5. "completion": {
    6. "field": "name.suggest",
    7. "size": 3
    8. }
    9. }
    10. }
    11. }

    响应结果:

    1. {
    2. "took": 1,
    3. "timed_out": false,
    4. "_shards": {
    5. "total": 1,
    6. "successful": 1,
    7. "skipped": 0,
    8. "failed": 0
    9. },
    10. "hits": {
    11. "total": {
    12. "value": 0,
    13. "relation": "eq"
    14. },
    15. "max_score": null,
    16. "hits": []
    17. },
    18. "suggest": {
    19. "my_suggest_query": [
    20. {
    21. "text": "中华",
    22. "offset": 0,
    23. "length": 2,
    24. "options": [
    25. {
    26. "text": "中华人民共和国",
    27. "_index": "test_completion_index",
    28. "_type": "_doc",
    29. "_id": "1",
    30. "_score": 1.0,
    31. "_source": {
    32. "name": "中华人民共和国"
    33. }
    34. },
    35. {
    36. "text": "中华人民共和国国防部",
    37. "_index": "test_completion_index",
    38. "_type": "_doc",
    39. "_id": "2",
    40. "_score": 1.0,
    41. "_source": {
    42. "name": "中华人民共和国国防部"
    43. }
    44. },
    45. {
    46. "text": "中华人民共和国国防部检查室",
    47. "_index": "test_completion_index",
    48. "_type": "_doc",
    49. "_id": "4",
    50. "_score": 1.0,
    51. "_source": {
    52. "name": "中华人民共和国国防部检查室"
    53. }
    54. }
    55. ]
    56. }
    57. ]
    58. }
    59. }