批量删除es索引

当Elasticsearch集群状态变为red,且存在大量unassigned分片时,可能是由于旧的日期索引未被正确删除。通过执行`curl -XGET ip:port/_cat/shards | grep UNASSIGNED`可以找到这些索引。为恢复成green状态,需要编写脚本批量删除以特定日期格式(yyyy-MM-dd)命名的旧索引,确保不会影响新索引的创建和数据迁移。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

发现elasticsearch集群的状态是red,unassign的分片数很多,看了下都是些旧的日期的索引(应该是定时任务删除失败导致的)。
curl -XGET ip:port/_cat/shards | grep UNASSIGNED
数量有几百个,写个脚本处理下,先恢复成green。red状态好像会影响索引创建和数据迁移
先把需要删除的索引导出到文件

curl -XGET ip:port/_cat/shards | grep UNASSIGNED >> needDelIndex.txt
确认下要删除的索引列表。没问题就执行下面删除shell(es的ip和端口需要修改下)

#!/bin/bash
echo "$1"
esUrl=${esip}:${esport}

indexfile=needDelIndex.txt
#cp -f /dev/null ${indexfile}
#curl -XGET ip:port/_cat/shards | grep UNASSIGNED >> needDelIndex.txt
if [ ! -f ./${indexfile} ]; then
    echo $indexfile not exists
    exit 0
fi

logfile=esindex_del.`date +"%m-%d"`.log
cp -f /dev/null ${logfile}

lastIndexName="test"

for item in `cat ${indexfile} | awk  '{print $1}'`
do
    if [ "$item" = "error" ]
    then
        continue
    fi

    if [ "$item" != "$lastIndexName" ]
    then
        curl -XDELETE ${esUrl}/${item} >> ${logfile}
        echo ---------${item} `date` >> ${logfile}
        sleep 5
    fi
    lastIndexName=${item}

done

因为我们的索引是按天创建的,索引名前缀是yyyy-MM-dd, 保留一段时间后需要批量删除。shell的第一个参数为yyyy-MM-dd,将删除该天及以前的旧索引

#!/bin/bash

esUrl=${esip}:${esport}
echo "$1"
if [ $# -ge 1 ]
then
    deleteDate=$1
else
    echo "please inpust detete esindex's date(yyyy-MM-dd)"
    exit 0
fi

indexfile=esindex.info
cp -f /dev/null ${indexfile}
curl  '${esUrl}/_cat/indices' >> ${indexfile}

logfile=esindex_del.`date +"%m-%d"`.out
cp -f /dev/null ${logfile}

for item in `cat ${indexfile} | awk  '{print $3}'`
do
    if [ "$item" = "error" ]
    then
        continue
    fi

    parameter=${esUrl}/${item}
    indexdate=${item:0:10}
    if [ "$indexdate" = "$deleteDate" ]
    then
        curl -XDELETE ${parameter} >> ${logfile}
        echo ---------${item}  >> ${logfile}
        sleep 5
    elif [[ "$indexdate" < "$deleteDate" ]]
    then
        curl -XDELETE ${parameter} >> ${logfile}
        echo ---------${item}  >> ${logfile}
        sleep 5
    fi
done

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值