写一个shell脚本,功能是删除elasticsearch上超过7天的索引
时间: 2024-04-15 16:29:29 浏览: 103
当然可以!以下是一个简单的Shell脚本示例,用于删除Elasticsearch中超过7天的索引:
```bash
#!/bin/bash
# Elasticsearch的主机和端口
HOST="localhost"
PORT=9200
# 获取当前日期并计算7天前的日期
CURRENT_DATE=$(date +%Y-%m-%d)
SEVEN_DAYS_AGO=$(date -d "7 days ago" +%Y-%m-%d)
# 获取所有索引
indices=$(curl -s -X GET "$HOST:$PORT/_cat/indices?h=index")
# 遍历每个索引并删除超过7天的索引
for index in $indices; do
# 检查索引创建日期是否超过7天
created_date=$(curl -s -X GET "$HOST:$PORT/$index/_settings?flat_settings=true" | grep -Po "(?<=index\.creation_date\":\")[^\"]*")
if [[ "$created_date" < "$SEVEN_DAYS_AGO" ]]; then
echo "Deleting index: $index"
curl -X DELETE "$HOST:$PORT/$index"
fi
done
echo "Index cleanup completed."
```
使用方法:
1. 将以上代码保存为一个脚本文件(例如:`cleanup_indices.sh`)。
2. 确保您具有执行脚本的权限:`chmod +x cleanup_indices.sh`。
3. 运行脚本:`./cleanup_indices.sh`。
脚本将连接到本地主机(localhost)上的Elasticsearch实例,默认端口为9200。如果您的Elasticsearch实例托管在不同的主机或端口上,请相应地修改`HOST`和`PORT`变量。
请注意,执行此脚本将永久删除超过7天的索引,请谨慎操作,并确保您已经备份了重要数据。
阅读全文
相关推荐
















