深色模式
ELK 入门 ElasticSearch
ElasticSearch 是 ELK 的存储与检索核心,用倒排索引做全文搜索。本文在单机起一个 ES,创建索引并写入、查询一条日志。
适用环境
bash
# ES 需要 JVM,确认内存充足
free -h
# 确认没有占用 9200 端口
ss -ltnp | grep 92001
2
3
4
2
3
4
操作步骤
1. 用 Docker 启动单节点 ES
bash
docker run -d --name elasticsearch \
-p 9200:9200 -p 9300:9300 \
-e "discovery.type=single-node" \
-e "ES_JAVA_OPTS=-Xms1g -Xmx1g" \
docker.elastic.co/elasticsearch/elasticsearch:latest1
2
3
4
5
2
3
4
5
2. 创建索引并写入一条日志
bash
# 创建索引
curl -X PUT "http://localhost:9200/logs-app-2026-10-09" -H 'Content-Type: application/json' -d '{
"mappings": { "properties": { "level": {"type":"keyword"}, "msg": {"type":"text"} } }
}'
# 写入文档
curl -X POST "http://localhost:9200/logs-app-2026-10-09/_doc" -H 'Content-Type: application/json' -d '{
"level":"error","msg":"connection timeout","ts":"2026-10-09T10:00:00Z"
}'1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
3. 查询
bash
curl -s "http://localhost:9200/logs-app-2026-10-09/_search?q=level:error" | head -c 4001
验证
bash
curl -s http://localhost:9200/_cluster/health?pretty | head -n 6
curl -s 'http://localhost:9200/_cat/indices?v'1
2
2
常见坑
DANGER
单机用 discovery.type=single-node 仅适合学习。生产必须 3 节点以上且配置 cluster.initial_master_nodes,否则脑裂丢数据。
WARNING
keyword 与 text 区别很大:状态、级别用 keyword(精确匹配、聚合);正文用 text(分词搜索)。映射建错后需重建索引。