安裝 Elasticsearch IK 分詞器(手動 .zip/.zip 安裝)
IK 分詞器(IK Analysis)是 Elasticsearch 最常用的中文分詞插件,支持 細粒度分詞(ik_max_word) 和 智能切分(ik_smart)。以下是詳細安裝步驟:
1. 下載 IK 分詞器
方式 1:直接下載預編譯版本(推薦)
訪問 IK Releases,選擇 與 Elasticsearch 版本匹配 的插件包,例如:
# 示例: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:源碼編譯(適用于自定義詞典)
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)創建插件目錄
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)驗證安裝
# 查看已安裝插件
/usr/local/elasticsearch/bin/elasticsearch-plugin list
輸出應包含:
analysis-ik
3. 重啟 Elasticsearch
# 如果使用 systemd
sudo systemctl restart elasticsearch# 如果手動運行
ps -ef | grep elasticsearch # 找到進程 ID
kill -9 <PID> # 停止
/usr/local/elasticsearch/bin/elasticsearch -d # 后臺啟動
4. 測試 IK 分詞器
(1)創建測試索引
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)測試分詞效果
curl -XGET "http://localhost:9200/ik_test/_analyze" -H "Content-Type: application/json" -d'
{"analyzer": "ik_max_word","text": "中華人民共和國"
}'
正常輸出:
{"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
文件,每行一個詞:區塊鏈 深度學習
- 修改
IKAnalyzer.cfg.xml
:<entry key="ext_dict">custom.dic</entry>
(2)熱更新詞典(無需重啟)
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
- 解決:
sudo chown -R elasticsearch:elasticsearch /usr/local/elasticsearch/plugins/ik/
(3)分詞不生效
- 檢查索引是否使用了正確的分詞器:
{"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 已支持中文分詞。