ElasticSearch 中文分词插件ik 的使用

2023-05-22,,

下载

IK 的版本要与 Elasticsearch 的版本一致,因此下载 7.1.0 版本。

安装

1、中文分词插件下载地址:https://github.com/medcl/elasticsearch-analysis-ik

2、拼音分词插件下载地址:https://github.com/medcl/elasticsearch-analysis-pinyin

下载你对应的版本

将解压后的 IK 文件夹,放入 elasticsearch 文件夹下的 plugins/ik 目录下。

启动 Elasticsearch 后,看到下图,表示启动成功。

扩展本地词库

在 plugins\ik\config\custom 目录下新增文件 hotwords.dic。如添加 洪荒之力 。每一个词语一行。

在 plugins\ik\config 文件夹下的 IKAnalyzer.cfg.xml 文件配置本地词库。

<!--用户可以在这里配置自己的扩展字典,如果多个字典,则用分号分隔 custom/mydict.dic;custom/single_word_low_freq.dic-->
<entry key="ext_dict">custom/hotwords.dic</entry>

重新启动 Elasticsearch 显示如下图,表示启动成功。

文档的中文分词使用

IK分词器有两种分词模式:ik_max_word和ik_smart模式。

1、ik_max_word

会将文本做最细粒度的拆分,比如会将“中华人民共和国人民大会堂”拆分为“中华人民共和国、中华人民、中华、华人、人民共和国、人民、共和国、大会堂、大会、会堂等词语。

2、ik_smart
会做最粗粒度的拆分,比如会将“中华人民共和国人民大会堂”拆分为中华人民共和国、人民大会堂。

下面我们分别测试下。
先测试ik_max_word,输入命令如下:

POST http://localhost:9200/_analyze
{
"analyzer": "ik_max_word",
"text": "世界如此之大"
}

响应结果如下:

{
"tokens": [
{
"token": "世界",
"start_offset": ,
"end_offset": ,
"type": "CN_WORD",
"position":
},
{
"token": "如此之",
"start_offset": ,
"end_offset": ,
"type": "CN_WORD",
"position":
},
{
"token": "如此",
"start_offset": ,
"end_offset": ,
"type": "CN_WORD",
"position":
},
{
"token": "之大",
"start_offset": ,
"end_offset": ,
"type": "CN_WORD",
"position":
}
]
}

再测试ik_smart,输入命令如下:

POST http://localhost:9200/_analyze
{
"analyzer": "ik_smart",
"text": "世界如此之大"
}

响应结果如下:

{
"tokens": [
{
"token": "世界",
"start_offset": ,
"end_offset": ,
"type": "CN_WORD",
"position":
},
{
"token": "如此",
"start_offset": ,
"end_offset": ,
"type": "CN_WORD",
"position":
},
{
"token": "之大",
"start_offset": ,
"end_offset": ,
"type": "CN_WORD",
"position":
}
]
}

通过Docker 安装elasticsearch-analysis-ik-6.4.5插件

FROM docker.elastic.co/elasticsearch/elasticsearch:6.4.5
ADD elasticsearch-analysis-ik-6.4.5 /usr/share/elasticsearch/plugins/elasticsearch-analysis-ik-6.4.5

这里我将elasticsearch-analysis-ik-6.4.5.zip 下载都解压到了Dockerfile同目录下的elasticsearch-analysis-ik-6.4.5目录中,然后通过ADD指令将elasticsearch-analysis-ik-6.4.5目录拷贝到了docker中elasticsearch的plugins目录。

ElasticSearch 中文分词插件ik 的使用的相关教程结束。

《ElasticSearch 中文分词插件ik 的使用.doc》

下载本文的Word格式文档,以方便收藏与打印。