python删除es索引

需求:删除4天前且pri.store.size大于1G的索引

复制代码
import logging
from datetime import datetime, timedelta
from elasticsearch import Elasticsearch

# 配置日志记录
logging.basicConfig(
    filename='index_deletion.log',
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

# 连接到 Elasticsearch 集群
es = Elasticsearch([{'scheme': 'http','host': '127.0.0.1', 'port': 9200}],
                   basic_auth=('elastic', 'IOT#1033#ff'))

# 检查连接是否成功
if es.ping():
    logging.info('成功连接到 Elasticsearch 集群')
else:
    logging.error('无法连接到 Elasticsearch 集群')
    exit()

# 计算五天前的日期
ten_days_ago = datetime.now() - timedelta(days=5)
date_str = ten_days_ago.strftime('%Y-%m-%d')

# 构建带有通配符的索引名称
index_pattern = f'*-{date_str}'

try:
    # 使用 cat.indices API 获取匹配索引的信息
    indices_info = es.cat.indices(index=index_pattern, format='json')
    if not indices_info:
        logging.info(f"未找到匹配 {index_pattern} 的索引信息")  
except Exception as e:
    logging.error(f"查询索引信息时出错: {e}")
exit()

# 存储需要删除的索引名称
indices_to_delete = []

# 遍历所有索引,找出 pri.store.size 大于 1GB 的索引
for index_info in indices_info:
    pri_store_size_str = index_info.get('pri.store.size')
    if pri_store_size_str:
        # 解析存储大小
        if pri_store_size_str.endswith('gb'):
            delete_info = {'index_name': index_info['index'], 'size': pri_store_size_str}
            indices_to_delete.append(delete_info)

#删除符合条件的索引
if indices_to_delete:
    for index in indices_to_delete:
        try:
            es.indices.delete(index=index['index_name'])
            logging.info(f"成功删除索引: {index['index_name']},大小:{index['size']}")
        except Exception as e:
            logging.error(f"删除索引 {index['index_name']} 时出错: {e}")
else:
    logging.info("没有找到 pri.store.size 大于 1GB 的索引")
复制代码

 

posted @   高佳丰  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
历史上的今天:
2024-03-04 prometheus 系统学习
点击右上角即可分享
微信分享提示