es 索引生命周期管理

less than 1 minute read

使用 Elasticsearch 中的索引生命周期管理(ILM)功能来管理索引。Configure a lifecycle policy | Elastic

创建生命周期策略

创建索引生命周期策略 test_policy

PUT _ilm/policy/test_policy
{
  "policy": {                       
    "phases": {
      "hot": {                      
        "actions": {
              "rollover":{
                  "max_age":"30s"
              }
        }
      },
      "delete": {
        "min_age": "90s",           
        "actions": {
          "delete": {}              
        }
      }
    }
  }
}

本文为了演示,定义了索引在 hot 阶段保留10s,然后就会触发滚动策略到 delete 阶段,到 delete 阶段之后,保留60s左右,就会删除。

其他策略,当索引已存在 7 天或任何主分片达到 25 GB 时滚动更新;当索引翻转后已经 8 天时删除该索引。

PUT _ilm/policy/test-1_policy
{
  "policy": {
    "phases": {
      "hot": {                                
        "actions": {
          "rollover": {
            "max_primary_shard_size": "25GB", 
            "max_age": "7d"
          }
        }
      },
      "delete": {
        "min_age": "8d",                     
        "actions": {
          "delete": {}                        
        }
      }
    }
  }
}

创建索引模板

创建索引模板 test_index_template

PUT _index_template/test_index_template
{
  "index_patterns": ["test-*"],
  //"data_stream": { },
  "template": {  
    "settings": {
      "number_of_shards": 2,
      "number_of_replicas": 1,
      "index.lifecycle.name": "test_policy",      
      "index.lifecycle.rollover_alias": "test-alias"    
    }
  }
}
  • index_patterns:对所有名称以 “test-“ 开头的新索引使用此模板
  • data_stream:该模板创建数据流,而非索引
  • number_of_shards:索引分片数为2
  • number_of_replicas:索引副本数为1
  • index.lifecycle.name:将 test_policy 应用于用此模板创建的新索引
  • index.lifecycle.rollover_alias: 定义一个索引别名,用于引用由 test_policy 管理的索引

创建索引

当为滚动索引设置策略时,需要手动创建由策略管理的第一个索引,并指定它为写索引。

索引的名称必须符合索引模板中定义的模式,并以数字结尾。这个数字会被递增,以生成由翻转动作创建的索引的名称。

下面这个请求创建了 test-2022.11.28-000001 索引。因为它符合上面创建的索引模板 test_index_template 中指定的索引模式 test-*,所以 Elasticsearch 会自动应用 test_index_template 模板的设置。

PUT test-2022.11.28-000001
{
  "aliases": {
    "test-alias":{
      "is_write_index": true 
    }
  }
}
  • is_write_index:将这个初始索引设置为这个别名的写入索引。

在 kibana 中查看索引信息

现在可以开始向生命周期策略中指定的滚动别名 test_alias 索引数据了。在 test_policy 策略样本中,一旦初始索引超过10s,就会触发翻转动作。然后 ILM 创建一个新的索引,成为 test-alias 的写索引。

配置 lifecycle 检测时间

PUT _cluster/settings
{
  "transient": {
    "indices.lifecycle.poll_interval": "10s" 
  }
}

默认策略轮询时间间隔为十分钟,这里为了方便观察滚动效果改成10秒。

功能验证

批量写入几条数据,观察滚动效果。

Note: 是向滚动别名 test_alias 索引数据。

PUT /test_alias/_doc/_bulk
{"index":{}}
{"message":"hallo-01"}
{"index":{}}
{"message":"hallo-02"}
{"index":{}}
{"message":"hallo-03"}