ElasticSearch索引生命周期策略配置(ES TTL)

背景

有些索引数据作为临时数据存放,一段时间后我们希望索引可以自动过期删除,就是常说的TTL(Time To Live)机制

ElasticSearch索引数量过多会占用很多主分片和副本分片,最终导致可用分片数量为0,不能再创建新的索引

这里说明一下,我们用的ElasticSearch版本为7.8.0

 

官方文档

关于如何管理索引的生命周期策略,官方文档有详细的描述,英语基础能力好的同学可以自行研读官方wiki

Elasticsearch7.8 生命周期策略配置

https://www.elastic.co/guide/en/elasticsearch/reference/7.8/set-up-lifecycle-policy.html

Elasticsearch7.8 开启生命周期管理

https://www.elastic.co/guide/en/elasticsearch/reference/7.8/start-stop-ilm.html

Elasticsearch7.8 查询生命周期策略

https://www.elastic.co/guide/en/elasticsearch/reference/7.8/ilm-get-lifecycle.html

 

启用索引生命周期管理策略

curl -u 用户名:密码 --location --request POST http://127.0.0.1:9200/_ilm/start

 

创建Elasticsearch生命周期策略,TTL时间1小时

curl -u 用户名:密码 --location --request PUT http://127.0.0.1:9200/_ilm/policy/index_ttl_one_hours_policy --header "Content-Type: application/json" --data-raw "{\"policy\":{\"phases\":{\"delete\":{\"min_age\":\"1h\",\"actions\":{\"delete\":{}}}}}}"

 

查看已创建的生命周期管理策略

curl -u 用户名:密码 --request GET http://127.0.0.1:9200/_ilm/policy

 

 

 

调用客户端创建引用生命周期策略的索引

 

public boolean createIndex() throws IOException {
    String indexName = "test_index";
    Settings settings = Settings.builder().put("index.lifecycle.name", "index_ttl_one_hours_policy").build();
    CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
    createIndexRequest.settings(settings);
    CreateIndexResponse indexResponse = EsRestClientCache.getEsClient(EsConstants.DEFAULT).indices().create(createIndexRequest, RequestOptions.DEFAULT);
    log.info("CreateIndexResponse:" + indexResponse);
    return indexResponse.isAcknowledged();
}

  

ElasticSearch生命周期策略时间单位

d - Days

h - Hours

m - Minutes

s - Seconds

ms -  Milliseconds

micros -  Microseconds

nanos -  Nanoseconds

 

posted @ 2021-11-30 14:50  codest  阅读(4400)  评论(0编辑  收藏  举报