学完这篇,你能从零把一个 Elasticsearch 实例跑起来,写出可用的索引 Mapping、中文分词和查询语句,并知道集群该怎么分片才不会事后返工。
下面按「起服务 → 建索引 → 配分词 → 写查询 → 上集群」五步走,命令都能直接复制。
第一步:把实例跑起来
本地验证用 Docker 最省事,选 8.x 版本:
docker run -d --name es -p 9200:9200 \
-e "discovery.type=single-node" \
-e "ES_JAVA_OPTS=-Xms1g -Xmx1g" \
-e "xpack.security.enabled=false" \
docker.elastic.co/elasticsearch/elasticsearch:8.13.4
起来后验证:
curl localhost:9200
curl localhost:9200/_cluster/health?pretty
看到 status 为 green 或 yellow 就正常(单节点无副本必然是 yellow)。
注意:单机测试必须加 discovery.type=single-node,否则会卡在 bootstrap checks 起不来;xpack.security.enabled=false 只用于本地,线上必须开账号密码。
第二步:建索引,别依赖动态映射
动态映射会自动把字符串建成 text+keyword,日期猜错、数字变字符串都很常见。生产上老老实实手写 Mapping:
PUT /forum_post
{
"settings": { "number_of_shards": 1, "number_of_replicas": 0 },
"mappings": {
"properties": {
"title": { "type": "text", "analyzer": "ik_max_word",
"search_analyzer": "ik_smart",
"fields": { "keyword": { "type": "keyword" } } },
"content": { "type": "text", "analyzer": "ik_max_word",
"search_analyzer": "ik_smart" },
"forum_id": { "type": "integer" },
"user_id": { "type": "integer" },
"created_at": { "type": "date" }
}
}
}
写入一条数据:
PUT /forum_post/_doc/1
{ "title": "Elasticsearch 分词原理", "content": "……",
"forum_id": 3, "user_id": 12, "created_at": "2025-05-01T10:00:00" }
注意:text 用于全文检索,keyword 用于精确过滤、排序、聚合。给 title 加 fields.keyword,后面做聚合和排序就不用重建索引了。批量导入用 _bulk,几百条一次,别一条条 PUT。
第三步:装中文分词器
默认 standard 分词器会把中文切成单字,搜"分词原理"基本没效果。装 IK:
docker exec -it es bin/elasticsearch-plugin install \
https://get.infini.cloud/elasticsearch/analysis-ik/8.13.4
docker restart es
验证分词结果:
GET /_analyze
{ "analyzer": "ik_max_word", "text": "Elasticsearch 中文分词原理" }
注意:IK 插件版本必须和 ES 版本严格一致,8.13.4 的 ES 装 8.12 的 IK 会直接启动失败。索引时用 ik_max_word(切得细,召回高),查询时用 ik_smart(切得粗,精度高),这是最常用的组合。
第四步:写查询,够用就这几种
GET /forum_post/_search
{
"query": {
"bool": {
"must": [ { "match": { "title": { "query": "分词 原理", "operator": "and" } } } ],
"should": [ { "match": { "content": "原理" } } ],
"filter": [ { "term": { "forum_id": 3 } },
{ "range": { "created_at": { "gte": "now-7d" } } } ]
}
},
"highlight": { "fields": { "title": {} } },
"from": 0, "size": 20
}
要点:全文匹配用 match,精确值(ID、状态、标签)一律放 filter——不参与打分、可被缓存,比塞进 must 快很多。高亮用 highlight,翻页 from+size 只适合前一万条。
注意:深翻页用 search_after 而不是 from: 10000,ES 默认 max_result_window 就是 10000,超了直接报错。
第五步:分片和集群
分片数在建索引那一刻就定死了,之后改不了(只能 _reindex 或 split),所以宁可先小后扩:
- 单分片 10–30GB 是常见区间,日增量几十万条的中型站,1 主分片起步完全够;
- 副本随时可改:
PUT /forum_post/_settings {"number_of_replicas": 1};
- 多节点时用
node.roles 区分角色,数据节点专职存数据,避免主节点被查询压垮:
node.roles: [ data, ingest ]
# 专用主节点(建议 3 个,防脑裂)
node.roles: [ master ]
查看健康状况和分片分布:
curl "localhost:9200/_cluster/health?pretty"
curl "localhost:9200/_cat/shards?v"
注意:节点数少于副本数 +1 时,副本分片会一直 unassigned,集群停在 yellow。别看到 yellow 就以为出故障了。
小结
- 单机验证记得
discovery.type=single-node,上线必须开安全认证;
- 手写 Mapping,
text 管全文检索、keyword 管过滤排序聚合,两者别混;
- 中文必装 IK,索引
ik_max_word、查询 ik_smart,版本必须与 ES 一致;
- 精确条件放
filter,深翻页用 search_after;
- 分片数建索引时定死,宁少勿多;副本随时可调;节点角色拆开更稳。