常见的中文分词器和使用
在上一章介绍了几种默认的分词器的规则和使用,有兴趣的可以参考一下 elasticSearch核心概念的介绍(五):分词器的介绍和使用 在这一章我们介绍常见的中文分词器
为什么要使用中文分词器,我们可以简单来试一下。
-
请求
curl -X POST "http://172.25.45.150:9200/_analyze" -H 'Content-Type:application/json' -d ' { "analyzer":"standard", "text":"火箭明年总冠军" } '
-
响应
{ "tokens": [ { "token": "火", "start_offset": 0, "end_offset": 1, "type": "", "position": 0 }, { "token": "箭", "start_offset": 1, "end_offset": 2, "type": "", "position": 1 }, { "token": "明", "start_offset": 2, "end_offset": 3, "type": "", "position": 2 }, { "token": "年", "start_offset": 3, "end_offset": 4, "type": "", "position": 3 }, { "token": "总", "start_offset": 4, "end_offset": 5, "type": "", "position": 4 }, { "token": "冠", "start_offset": 5, "end_offset": 6, "type": "", "position": 5 }, { "token": "军", "start_offset": 6, "end_offset": 7, "type": "", "position": 6 } ] }
可以看到把每一个中文都进行了分词,我们通常希望它能够以词语等规则进行分词,所以这显然不是我们想要的结果
- smartCN : 一个简单的中文或英文混合文本的分词器(这里不做使用,因为用的比较少)
- IK分词器 更智能更友好的中文分词器
这里我的es是通过docker去安装的,因此有需要的朋友可以参考
Docker安装Elasticsearch和Kibana
版本为7.4.2
安装ik分词器
-
下载 Release v7.4.2 · medcl/elasticsearch-analysis-ik · GitHub尽量保持一致的tag
-
进入挂载目录
cd /mydata/elasticsearch/plugins
-
创建目录
mkdir ik
-
上传ik.zip
-
解压
unzip ./elasticsearch-analysis-ik-7.4.2.zip
-
删除压缩包
rm -rf ./elasticsearch-analysis-ik-7.4.2.zip
-
重启es
docker restart elasticsearch
使用ik分词器
- 请求
curl -X POST http://172.25.45.150:9200/_analyze -H 'Content-Type' -d '
{
"analyzer":"ik_max_word",
"text":"火箭明年总冠军"
}
'
- 响应
{
"tokens": [
{
"token": "火箭",
"start_offset": 0,
"end_offset": 2,
"type": "CN_WORD",
"position": 0
},
{
"token": "明年",
"start_offset": 2,
"end_offset": 4,
"type": "CN_WORD",
"position": 1
},
{
"token": "总冠军",
"start_offset": 4,
"end_offset": 7,
"type": "CN_WORD",
"position": 2
},
{
"token": "冠军",
"start_offset": 5,
"end_offset": 7,
"type": "CN_WORD",
"position": 3
}
]
}
这就我们就能看到ik分词后的效果,达到了我们想要的效果。