开关索引与索引限制

开关索引与索引限制 #

关闭索引 #

关闭的索引不消耗集群资源(CPU、内存、文件句柄),但索引数据仍保留在磁盘上。关闭后索引不能读写,但可以随时重新打开。

典型场景:

  • 历史索引暂时不需要查询,但不想删除
  • 修改 Static 类型的索引设置(必须先关闭索引)
  • 降低集群负载
POST /my-index/_close

响应:

{
  "acknowledged": true,
  "shards_acknowledged": true,
  "indices": {
    "my-index": {
      "closed": true
    }
  }
}

批量关闭:

POST /logs-2024-01,logs-2024-02/_close
POST /logs-2024-*/_close

查询参数 #

参数类型默认值说明
timeoutTime30s操作超时时间
master_timeoutTime30s连接主节点的超时时间
wait_for_active_shardsString等待的活跃分片数(数字、allindex-setting
expand_wildcardsStringopen通配符展开策略:openclosedhiddennoneall
ignore_unavailableBooleanfalse是否忽略不存在的索引
allow_no_indicesBooleantrue通配符未匹配到索引时是否报错

打开索引 #

POST /my-index/_open

打开后索引会进入恢复流程(重建分片、分配副本),需要等待分片就绪后才能正常读写。

响应:

{
  "acknowledged": true,
  "shards_acknowledged": true
}

查询参数 #

参数类型默认值说明
timeoutTime30s操作超时时间
master_timeoutTime30s连接主节点的超时时间
wait_for_active_shardsString等待的活跃分片数
expand_wildcardsStringclosed通配符展开策略
ignore_unavailableBooleanfalse是否忽略不存在的索引
allow_no_indicesBooleantrue通配符未匹配到索引时是否报错

修改 Static 设置的典型流程 #

有些索引设置(如 index.number_of_shardsindex.codec)是 Static 类型,只能在创建时或关闭状态下修改:

// 1. 关闭索引
POST /my-index/_close

// 2. 修改 Static 设置
PUT /my-index/_settings
{
  "index.codec": "best_compression"
}

// 3. 重新打开
POST /my-index/_open

索引限制(Index Block) #

索引限制可以精细控制索引的读写行为,比"关闭索引"更灵活。

添加索引限制 #

PUT /my-index/_block/write

响应:

{
  "acknowledged": true,
  "shards_acknowledged": true,
  "indices": [
    {
      "name": "my-index",
      "blocked": true
    }
  ]
}

可用的限制类型 #

限制类型对应设置说明
read_onlyindex.blocks.read_only完全只读:禁止写入和元数据变更
readindex.blocks.read禁止读操作
writeindex.blocks.write禁止写操作(但允许元数据变更)
metadataindex.blocks.metadata禁止元数据修改(settings、mappings 变更等)
read_only_allow_deleteindex.blocks.read_only_allow_delete只读但允许删除索引(磁盘空间不足时系统自动设置)

查询参数 #

参数类型默认值说明
timeoutTime30s操作超时时间
master_timeoutTime30s连接主节点的超时时间
expand_wildcardsStringopen通配符展开策略
ignore_unavailableBooleanfalse是否忽略不存在的索引
allow_no_indicesBooleantrue通配符未匹配到索引时是否报错

通过 Settings API 设置/移除限制 #

也可以直接通过 _settings API 管理限制:

// 设为只读
PUT /my-index/_settings
{
  "index.blocks.write": true
}

// 移除只读
PUT /my-index/_settings
{
  "index.blocks.write": false
}

使用建议 #

场景推荐方式
索引归档,长期不查询_close 关闭索引
索引仍需查询但禁止写入_block/writeindex.blocks.write: true
修改 Static 设置_close,改完再 _open
磁盘空间紧张时自动保护系统自动设置 read_only_allow_delete,释放空间后手动移除

下一步 #