分词器主要应用在中文上,在ES中字符串类型有keyword和text两种。
keyword默认不进行分词,
text是将每一个汉字拆开称为独立的词,
这两种都是不适用于生产环境,所以我们需要有其他的分词器帮助我们完成这些事情,其中IK分词器是应用最为广泛的一个分词器。

1)keyword类型的分词

  1. GET _analyze
  2. {
  3. "keyword":"我是程序员"
  4. }
  1. {
  2. "error": {
  3. "root_cause": [
  4. {
  5. "type": "illegal_argument_exception",
  6. "reason": "Unknown parameter [keyword] in request body or parameter is of the wrong type[VALUE_STRING] "
  7. }
  8. ],
  9. "type": "illegal_argument_exception",
  10. "reason": "Unknown parameter [keyword] in request body or parameter is of the wrong type[VALUE_STRING] "
  11. },
  12. "status": 400
  13. }

2)text类型的分词

  1. GET _analyze
  2. {
  3. "text":"我是程序员"
  4. }
  1. {
  2. "tokens": [
  3. {
  4. "token": "我",
  5. "start_offset": 0,
  6. "end_offset": 1,
  7. "type": "<IDEOGRAPHIC>",
  8. "position": 0
  9. },
  10. {
  11. "token": "是",
  12. "start_offset": 1,
  13. "end_offset": 2,
  14. "type": "<IDEOGRAPHIC>",
  15. "position": 1
  16. },
  17. {
  18. "token": "程",
  19. "start_offset": 2,
  20. "end_offset": 3,
  21. "type": "<IDEOGRAPHIC>",
  22. "position": 2
  23. },
  24. {
  25. "token": "序",
  26. "start_offset": 3,
  27. "end_offset": 4,
  28. "type": "<IDEOGRAPHIC>",
  29. "position": 3
  30. },
  31. {
  32. "token": "员",
  33. "start_offset": 4,
  34. "end_offset": 5,
  35. "type": "<IDEOGRAPHIC>",
  36. "position": 4
  37. }
  38. ]
  39. }

3)IK分词器测试

IK提供了两个分词算法ik_smart 和 ik_max_word,
其中 ik_smart 为最少切分,
ik_max_word为最细粒度划分。

1)最少划分ik_smart

  1. GET _analyze
  2. {
  3. "analyzer": "ik_smart",(指定分词器)
  4. "text":"我是程序员"
  5. }
  1. {
  2. "tokens" : [
  3. {
  4. "token" : "我",
  5. "start_offset" : 0,
  6. "end_offset" : 1,
  7. "type" : "CN_CHAR",
  8. "position" : 0
  9. },
  10. {
  11. "token" : "是",
  12. "start_offset" : 1,
  13. "end_offset" : 2,
  14. "type" : "CN_CHAR",
  15. "position" : 1
  16. },
  17. {
  18. "token" : "程序员",
  19. "start_offset" : 2,
  20. "end_offset" : 5,
  21. "type" : "CN_WORD",
  22. "position" : 2
  23. }
  24. ]
  25. }

2)最细切分ik_max_word

  1. GET _analyze
  2. {
  3. "analyzer": "ik_max_word",(指定分词器)
  4. "text":"我是程序员"
  5. }
  1. {
  2. "tokens" : [
  3. {
  4. "token" : "我",
  5. "start_offset" : 0,
  6. "end_offset" : 1,
  7. "type" : "CN_CHAR",
  8. "position" : 0
  9. },
  10. {
  11. "token" : "是",
  12. "start_offset" : 1,
  13. "end_offset" : 2,
  14. "type" : "CN_CHAR",
  15. "position" : 1
  16. },
  17. {
  18. "token" : "程序员",
  19. "start_offset" : 2,
  20. "end_offset" : 5,
  21. "type" : "CN_WORD",
  22. "position" : 2
  23. },
  24. {
  25. "token" : "程序",
  26. "start_offset" : 2,
  27. "end_offset" : 4,
  28. "type" : "CN_WORD",
  29. "position" : 3
  30. },
  31. {
  32. "token" : "员",
  33. "start_offset" : 4,
  34. "end_offset" : 5,
  35. "type" : "CN_CHAR",
  36. "position" : 4
  37. }
  38. ]
  39. }