利用 index.routing.allocation.require.box_type 实现热温冷
解读
国内中大型 Elasticsearch 集群普遍采用“热-温-冷”三级架构来平衡实时写入、近线查询与长期归档的成本。
面试官问“怎么用 index.routing.allocation.require.box_type 实现”,核心想验证三点:
- 你是否理解 分片分配过滤(Shard Allocation Filtering) 机制;
- 能否把节点属性、索引设置与 ILM(索引生命周期管理)串成闭环;
- 是否具备落地经验(例如云盘 vs 本地盘、机型混布、故障迁移)。
一句话:用 box_type 打标签,用索引模板绑定 require 规则,用 ILM 驱动索引在不同 box_type 之间自动流动。
知识点
- 节点属性(node.attr)
在 elasticsearch.yml 里显式声明:node.attr.box_type: hot,重启生效;也可通过-E参数注入。 - 分片分配过滤规则
index.routing.allocation.require.{attribute}:索引分片必须落在满足条件的节点;include:允许;exclude:禁止。
- 索引生命周期管理(ILM)
在 Hot、Warm、Cold 三个阶段分别挂载 allocate action,动态修改require.box_type值,实现无重启迁移。 - 国内云厂商实践
- 阿里云 ESSD 云盘 PL1/PL0 对应 hot/warm,OSS 快照对应 cold;
- 腾讯云 CBS 高性能盘做 hot,普通云盘做 warm,COS 归档做 cold;
- 物理机混布时,大容量 SATA 盘节点标记为 warm/cold,NVMe 机型标记为 hot。
- 常见坑
- 节点属性写错导致 NO_VALID_SHARD_COPY;
- 副本数 > warm 节点数引起 UNASSIGNED;
- 冷节点磁盘 >85% 触发 flood-stage 写阻塞;
- 修改 box_type 后忘记 手动触发 cluster.routing.allocation.enable=primaries,导致搬迁慢。
答案
-
规划节点角色
hot 节点:16C64G + 2T NVMe,elasticsearch.yml 追加:node.attr.box_type: hotwarm 节点:8C32G + 12T SATA,追加:
node.attr.box_type: warmcold 节点:8C16G + 36T SATA,追加:
node.attr.box_type: cold重启各节点,通过
GET _cat/nodeattrs?v确认生效。 -
创建 ILM 策略
PUT _ilm/policy/hot-warm-cold-30d { "policy": { "phases": { "hot": { "actions": { "rollover": { "max_age": "1d", "max_size": "50gb" }, "allocate": { "require": { "box_type": "hot" } } } }, "warm": { "min_age": "1d", "actions": { "allocate": { "require": { "box_type": "warm" } }, "forcemerge": { "max_num_segments": 1 }, "shrink": { "number_of_shards": 1 } } }, "cold": { "min_age": "7d", "actions": { "allocate": { "require": { "box_type": "cold" } }, "freeze": {} } }, "delete": { "min_age": "30d", "actions": { "delete": {} } } } } } -
建立索引模板
PUT _index_template/log-data { "index_patterns": ["log-*"], "template": { "settings": { "number_of_shards": 3, "number_of_replicas": 1, "index.lifecycle.name": "hot-warm-cold-30d", "index.routing.allocation.require.box_type": "hot", "index.refresh_interval": "5s" } } } -
写入与观察
首日索引log-2025-06-20自动落在 hot 节点;
第二天 ILM 进入 warm 阶段,分片自动迁移到 warm 节点并触发 shrink + forcemerge;
第七天进入 cold 阶段,分片再次迁移到 cold 节点并执行 freeze;
第 30 天自动删除。
全程用GET _cat/shards?v&h=index,shard,prirep,state,node,unassigned.reason监控搬迁进度。 -
应急与调优
- 若 warm 节点磁盘告急,临时
PUT log-*/_settings把require.box_type改成 cold,手动释放空间; - 大促期间把 hot 节点
cluster.routing.allocation.enable=none,禁止搬迁保障写入; - 冷节点开启 searchable snapshot(7.10+),把冷数据挂载到 对象存储,进一步节省磁盘。
- 若 warm 节点磁盘告急,临时
拓展思考
- 如果公司预算有限,只有 hot 与 warm 两类机型,如何用 box_type + 副本数动态调整 实现“逻辑冷”?
- 当集群跨两个机房,box_type 与 awareness.attr 冲突时,如何设计分配规则既满足热温冷又满足容灾?
- 数据节点角色分离后,Master、Coordinating 节点是否还需要打 box_type?为什么?
- 国内信创环境(ARM+国产OS)下,box_type 标签如何与 Kubernetes nodeSelector 联动,实现 Pod 级热温冷?
- 在 Logstash 输出端提前按日期生成索引,如何避免因 ILM rollover 规则与 box_type 不匹配导致 双写热点?