📣 极限科技诚招搜索运维工程师(Elasticsearch/Easysearch)- 全职/北京 👉 : 立即申请加入

为什么这个错误发生 #

resource_not_found_exception 是一个通用的资源未找到异常,表示请求的资源(索引、文档、快照、模板等)不存在。

这个错误可能由以下原因引起:

  1. 索引不存在:请求的索引未创建或已被删除
  2. 文档不存在:指定的文档 ID 不存在
  3. 快照不存在:请求的快照不存在或已被删除
  4. 模板不存在:索引模板或组件模板不存在
  5. 别名不存在:引用的别名不存在
  6. 管道不存在:Ingest 管道不存在
  7. 仓库不存在:快照仓库不存在
  8. 角色/用户不存在:安全角色或用户不存在

如何修复这个错误 #

1. 验证资源是否存在 #

# 检查索引是否存在
GET /<index>

# 列出所有索引
GET /_cat/indices?v

# 检查文档是否存在
GET /<index>/_doc/<id>

# 检查快照
GET /_snapshot/<repository>/_all

# 检查模板
GET /_index_template/*
GET /_component_template/*

2. 创建缺失的索引 #

# 创建新索引
PUT /<index>

# 使用索引模板创建
PUT /<index>
{
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 1
  }
}

3. 使用 ignore_unavailable #

# 在操作中忽略不存在的资源
GET /<index1>,<index2>,<index3>/_search?ignore_unavailable=true

# 删除时忽略不存在的索引
DELETE /<index>?ignore_unavailable=true

4. 检查资源名称拼写 #

# 列出所有资源确认名称
GET /_cat/indices?v
GET /_cat/aliases?v
GET /_cat/templates?v

5. 使用通配符 #

# 使用通配符匹配多个资源
GET /logs-*/_search

# 使用 _all 或通配符
GET /_search

6. 创建缺失的模板 #

# 创建索引模板
PUT /_index_template/<template_name>
{
  "index_patterns": ["<index>-*"],
  "template": {
    "settings": {
      "number_of_shards": 1
    }
  }
}

7. 创建缺失的别名 #

# 为现有索引创建别名
POST /_aliases
{
  "actions": [
    {
      "add": {
        "index": "<actual_index>",
        "alias": "<alias_name>"
      }
    }
  ]
}

8. 创建缺失的管道 #

# 创建 Ingest 管道
PUT /_ingest/pipeline/<pipeline_name>
{
  "description": "Pipeline description",
  "processors": [
    {
      "set": {
        "field": "timestamp",
        "value": "{{_ingest.timestamp}}"
      }
    }
  ]
}

9. 创建缺失的仓库 #

# 创建快照仓库
PUT /_snapshot/<repository_name>
{
  "type": "fs",
  "settings": {
    "location": "/path/to/backup"
  }
}

10. 条件操作 #

# 使用 if_seq_no 和 if_primary_term 进行条件操作
POST /<index>/_update/<id>
{
  "doc": { "field": "value" },
  "if_seq_no": 5,
  "if_primary_term": 1
}

# 或使用 op_type=create 仅在不存在时创建
PUT /<index>/_doc/<id>?op_type=create
{
  "field": "value"
}

预防措施 #

  • 在操作前验证资源是否存在
  • 使用索引模板自动创建索引
  • 使用别名提供稳定的访问接口
  • 实现客户端重试逻辑处理临时资源不存在
  • 使用条件操作避免竞争条件
  • 在代码中添加资源存在性检查
  • 使用配置管理确保所有依赖资源已创建
  • 监控资源创建和删除操作