分词器是将一段文本,按照一定逻辑,拆分成多个词语的一种工具
    image.png

    1. #分词效果验证
    2. GET _analyze
    3. {
    4. "text": "我爱黑马程序员",
    5. "analyzer": "standard"
    6. }

    分词结果:
    image.png
    ElasticSearch 内置分词器对中文很不友好,处理方式为:一个字一个词。

    IK分词器
    词条查询: term:
    词条查询不会对查询条件进行分词,只有当查询字符串和倒排索引中的词条完全匹配时才匹配搜索
    全文查询:match
    全文查询会对查询条件进行分词,然后将分出的词分别取倒排索引中进行词条的匹配,求结果并集

    1. PUT person/_doc/1
    2. {
    3. "name": "张三",
    4. "age": 20,
    5. "address": "广东天河区"
    6. }
    7. PUT person/_doc/2
    8. {
    9. "name": "李四",
    10. "age": 19,
    11. "address": "广东黄浦区"
    12. }
    13. PUT person/_doc/3
    14. {
    15. "name": "王五",
    16. "age": 19,
    17. "address": "广东越秀区"
    18. }
    19. PUT person/_doc/4
    20. {
    21. "name": "王五",
    22. "age": 19,
    23. "address": "华为5G手机"
    24. }

    image.png
    1.执行term搜索:

    1. #term查询,查询的关键字必须和词条完全匹配
    2. GET person/_search
    3. {
    4. "query": {
    5. "term": {
    6. "address": {
    7. "value": "广东"
    8. }
    9. }
    10. }
    11. }

    查询结果如下
    image.png

    1. 可以发现查询结果为空,因为我们之前在添加文档时,并没有指定字段使用哪种分词器,它会默认使用standard单字分词器,将address的内容分成一个个字来和文档建立倒排索引。因此如果我们查询的关键字如果是“广”、“东”这样一个个字就可以查询到结果,如下所示::::

    image.png
    实际项目中,我们查询一般是按照一个个词来进行查询,所以如果使用standard分词器,查询效果并不好,因此我们在创建索引之初一般会指定需要分词的字段的分词器是ik分词器,我们删除person索引库并进行重建,脚本如下:

    1. #删除索引库
    2. DELETE person
    3. #创建索引库并指定映射
    4. PUT person
    5. {
    6. "mappings": {
    7. "_doc":{
    8. "properties": {
    9. "age": {
    10. "type": "integer"
    11. },
    12. "name": {
    13. "type": "keyword"
    14. },
    15. "address": {
    16. "type": "text",
    17. "analyzer": "ik_max_word"
    18. }
    19. }
    20. }
    21. }
    22. }
    23. # 再重新添加文档
    24. PUT person/_doc/1
    25. {
    26. "name": "张三",
    27. "age": 20,
    28. "address": "广东天河区"
    29. }
    30. PUT person/_doc/2
    31. {
    32. "name": "李四",
    33. "age": 19,
    34. "address": "广东黄浦区"
    35. }
    36. PUT person/_doc/3
    37. {
    38. "name": "王五",
    39. "age": 19,
    40. "address": "广东越秀区"
    41. }
    42. PUT person/_doc/4
    43. {
    44. "name": "王五",
    45. "age": 19,
    46. "address": "华为5G手机"
    47. }

    这时候我们再来搜索关键字“广东”就搜索到结果了,我们可以根据ES提供的分词验证接口,验证广东天河区的分出了哪些词,如下所示:
    image.png
    2.执行match搜索

    1. GET person/_search
    2. {
    3. "query": {
    4. "match": {
    5. "address": "广东天河"
    6. }
    7. }
    8. }

    查询结果如下:
    image.png
    为什么可以查询出来呢?虽然索引库里并没有”广东天河”这个词,但是match搜索会将查询条件,也就是”广东天河”先分词,分词算法同样是使用ik_max_word,我们来验证一下看看分词效果:
    image.png