脚本能自动删除旧Elasticsearch索引吗?

wen 实用脚本 3

本文目录导读:

脚本能自动删除旧Elasticsearch索引吗?

  1. 基于 Curator(官方推荐,最成熟)
  2. 使用 Shell 脚本 + curl(简单轻量)
  3. 使用 PowerShell 脚本(Windows 环境)
  4. 使用 Python 脚本(灵活,便于自定义)
  5. 使用 ILM(Index Lifecycle Management,生产环境最佳实践)

是的,可以通过脚本自动删除旧的 Elasticsearch 索引,通常基于索引名称中的日期模式(如 logs-2025-01-01)或索引的创建时间来判断。

以下是几种常见的实现方案:

基于 Curator(官方推荐,最成熟)

Elasticsearch 官方工具,通过配置文件定义删除策略。

安装:

pip install elasticsearch-curator

配置文件 delete_old_indices.yml

actions:
  1:
    action: delete_indices
    description: "Delete indices older than 30 days"
    options:
      ignore_empty_list: True
      disable_action: False
    filters:
    - filtertype: age
      source: name
      direction: older
      unit: days
      unit_count: 30
      timestring: '%Y.%m.%d'   # 根据你的索引命名格式调整
    - filtertype: pattern
      kind: prefix
      value: logs-              # 只处理以 logs- 开头的索引

运行:

curator --config delete_old_indices.yml

使用 Shell 脚本 + curl(简单轻量)

通过 Elasticsearch API 获取索引列表,按名称日期过滤后删除。

#!/bin/bash
ES_HOST="http://localhost:9200"
# 设置保留天数,删除 30 天前的索引
RETENTION_DAYS=30
CUTOFF_DATE=$(date -d "$RETENTION_DAYS days ago" +%Y.%m.%d)
# 获取需要删除的索引列表(假设索引格式为 logs-YYYY.MM.DD)
INDICES_TO_DELETE=$(curl -s "$ES_HOST/_cat/indices/logs-*?h=index" | \
    awk -F'-' -v cutoff="$CUTOFF_DATE" '$2 < cutoff {print $0}')
if [ -n "$INDICES_TO_DELETE" ]; then
    echo "即将删除以下索引:"
    echo "$INDICES_TO_DELETE"
    for index in $INDICES_TO_DELETE; do
        echo "删除索引:$index"
        curl -s -X DELETE "$ES_HOST/$index"
        echo ""
    done
else
    echo "没有需要删除的索引。"
fi

注意事项:

  • 请确保索引命名格式是固定的(如 logs-2025.01.01app-20250101)。
  • 测试时先加上 echo 预览要删除的索引,确认无误后再实际删除。

使用 PowerShell 脚本(Windows 环境)

$esHost = "http://localhost:9200"
$retentionDays = 30
$cutoffDate = (Get-Date).AddDays(-$retentionDays).ToString("yyyy.MM.dd")
# 获取索引列表(假设索引名为 logs-yyyy.MM.dd)
$indices = Invoke-RestMethod "$esHost/_cat/indices/logs-*?h=index" | Select-String -Pattern "logs-\d{4}\.\d{2}\.\d{2}"
foreach ($index in $indices) {
    $datePart = $index -replace "logs-", ""
    if ($datePart -lt $cutoffDate) {
        Write-Host "删除索引: $index"
        Invoke-RestMethod -Method Delete "$esHost/$index"
    }
}

使用 Python 脚本(灵活,便于自定义)

from elasticsearch import Elasticsearch
from datetime import datetime, timedelta
es = Elasticsearch("http://localhost:9200")
retention_days = 30
cutoff = datetime.now() - timedelta(days=retention_days)
# 获取所有以 logs- 开头的索引
indices = es.indices.get(index="logs-*")
for index_name in indices:
    # 假设索引格式 logs-2025.01.01,提取日期部分
    try:
        date_str = index_name.split("-")[1]
        index_date = datetime.strptime(date_str, "%Y.%m.%d")
        if index_date < cutoff:
            print(f"删除索引: {index_name}")
            es.indices.delete(index=index_name)
    except:
        pass

使用 ILM(Index Lifecycle Management,生产环境最佳实践)

如果系统允许,建议直接在 Elasticsearch 层面配置 ILM 策略,无需额外脚本。

ILM 策略示例(删除 30 天前的索引):

PUT _ilm/policy/30_days_delete
{
  "policy": {
    "phases": {
      "hot": {
        "min_age": "0ms",
        "actions": {
          "set_priority": {
            "priority": 100
          }
        }
      },
      "delete": {
        "min_age": "30d",
        "actions": {
          "delete": {}
        }
      }
    }
  }
}

应用到索引模板:

PUT _index_template/logs_template
{
  "index_patterns": ["logs-*"],
  "template": {
    "settings": {
      "index.lifecycle.name": "30_days_delete"
    }
  }
}
场景 推荐方案
简单脚本、快速实现 Shell + curl
生产环境、灵活配置 Curator
已有 Python 栈 Python elasticsearch-py
长期维护、无需运维 ILM 策略(最佳)

重要安全建议:

  • 删除前先执行预览模式,确保不会误删有用数据。
  • 生产环境删除索引前请考虑是否需要数据备份先快照再删除
  • 建议将脚本通过 cron 或 Windows 任务计划程序定期执行。

抱歉,评论功能暂时关闭!