elasticsearch +ik分词容器化

1.构建自定义镜像

这是最干净的方式。

1.1Dockerfile

1
2
3
4
FROM docker.elastic.co/elasticsearch/elasticsearch:8.12.2

RUN elasticsearch-plugin install \
https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v8.12.2/elasticsearch-analysis-ik-8.12.2.zip

1.2构建镜像

1
docker build -t es-ik:8.12.2 .

1.3运行

1
2
3
4
5
6
docker run -d \
--name es01 \
-p 9200:9200 \
-e "discovery.type=single-node" \
-e "xpack.security.enabled=false" \
es-ik:8.12.2

1.4验证

1
2
3
curl localhost:9200/_cat/plugins
....
analysis-ik

2.K8S 场景

如果你在 Kubernetes 上跑 ES(例如用 StatefulSet),可以这样:

1
2
3
4
5
6
7
8
9
10
11
initContainers:
- name: install-ik
image: docker.elastic.co/elasticsearch/elasticsearch:8.12.2
command:
- sh
- -c
- |
elasticsearch-plugin install --batch https://xxx/elasticsearch-analysis-ik-8.12.2.zip
volumeMounts:
- name: plugins
mountPath: /usr/share/elasticsearch/plugins

3.分词测试

1
2
3
4
5
curl -X POST "localhost:9200/_analyze" -H 'Content-Type: application/json' -d'
{
"analyzer": "ik_max_word",
"text": "中华人民共和国国歌"
}'

IK 有两个常用 analyzer:

  • ik_smart(最小切分)
  • ik_max_word(最细粒度切分)

4.进阶:词库自定义

IK 支持:

  • remote_ext_dict
  • 本地扩展词典
  • 热更新(通过 HTTP 词库)

容器化部署时建议:

/usr/share/elasticsearch/config/analysis-ik/

挂载 ConfigMap 或 Volume否则你每次改词库都要重建镜像。