NoSQL 与搜索 / 系统课时
读取 Cluster Health 的真实含义
读取 Cluster Health 的真实含义
_cluster/health 很适合做分片分配的第一层判断,但颜色只描述 primary 与 replica 是否被分配,并不直接等价于“业务健康”。本篇把 green、yellow、red 还原到分片层含义,并给出从颜色下钻到受影响索引的最短排查路径。
学习目标
- 准确解释 green、yellow、red 对 primary 与 replica 的含义
- 用 Cluster Health API 读取关键计数并判断风险范围
- 知道何时必须继续下钻,而不是只看颜色结束排查
颜色判断的是分片分配
Cluster Health 从 shard 汇总到 index,再从 index 汇总到 cluster,最终状态由最差一级决定。三种颜色的含义很具体:
| 状态 | 分片条件 | 直接含义 |
|---|---|---|
| green | 所有 primary 与 replica 都已分配 | 分片分配完整 |
| yellow | primary 全部已分配,但至少一个 replica 未分配 | 数据当前可由 primary 提供,但冗余下降 |
| red | 至少一个 primary 未分配 | 至少一部分数据不可用,相关查询或写入可能失败 |
因此,red 不代表整个集群所有请求都失败;它可能只影响少数索引。反过来,green 也不代表 P99 延迟、线程池拒绝、磁盘余量、认证链路或应用结果一定正常。
读取关键计数
先把连接地址与 API Key 放入 ELASTICSEARCH_URL、ELASTIC_API_KEY,然后只取判断分配风险需要的字段:
curl -sS "$ELASTICSEARCH_URL/_cluster/health?filter_path=cluster_name,status,active_primary_shards,active_shards,unassigned_shards,unassigned_primary_shards,initializing_shards,relocating_shards" -H "Authorization: ApiKey $ELASTIC_API_KEY"预期输出的具体数值取决于当前集群,结构类似:
{"cluster_name":"<VALUE>","status":"<VALUE>","active_primary_shards":<VALUE>,"active_shards":<VALUE>,"relocating_shards":<VALUE>,"initializing_shards":<VALUE>,"unassigned_shards":<VALUE>,"unassigned_primary_shards":<VALUE>}判断时先看 unassigned_primary_shards:大于 0 时一定要定位哪些 primary 丢失。若它为 0 而 unassigned_shards 大于 0,则通常是 replica 未分配,对应 yellow。initializing_shards 与 relocating_shards 则帮助区分“正在恢复”与“长期卡住”。
从集群颜色下钻到具体分片
颜色只告诉你严重度,不告诉你故障对象。出现 yellow 或 red 时,先按索引查看状态,再列出未分配 shard:
curl -sS "$ELASTICSEARCH_URL/_cluster/health?level=indices&filter_path=status,indices.*.status" -H "Authorization: ApiKey $ELASTIC_API_KEY"
curl -sS "$ELASTICSEARCH_URL/_cat/shards?v=true&h=index,shard,prirep,state,node,unassigned.reason&s=state" -H "Authorization: ApiKey $ELASTIC_API_KEY"预期结果中,问题分片会呈现为 UNASSIGNED;prirep 为 p 表示 primary,为 r 表示 replica。实际索引名、分片号和原因会因故障而异:
index shard prirep state node unassigned.reason
<INDEX> <ID> <p|r> UNASSIGNED - <REASON>找到目标 shard 后,再对它使用 _cluster/allocation/explain。这一步比盲目改 number_of_replicas 或手工 reroute 更安全,因为真正原因可能是节点离线、磁盘水位、allocation filter、awareness 约束或多次分配失败。
把颜色与业务可用性分开
监控上应把 Cluster Health 当作分片可用性信号,而不是唯一的服务健康信号。red 需要立即确认受影响索引是否承载在线流量;yellow 需要关注持续时间、剩余故障容忍度与恢复进度;即使 green,也仍要同时看请求错误率、P95/P99 延迟、线程池拒绝、JVM 与磁盘压力。
使用 wait_for_status=yellow 做自动化等待时也要注意,它表示等待状态达到 yellow 或更好,所以 green 同样会满足条件。把“颜色含义”“受影响对象”和“用户 SLI”拆开判断,才能避免 yellow 过度告警,也避免 green 掩盖真实业务故障。