原文网址:ES--为什么没有完全删除?_IT利刃出鞘的博客-CSDN博客
简介
本文介绍ES的删除策略:逻辑删除。
问题描述
ES删除索引
会立即释放空间,不存在所谓的“标记”逻辑。
ES关闭索引
会立即释放空间,不存在所谓的“标记”逻辑。会保存索引的数据。
ES删除文档
不会立刻删除,只是将文档标记为已删除(在.del文件里记录已删除的文档ID)。ES会在你往索引里写入数据后在后台物理删除标记为已删除的文档。注意:ES通过后台的segment merge清除已删除的数据(对当前的segment file进行处理)。
一个shard可能会有上百个segment file,有很大几率新旧文档存在于不同的segment里而无法物理删除。想要手动释放空间,只能是定期做一下force merge,并且将max_num_segments设置为1。
物理删除旧数据
法1.重启索引
# 关闭指定索引(Elasticsearch 7.x)
curl -X POST "http://localhost:9200/logs-2023-05-01/_close"
# 查看关闭状态
curl -X GET "http://localhost:9200/logs-2023-05-01/_stats?pretty"
# 打开索引
curl -X POST "http://localhost:9200/logs-2023-05-01/_open"
法2.强制合并
以保存近100天的数据为例:
- 第一步:delete_by_query删除近100天数据;
- 第二步:执行forcemerge操作,手动释放磁盘空间。
删除脚本如下:
#!/bin/sh
curl -H'Content-Type:application/json' -d'{
"query": {
"range": {
"pt": {
"lt": "now-100d",
"format": "epoch_millis"
}
}
}
}
' -XPOST "http://192.168.1.101:9200/logstash_*/
_delete_by_query?conflicts=proceed"
merge脚本如下:
#!/bin/sh
curl -XPOST 'http://192.168.1.101:9200/_forcemerge?
only_expunge_deletes=true&max_num_segments=1'
注意:此方法很耗性能,生产环境谨慎操作!
法3.用工具删除
ES官网工具:curator。作用:规划和管理ES的索引。支持常见操作:创建、删除、合并、reindex、快照等操作。
官网地址
Git地址:https://github.com/elastic/curator
安装向导
地址:https://www.elastic.co/guide/en/elasticsearch/client/curator/current/installation.html
注意:
- curator博客很多,但curator旧版本和新版本有较大差异,建议参考官网最新手册部署。
- 旧版本命令行方式新版本已不支持。
命令行操作
$ curator --help
Usage: curator [OPTIONS] ACTION_FILE
Curator for Elasticsearch indices.
See http://elastic.co/guide/en/elasticsearch/client/curator/current
Options:
--config PATH Path to configuration file. Default: ~/.curator/curator.yml
--dry-run Do not perform any changes.
--version Show the version and exit.
--help Show this message and exit.
核心是配置文件config.yml:配置要连接的ES地址、日志配置、日志级别等;
- 执行文件action.yml: 配置要执行的操作(可批量)、配置索引的格式(前缀匹配、正则匹配方式等)
curator适用场景
最重要的是:
- 仅以删除操作为例:curator可以非常简单地删除x天后的索引的前提是:索引命名要遵循特定的命名模式——如:以天为命名的索引:logstash_2018.04.05。
- 命名模式需要和action.yml中的delete_indices下的timestring对应。