Elasticsearch 的 index 會隨著時間變大,導致查詢變慢、儲存成本升高。ILM (Index Lifecycle Management) 可以自動化:
- Index 的 rollover(建立新 index)
- Index 的 刪除(清理舊資料)
- Index 的 轉冷 / 凍結(降低儲存成本)
1. ILM 基本概念
ILM(Index Lifecycle Management)用來自動化索引的生命週期管理,確保資料依照時間或大小條件自動 rollover、壓縮、甚至刪除。常見的階段(phase)有:
- hot:資料正在寫入與查詢,效能需求最高。
- warm:資料仍需查詢,但寫入頻率下降,可以壓縮或移到較慢的節點。
- cold:資料幾乎不查詢,僅保存,通常移到低成本儲存。
- frozen:極少存取的資料,僅保留以供查詢,會依賴快取與搜尋快照。
- delete:資料不再需要,直接刪除。
2. 設定 ILM Policy
我們要建立一個 metricbeat 的 ILM 規則:
- 每天 rollover(index 活超過 1 天就換新 index)
- 30 天後自動刪除
PUT _ilm/policy/metricbeat
{
"policy": {
"phases": {
"hot": {
"actions": {
"rollover": {
"max_age": "1d", // 存活超過 1 天就 rollover
"max_primary_shard_size": "50gb" // 單 shard 達 50GB 就 rollover
}
}
},
"delete": {
"min_age": "30d", // index 存活超過 30 天就刪除
"actions": {
"delete": {}
}
}
}
}
}
3. 套用 ILM Policy 到 Index Template
建立好的 policy 需要跟 index template 綁定,這樣新建立的 index 才會自動套用。
以下範例:
- index 名稱符合
metricbeat-8.17.7*
的,會使用 metricbeat policy
PUT _index_template/metricbeat-8.17.7
{
"index_patterns": ["metricbeat-8.17.7"],
"template": {
"settings": {
"index": {
"lifecycle": {
"name": "metricbeat" // 指定要套用的 ILM policy
},
"refresh_interval": "5s"
}
}
}
}
4. 檢查 ILM 狀態
查詢某個 index 的 ILM 狀態:
GET .ds-metricbeat-8.17.7-*/_ilm/explain
範例輸出:
{
"indices": {
".ds-metricbeat-8.17.7-2025.09.09-000012": {
"index": ".ds-metricbeat-8.17.7-2025.09.09-000012",
"managed": true,
"policy": "metricbeat",
"age": "18.25h",
"phase": "hot",
"action": "rollover",
"step": "check-rollover-ready"
}
}
}
解讀:
phase: hot
→ 現在在 Hot 階段action: rollover
→ 正在檢查 rollover 條件age: 18.25h
→ Index 已經活了 18 小時step: check-rollover-ready
→ 等待超過 1d 或滿足大小條件才 rollover
5. 總結
- ILM 幫助自動化索引管理,不用手動清理舊資料
- index template 必須綁定 ILM policy,否則不會生效
- 可用
_ilm/explain
查狀態,理解 index 現在在哪個階段