使用pyhon脚本删除50天前的日志
pip install Elasticsearch
pip install datetime
!/usr/bin/python3
from elasticsearch import Elasticsearch
from datetime import datetime, timedelta
Elasticsearch服务器地址,默认本地为'localhost',可按需替换
es_host = "localhost"
Elasticsearch服务器端口,默认9200,按需替换
es_port = 9200
创建Elasticsearch客户端连接对象
es = Elasticsearch([{"host": es_host, "port": es_port}])
计算50天前的日期
fifty_days_ago = datetime.now() - timedelta(days=50)
fifty_days_ago_str = fifty_days_ago.strftime('%Y.%m.%d')
遍历所有索引
try:
all_indices = es.indices.get_alias("*")
for index in all_indices:
# 判断索引名是否包含'2024'
if '2024' in index and 'externalorder' not in index:
index_info = es.indices.get(index)
creation_date_timestamp = int(index_info[index]['settings']['index']['creation_date'])
# 将时间戳(假设此处为毫秒)转换为秒(Python中时间相关函数常用秒为单位处理)
creation_date_seconds = creation_date_timestamp / 1000
# 通过fromtimestamp方法将秒数转换为datetime对象
creation_date = datetime.fromtimestamp(creation_date_seconds)
# 以下是示例中与50天前时间比较的逻辑,假设前面已经正确计算好50天前的时间并存储在fifty_days_ago变量中fifty_days_ago = datetime.now() - timedelta(days=50)if creation_date < fifty_days_ago:response = es.indices.delete(index=index)request_timeout=30print(f"索引 {index} 删除结果: {response}")
except Exception as e:
print(f"删除索引时出现错误: {str(e)}")