es在创建倒排索引时需要对文档分词;在搜索时,需要对用户输入内容分词。但默认的分词规则对中文处理并不友好。

我们在kibana的DevTools中测试:

  1. POST /_analyze
  2. {
  3. "text": "黑马程序员学习Java太棒了",
  4. "analyzer": "standard"
  5. }
  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. "token" : "学",
  40. "start_offset" : 5,
  41. "end_offset" : 6,
  42. "type" : "<IDEOGRAPHIC>",
  43. "position" : 5
  44. },
  45. {
  46. "token" : "习",
  47. "start_offset" : 6,
  48. "end_offset" : 7,
  49. "type" : "<IDEOGRAPHIC>",
  50. "position" : 6
  51. },
  52. {
  53. "token" : "java",
  54. "start_offset" : 7,
  55. "end_offset" : 11,
  56. "type" : "<ALPHANUM>",
  57. "position" : 7
  58. },
  59. {
  60. "token" : "太",
  61. "start_offset" : 11,
  62. "end_offset" : 12,
  63. "type" : "<IDEOGRAPHIC>",
  64. "position" : 8
  65. },
  66. {
  67. "token" : "棒",
  68. "start_offset" : 12,
  69. "end_offset" : 13,
  70. "type" : "<IDEOGRAPHIC>",
  71. "position" : 9
  72. },
  73. {
  74. "token" : "了",
  75. "start_offset" : 13,
  76. "end_offset" : 14,
  77. "type" : "<IDEOGRAPHIC>",
  78. "position" : 10
  79. }
  80. ]
  81. }

语法说明: POST:请求方式 /_analyze:请求路径,这里省略了http://ip:9200,有kibana帮我们补充 请求参数,json风格: analyzer:分词器类型,这里是默认的standard分词器 text:要分词的内容


IK分词器

处理中文分词,一般会使用IK分词器。

ik分词器包含两种模式:

  • ik_smart:最少切分,粗粒度
  • ik_max_word:最细切分,细粒度

安装分词器ik

下载分词版本,解压到挂在目录plugins,然后重启es服务
image.png


ik分词器-拓展词库

image.png
image.png