安装 Elasticsearch IK 分词器(手动 .zip/.zip 安装)
IK 分词器(IK Analysis)是 Elasticsearch 最常用的中文分词插件,支持 细粒度分词(ik_max_word) 和 智能切分(ik_smart)。以下是详细安装步骤:
1. 下载 IK 分词器
方式 1:直接下载预编译版本(推荐)
访问 IK Releases,选择 与 Elasticsearch 版本匹配 的插件包,例如:
bash
# 示例:ES 8.13.0 对应的 IK 版本
wget https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v8.13.0/elasticsearch-analysis-ik-8.13.0.zip
方式 2:源码编译(适用于自定义词典)
bash
git clone https://github.com/medcl/elasticsearch-analysis-ik.git
cd elasticsearch-analysis-ik
git checkout v8.13.0 # 切换到对应版本分支
mvn clean package # 编译(需 Maven 和 JDK)
编译后,在 target/releases/
目录下生成 .zip
文件。
2. 安装 IK 插件到 Elasticsearch
(1)创建插件目录
bash
cd /usr/local/elasticsearch/plugins
sudo mkdir ik
sudo unzip elasticsearch-analysis-ik-8.13.0.zip -d ik/
sudo chown -R elasticsearch:elasticsearch ik/ # 确保权限正确
(2)验证安装
bash
# 查看已安装插件
/usr/local/elasticsearch/bin/elasticsearch-plugin list
输出应包含:
plaintext
analysis-ik
3. 重启 Elasticsearch
bash
# 如果使用 systemd
sudo systemctl restart elasticsearch
# 如果手动运行
ps -ef | grep elasticsearch # 找到进程 ID
kill -9 <PID> # 停止
/usr/local/elasticsearch/bin/elasticsearch -d # 后台启动
4. 测试 IK 分词器
(1)创建测试索引
bash
curl -XPUT "http://localhost:9200/ik_test" -H "Content-Type: application/json" -d'
{
"settings": {
"analysis": {
"analyzer": {
"ik_analyzer": {
"type": "custom",
"tokenizer": "ik_max_word"
}
}
}
}
}'
(2)测试分词效果
bash
curl -XGET "http://localhost:9200/ik_test/_analyze" -H "Content-Type: application/json" -d'
{
"analyzer": "ik_max_word",
"text": "中华人民共和国"
}'
正常输出:
json
{
"tokens": [
{"token": "中华人民共和国", "start_offset": 0, "end_offset": 7, "type": "CN_WORD", "position": 0},
{"token": "中华", "start_offset": 0, "end_offset": 2, "type": "CN_WORD", "position": 1},
{"token": "华人", "start_offset": 1, "end_offset": 3, "type": "CN_WORD", "position": 2},
{"token": "人民", "start_offset": 2, "end_offset": 4, "type": "CN_WORD", "position": 3},
{"token": "共和国", "start_offset": 4, "end_offset": 7, "type": "CN_WORD", "position": 4}
]
}
5. 扩展配置(可选)
(1)自定义词典
-
在
plugins/ik/config/
下创建custom.dic
文件,每行一个词:plaintext区块链 深度学习
-
修改
IKAnalyzer.cfg.xml
:xml<entry key="ext_dict">custom.dic</entry>
(2)热更新词典(无需重启)
bash
curl -XPOST "http://localhost:9200/ik_test/_close"
curl -XPOST "http://localhost:9200/ik_test/_open"
6. 常见问题
(1)版本不匹配
- 错误:
Failed to load plugin [analysis-ik] due to version mismatch
- 解决:下载与 Elasticsearch 完全一致 的 IK 版本。
(2)权限问题
-
错误:
Permission denied
-
解决:
bashsudo chown -R elasticsearch:elasticsearch /usr/local/elasticsearch/plugins/ik/
(3)分词不生效
-
检查索引是否使用了正确的分词器:
json{ "mappings": { "properties": { "content": { "type": "text", "analyzer": "ik_max_word" } } } }
总结
步骤 | 命令/操作 |
---|---|
1. 下载 IK | wget https://github.com/.../elasticsearch-analysis-ik-8.13.0.zip |
2. 解压到插件目录 | unzip -d /usr/local/elasticsearch/plugins/ik/ |
3. 重启 ES | systemctl restart elasticsearch |
4. 测试分词 | curl -XGET "http://localhost:9200/_analyze" -d'{"text":"测试文本"}' |
完成! 现在你的 Elasticsearch 已支持中文分词。