本文系統梳理 Elasticsearch 核心配置文件 (elasticsearch.yml、jvm.options、log4j2.properties) 關鍵參數,並詳細說明文檔元數據字段 (_index、_id、_source、_version、_routing 等) 的含義與用法。
cluster.name: my-es-cluster # 集群名稱,同名節點自動組集群
node.name: node-1 # 節點名稱,建議有意義標識
node.roles: [master, data, ingest] # 節點角色:master候選、數據、預處理
network.host: 0.0.0.0 # 綁定所有網卡,生產環境請指定內網IP
http.port: 9200 # HTTP REST 端口
transport.port: 9300 # 節點間通信端口
discovery.seed_hosts: ["10.0.0.1:9300", "10.0.0.2:9300"] # 種子節點
cluster.initial_master_nodes: ["node-1", "node-2"] # 首輪選主候選
path.data: /var/lib/elasticsearch # 數據目錄,建議獨立掛載磁盤
path.logs: /var/log/elasticsearch # 日誌目錄
indices.memory.index_buffer_size: 10% # 索引緩衝佔堆內存比例
# 核心原則:堆內存 ≤ 物理內存 50% 且 ≤ 32GB (開啟壓縮指針)
# -Xms16g -Xmx16g (生產環境建議 16-31GB)
bootstrap.memory_lock: true # 鎖定內存防止 swap
thread_pool.write.queue_size: 10000 # 寫線程池隊列
thread_pool.search.queue_size: 1000 # 查詢線程池隊列
indices.breaker.total.limit: 70% # 總熔斷閾值
indices.breaker.request.limit: 60% # 請求熔斷
indices.queries.cache.size: 10% # 查詢緩存
-Xms16g
-Xmx16g
-XX:+UseG1GC
-XX:G1HeapRegionSize=16m
-XX:+UnlockDiagnosticVMOptions
-XX:+LogVMOutput
-XX:LogFile=/var/log/elasticsearch/gc.log
-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=/var/lib/elasticsearch
-Djava.io.tmpdir=/tmp/elasticsearch
每個文檔自帶以下元數據,不屬於 _source 業務數據:
| 字段 | 含義 | 可否自定義 | 典型用途 |
|---|---|---|---|
_index | 文檔所屬索引名 | 否 | 多索引查詢過濾、路由 |
_id | 文檔唯一標識 | 是 (索引時指定) | 主鍵查詢、去重、更新/刪除 |
_source | 原始 JSON 文檔體 | 是 | 返回給客戶端、reindex、高亮 |
_version | 樂觀鎖版本號 | 內部管理 | 並發更新衝突檢測 |
_seq_no / _primary_term | 序列號/主分片任期 | 內部管理 | 7.x+ 並發控制替代 _version |
_routing | 路由值,決定分片 | 是 (映射或索引時指定) | 親子關係、用戶隔離、熱點優化 |
_ttl (已棄用) | 生存時間 | 否 | 定期刪除過期數據 (現用 TTL 索引 + ILM) |
_timestamp (已棄用) | 時間戳 | 否 | 時間序列排序 (現用 @timestamp 字段) |
PUT /orders/_doc/order_20240115_001
{ "user_id": 1001, "amount": 299.0, "status": "paid" }
同一訂單號重複提交不會產生重複文檔。
# 映射配置
PUT /logs
{ "mappings": { "_routing": { "required": true } } }
# 寫入指定路由
PUT /logs/_doc/1?routing=user_1001
{ "level": "ERROR", "msg": "timeout" }
# 查詢同路由
GET /logs/_search?routing=user_1001
同一用戶數據落在同一分片,查詢單分片極快。
# 獲取帶版本文檔
GET /products/_doc/100?version=true
# 返回 _version: 3
# 條件更新
PUT /products/_doc/100?version=3&version_type=external
{ "price": 99.0, "stock": 50 }
# 版本不匹配拋 409 Conflict
bootstrap.memory_lock: true 並配置 ulimit -l unlimited