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

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.lryc.cn/news/2384816.html

相关文章:

  • 基于OAuth2-proxy和Keycloak为comfyui实现SSO
  • SmartSoftHelp 之 SQL Server 数据库安全备份与安全还原详解---深度优化版:SmartSoftHelp DeepCore XSuite
  • Spring 代理与 Redis 分布式锁冲突:一次锁释放异常的分析与解决
  • 【数据结构】队列的完整实现
  • 2025 全球优质 AI 产品深度测评:从通用工具到垂直领域的技术突围 —— 轻量聚合工具篇
  • Python爬虫实战:获取天气网最近一周北京的天气数据,为日常出行做参考
  • 根据YOLO数据集标签计算检测框内目标面积占比(YOLO7-10都适用)
  • Helm简介、安装、配置、使用!
  • LLM笔记(九)KV缓存(2)
  • 开发 前端搭建npm v11.4.0 is known not to run on Node.js v14.18.1.
  • LVS 负载均衡集群应用实战
  • MySQL——基本查询内置函数
  • Day34打卡 @浙大疏锦行
  • 【Jitsi Meet】(腾讯会议的平替)Docker安装Jitsi Meet指南-使用内网IP访问
  • AdGuard解锁高级版(Nightly)_v4.10.36 安卓去除手机APP广告
  • C++修炼:红黑树的模拟实现
  • 基于Python+YOLO模型的手势识别系统
  • 自制操作系统day10叠加处理
  • docker初学
  • ## Docker 中 Elasticsearch 启动失败:日志文件权限问题排查与解决
  • 鸿蒙Flutter实战:23-混合开发详解-3-源码模式引入
  • leetcode:2469. 温度转换(python3解法,数学相关算法题)
  • 【软件安装】Windows操作系统中安装mongodb数据库和mongo-shell工具
  • 跨域问题及其CORS解决方案:gin框架中配置跨域
  • 记共享元素动画导致的内存泄露
  • Flyweight(享元)设计模式 软考 享元 和 代理属于结构型设计模式
  • Win/Linux安装flash attention2
  • 【原创】ubuntu22.04下载编译AOSP 15
  • 服务器网络配置 netplan一个网口配置两个ip(双ip、辅助ip、别名IP别名)
  • 响应面法(Response Surface Methodology ,RSM)