python清除一个月以前的ES索引文档数据
先查看一下mysql 数据,看一下那一列是日期字段
看到是 edittime 列
以下是 python 脚本
vim delete_old_noticeresult.py
import datetime
from elasticsearch import Elasticsearch, RequestError
import logging
# 配置日志
logging.basicConfig(filename='/var/log/es-index/delete_old_bidnotice.log', level=logging.INFO, format='%(asctime)s - %(message)s')
def delete_old_documents():
try:
# 获取当前日期
now = datetime.datetime.now()
logging.info("Current date and time: %s", now)
# 计算一个月前的日期
one_month_ago = now - datetime.timedelta(days=30)
logging.info("Date and time one month ago: %s", one_month_ago)
# 创建 Elasticsearch 连接
es = Elasticsearch(['http://127.0.0.1:9200'])
logging.info("Elasticsearch client created.")
# 构造删除请求
delete_query = {
"query": {
"range": {
"edittime.raw": {
"lt": one_month_ago.strftime("%Y-%m-%dT%H:%M:%SZ") # 格式化日期为Elasticsearch支持的格式
}
}
}
}
logging.info("Delete query constructed: %s", delete_query)
# 发送删除请求,并等待完成
response = es.delete_by_query(index='noticeresult', body=delete_query, wait_for_completion=True)
logging.info("Delete request sent. Response: %s", response)
except RequestError as e:
logging.error("Error deleting documents: %s", e)
if __name__ == "__main__":
delete_old_documents()
# 安装 模块
pip install elasticsearch
# 创建存放日志目录
mkdir /var/log/es-index/
1.在删除操作中,由于 edittime 是 text 类型,直接对 edittime 字段进行范围查询可能会导致不准确的结果。应该使用 edittime.raw 字段来进行精确的范围查询。
2.日期格式:确保 edittime.raw 的格式与你的 Elasticsearch 索引中字段的实际格式一致。如果字段没有 .raw 后缀,请移除它。
3.索引名称:确认 noticeresult 是你要删除文档的正确索引名称。
4.时间戳格式:two_months_ago.strftime(“%Y-%m-%dT%H:%M:%SZ”) 是正确的日期格式。
5.日志路径:确保 /var/log/es-index/delete_old_noticeresult.log 路径存在,并且你的脚本有写权限。
6.Elasticsearch 配置:如果 Elasticsearch 需要认证或其他配置,请在 Elasticsearch 实例创建时提供相应参数。
7.异常处理:可以进一步捕获和处理其他可能的异常(如连接失败)。
创建索引命令
PUT /noticeresult
{
"settings": {
"number_of_shards": 1,
"number_of_replicas": 0,
"analysis": {
"analyzer": {
"htmlStripAnalyzer": {
"filter": ["lowercase", "classic", "trim"],
"char_filter": ["html_strip"],
"type": "custom",
"tokenizer": "standard"
},
"chinese_analyzer": {
"type": "custom",
"tokenizer": "ik_max_word" // 使用 IK 分词器进行中文分词
}
},
"char_filter": {
"html_strip": {
"type": "html_strip"
}
},
"tokenizer": {
"ik_max_word": {
"type": "ik_max_word"
}
}
}
},
"mappings": {
"dynamic": "true",
"_source": {
"excludes": [
"fujcontent",
"projdetail"
]
},
"date_detection": false,
"numeric_detection": false,
"properties": {
"results_id": {
"type": "integer",
"fields": {
"raw": {
"type": "keyword",
"null_value": "NULL",
"ignore_above": 256
}
}
},
"notice_num": {
"type": "text",
"fields": {
"raw": {
"type": "keyword",
"null_value": "NULL",
"ignore_above": 256
}
}
},
"organ": { "type": "text", "analyzer": "htmlStripAnalyzer" },
....
....
"editip": { "type": "text", "analyzer": "htmlStripAnalyzer" }, // 使用中文分析器
"editname": { "type": "keyword" },
"putip": { "type": "keyword" },
"edittime": {
"type": "text",
"fields": {
"raw": {
"type": "keyword",
"null_value": "NULL",
"ignore_above": 256
}
}
},
....
....
"urlhost": {
"type": "text",
"fields": {
"raw": {
"type": "keyword",
"null_value": "null",
"ignore_above": 256
}
}
},
"attachment_info": { "type": "integer" }
}
}
}
创建索引时查看 edittime 字段的映射,这个字段是 text 类型,并且有一个 raw 子字段,类型是 keyword。
这意味着你可以在查询中使用 edittime.raw 来进行精确匹配查询。
对应上 上方 python 的精确匹配。
执行结果
python delete_old_noticeresult.py
2024-09-13 14:52:29,292 - Current date and time: 2024-09-13 14:52:29.292836
2024-09-13 14:52:29,293 - Date and time one month ago: 2024-08-14 14:52:29.292836
2024-09-13 14:52:29,296 - Elasticsearch client created.
2024-09-13 14:52:29,296 - Delete query constructed: {‘query’: {‘range’: {‘edittime.raw’: {‘lt’: ‘2024-08-14T14:52:29Z’}}}}
2024-09-13 14:52:29,657 - POST http://127.0.0.1:9200/noticeresult/_delete_by_query?wait_for_completion=true [status:200 duration:0.360s]
2024-09-13 14:52:29,658 - Delete request sent. Response: {‘took’: 353, ‘timed_out’: False, ‘total’: 0, ‘deleted’: 95, ‘batches’: 0, ‘version_conflicts’: 0, ‘noops’: 0, ‘retries’: {‘bulk’: 0, ‘search’: 0}, ‘throttled_millis’: 0, ‘requests_per_second’: -1.0, ‘throttled_until_millis’: 0, ‘failures’: []}