当前位置: 首页 > ops >正文

python定时删除指定索引

脚本

import logging
from datetime import datetime, timedelta
from elasticsearch import Elasticsearch# 配置日志记录
logging.basicConfig(filename='delete_uat_indices.log',level=logging.INFO,format='%(asctime)s - %(levelname)s - %(message)s'
)# Elasticsearch 集群的连接信息
ELASTICSEARCH_HOST = "http://192.178.18.209:9200"  # 修改为你的 Elasticsearch 地址
USERNAME = "elastic"  # 修改为你的用户名
PASSWORD = "7F9L%mYWjWtb"  # 修改为你的密码
INDEX_PATTERN = "*uat*"  # 匹配带有 "uat" 的索引def delete_old_indices():# 连接到 Elasticsearch 集群es = Elasticsearch([ELASTICSEARCH_HOST], basic_auth=(USERNAME, PASSWORD))# 检查连接是否成功if not es.ping():logging.error("无法连接到 Elasticsearch 集群")returnlogging.info("成功连接到 Elasticsearch 集群")# 计算 5 天前的日期five_days_ago = datetime.now() - timedelta(days=2)date_str = five_days_ago.strftime('%Y.%m.%d')# 获取所有索引(确保使用关键字参数)try:indices = es.indices.get(index="*uat*")  # 使用关键字参数except Exception as e:logging.error(f"获取索引列表失败: {e}")return# 过滤出符合条件的索引indices_to_delete = []for index_name in indices.keys():if not index_name.startswith(".") and "uat" in index_name:# 提取索引名称中的日期部分try:index_date_str = index_name.split("-")[-1]  # 假设日期在索引名称的最后部分index_date = datetime.strptime(index_date_str, '%Y.%m.%d')if index_date < five_days_ago:indices_to_delete.append(index_name)except Exception as e:logging.warning(f"无法解析索引名称 {index_name} 的日期部分: {e}")if not indices_to_delete:logging.info(f"未找到符合条件的索引: 包含 'uat' 且日期为 {date_str}")return# 删除符合条件的索引for index in indices_to_delete:try:es.indices.delete(index=index)logging.info(f"成功删除索引: {index}")except Exception as e:logging.error(f"删除索引 {index} 时失败: {e}")if __name__ == "__main__":delete_old_indices()

定时任务

crontab -e
#每天23点30定时删除5天前的uat环境日志
30 23 * * * /usr/local/python-3.9/bin/python3.9 /data/delete_old_indices/delete_uat_old_indices.py >/dev/null 2>&1

http://www.xdnf.cn/news/8269.html

相关文章:

  • 谷歌浏览器调试python pygui程序
  • 国产化Word处理控件Spire.Doc教程:使用 Python 创建 Word 文档的详细指南
  • 企业级云原生爬虫架构与智能优化
  • LET 2025盛大开幕!数智工厂×智慧物流×机器人,一展get创新科技
  • VSCode 插件 GitLens 破解方法
  • 线程池介绍,分类,实现(工作原理,核心组成,拒绝策略),固态线程池的实现+详细解释(支持超时取消机制和不同的拒绝策略)
  • [性能优化] 数据库连接池(Connection Pooling)原理及其在Java/Python应用中的配置
  • 大模型高效微调方法综述:P-Tuning软提示与lora低秩微调附案例代码详解
  • 在 ABP VNext 中集成 OpenCvSharp:构建高可用图像灰度、压缩与格式转换服务
  • 自制操作系统day10叠加处理
  • 数据库系统概论(九)SQL连接查询语言超详细讲解(附带例题,表格详细讲解对比带你一步步掌握)
  • MCP 服务与 Agent 协同架构的理论基石:从分布式智能到生态化协作
  • OSI 深度安全防御体系架构深度剖析
  • Java转Go日记(五十六):gin 渲染
  • 可视化大屏实现全屏或非全屏
  • iOS使用Metal对采集视频进行渲染
  • 【YOLO】Docker搭建镜像+运行容器
  • 如何制作令人印象深刻的UI设计?
  • HTTP 协议详解
  • 全金属工业防爆散热风扇风压与散热效果的关系
  • 无人机飞行间隔安全智能评估、安全风险评估
  • 单片机——实现交通信号灯管理
  • 【mindspore系列】- 算子源码分析
  • 超越感官的实相:声、光、气味的科学与哲学探微
  • Azure 公有云基础架构与核心服务:从基础到实践指南
  • C++——STL——封装红黑树实现mymap与myset
  • SpringBoot3+Vue3开发宾馆住房管理系统
  • 如何在UI设计中更好地平衡美学与功能性?
  • 【论文精读】2022 CVPR--RealBasicVSR现实世界视频超分辨率(RealWorld VSR)
  • Go语言爬虫系列教程(二) HTTP请求与响应处理详解