DEBUG.WIKI
PanstarCloud:部署应用,接入 AI,云服务器与 AI 网关
晚安云;香港 CN2 ¥15/月
V.PS:让项目靠近用户,亚太、欧洲、北美 KVM VPS

解决 Elasticsearch 报错 search_phase_execution_exception all shards failed 分片排查

排查 Elasticsearch 检索时报 search_phase_execution_exception all shards failed 分片全部失效错误,深入分析未分配分片与数据损坏恢复。

问题现象

向 Elasticsearch 发起日常搜索请求时,请求直接报错失败:

{
  "error": {
    "root_cause": [
      {
        "type": "search_phase_execution_exception",
        "reason": "all shards failed",
        "phase": "query",
        "grouped": true,
        "failed_shards": [ ... ]
      }
    ],
    "type": "search_phase_execution_exception",
    "reason": "all shards failed"
  },
  "status": 503
}

Kibana 发现该索引的所有搜索结果全部为空,集群状态显示为红(Red)。

触发根因

在分布式搜索流程中,query 阶段需要将查询并发下发给该索引的每一个主分片(Primary Shards)或副本分片(Replica Shards):

  1. 分片全部离线处于未分配状态(Unassigned Shards):包含该分片数据的节点突发物理下线,且副本数不足,导致该分片无任何存活节点可供读取;
  2. 底层 Lucene 段数据物理损坏:宿主机断电导致某些段文件损坏,分片加载时抛出 CorruptIndexException;
  3. 查询语法严重非法:使用了未定义字段的特定原生脚本计算触发整组分片运行时崩溃。

解决步骤

1. 使用 explain API 诊断未分配分片的底层根因

调用官方诊断接口定位该分片为何无法被分配:

curl -X GET "http://localhost:9200/_cluster/allocation/explain?pretty"

API 会清晰输出:

  • allocate_explanation:例如节点下线、达到分片数量配额上限、或存在损坏锁;
  • decider:阻断分配的决策器。

2. 触发集群未分配分片强制自动重试

如果故障节点已重新上线,通知集群重新调度重试:

curl -X POST "http://localhost:9200/_cluster/reroute?retry_failed=true"

3. 针对副本丢失紧急重新分配主分片

如果确认某节点物理报废且主分片丢失,但在灾难允许接受丢失部分数据前提下强制将空副本提升为主分片:

curl -X POST "http://localhost:9200/_cluster/reroute" -H 'Content-Type: application/json' -d'
{
  "commands": [
    {
      "allocate_empty_primary": {
        "index": "my-broken-index",
        "shard": 0,
        "node": "node-02",
        "accept_data_loss": true
      }
    }
  ]
}
'

4. 从快照归档中还原损坏分片(标准生产修复)

若有已建立的 Snapshot 快照仓库,从快照中精准恢复受损索引:

curl -X POST "http://localhost:9200/_snapshot/my_backup/snapshot_20261115/_restore" -H 'Content-Type: application/json' -d'
{
  "indices": "my-broken-index"
}
'

验证确认

监控集群健康状态:

curl "http://localhost:9200/_cluster/health?pretty"

集群状态恢复为 green 或 yellow,unassigned_shards 归零;重新发起查询请求,正常返回命中数据。