0
点赞
收藏
分享

微信扫一扫

删除两个月前的ES索引

夏天的枫_ 2023-04-15 阅读 66

cat a.sh
#!/bin/bash

# Define variables
IP="172.18.10.96"
DAYS_TO_KEEP=60
CURRENT_DATE=$(date +%Y-%m-%d)

# Define index prefixes
INDEX_PREFIXES=(
    "test-clavaplus-api"
    "test-blavaplus-api"
    "test-lava-mall-client"
)

# Loop through each index prefix and delete old indexes
for PREFIX in "${INDEX_PREFIXES[@]}"; do
    # Get all indexes with the current prefix
    INDEXES=$(curl -sS "${IP}:9200/_cat/indices/${PREFIX}-*" | awk '{print $3}')

    # Loop through each index and check the date
    for INDEX in $INDEXES; do
        # Get the date from the index name
        INDEX_DATE=${INDEX#${PREFIX}-}
        INDEX_DATE=$(echo $INDEX_DATE | sed 's/\./-/g') # Replace dots with dashes to match date format
        DATE_DIFF=$((($(date -d "${CURRENT_DATE}" +%s) - $(date -d "${INDEX_DATE}" +%s))/(60*60*24)))

        # If the date difference is greater than the threshold, delete the index
        if [[ ${DATE_DIFF} -gt ${DAYS_TO_KEEP} ]]; then
            echo "Deleting index ${INDEX}"
            curl -sS -XDELETE "${IP}:9200/${INDEX}"
        fi
    done
done

2 / 2

这一步使用了字符串截取的方式,将${INDEX}字符串中${PREFIX}-的部分删除,得到${INDEX_DATE},即索引名称中日期部分。

例如,对于索引名称test-clavaplus-api-2023.04.15和前缀test-clavaplus-api${PREFIX}-的部分就是test-clavaplus-api-,删除后得到日期部分2023.04.15


这一句代码是计算当前日期与索引名称中的日期之间相差的天数。

${CURRENT_DATE} 存储的是当前日期的字符串,格式为 YYYY-MM-DD

${INDEX_DATE} 存储的是从 Elasticsearch 中检索出的索引名称中的日期,这个日期是一个字符串,格式为 YYYY.MM.DD

$(date -d "${CURRENT_DATE}" +%s)${CURRENT_DATE} 转换为 Unix 时间戳,即从 1970 年 1 月 1 日 00:00:00 UTC 到 ${CURRENT_DATE} 的秒数。

$(date -d "${INDEX_DATE}" +%s)${INDEX_DATE} 转换为 Unix 时间戳,即从 1970 年 1 月 1 日 00:00:00 UTC 到 ${INDEX_DATE} 的秒数。

$((...)) 是 Bash 的算术扩展语法,用于计算括号中的算术表达式的值。

$(date -d "${CURRENT_DATE}" +%s) - $(date -d "${INDEX_DATE}" +%s) 计算 ${CURRENT_DATE}${INDEX_DATE} 相差的秒数。

/ (60*60*24) 将相差的秒数转换为相差的天数。其中 (60*60*24) 表示一天的秒数。


执行

[root@intranetsystem-gptools ~]# sh a.sh  
Deleting index test-clavaplus-api-2023.03.30
{"acknowledged":true}Deleting index test-clavaplus-api-2023.03.31
{"acknowledged":true}Deleting index test-clavaplus-api-2023.03.29
{"acknowledged":true}Deleting index test-blavaplus-api-2023.03.29
{"acknowledged":true}Deleting index test-lava-mall-client-2023.03.30
{"acknowledged":true}Deleting index test-lava-mall-client-2023.03.31

举报

相关推荐

0 条评论