背景
有些索引數據作為臨時數據存放,一段時間后我們希望索引可以自動過期刪除,就是常說的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
