美文网首页ELK服务器技术
Elasticsearch的索引自动清理及自定义清理

Elasticsearch的索引自动清理及自定义清理

作者: GoGooGooo | 来源:发表于2018-01-04 11:22 被阅读17次

    近发现elasticsearch近期索引文件大的吓人,清理了下之前的索引文件,发现服务器性能大大的减轻了一半,想一直保留近一个月的索引文件,但是又不想每个月手动清楚,在此写了一个小脚本

    查询索引:

    curl -XGET 'http://127.0.0.1:9200/_cat/indices/?v'
    

    一、 手动删除

    rm -rf *2017-03-*
    

    二、api删除

    curl -XDELETE 'http://127.0.0.1:9200/logstash-2016-07-*'
    

    清理掉了所有 3月份的索引文件,我发现curl 删除比rm删除要快出很多

    三、脚本加api删除(推荐)

     cat es-index-clear.sh
    
    #!/bin/bash
    ######################################################
    # $Name:        clean_es_index.sh
    # $Version:     v1.0
    # $Function:    clean es log index
    # $Author:      sjt
    # $Create Date: 2018-05-14
    # $Description: shell
    ######################################################
    #本文未加文件锁,需要的可以加
    #脚本的日志文件路径
    CLEAN_LOG="/app/elk/es/clean_es_index.log"
    #索引前缀
    INDEX_PRFIX="backstage_logs"
    #elasticsearch 的主机ip及端口
    SERVER_PORT=192.168.31.163:9200
    #取出已有的索引信息
    INDEXS=$(curl -s "${SERVER_PORT}/_cat/indices?v" |grep "${INDEX_PRFIX}"|awk '{print $3}')
    #删除多少天以前的日志,假设输入10,意味着10天前的日志都将会被删除
    DELTIME=30
    # seconds since 1970-01-01 00:00:00 seconds
    SECONDS=$(date -d  "$(date  +%F) -${DELTIME} days" +%s)
    #判断日志文件是否存在,不存在需要创建。
    if [ ! -f  "${CLEAN_LOG}" ]
    then
    touch "${CLEAN_LOG}"
    fi
    #删除指定日期索引
    echo "----------------------------clean time is $(date +%Y-%m-%d_%H:%M:%S) ------------------------------" >>${CLEAN_LOG}
    for del_index in ${INDEXS}
    do
        indexDate=$( echo ${del_index} |cut -d "-" -f 2 )
        format_date=$(echo ${indexDate}| sed 's/\.//g')
        format_date=$(echo ${indexDate}| sed 's/-//g')
        #根据索引的名称的长度进行切割,不同长度的索引在这里需要进行对应的修改
        indexSecond=$( date -d ${format_date} +%s )
        if [ $(( $SECONDS- $indexSecond )) -gt 0 ]
            then
            echo "${del_index}" >> ${CLEAN_LOG}
            #取出删除索引的返回结果
            delResult=`curl -s  -XDELETE "${SERVER_PORT}/"${del_index}"?pretty" |sed -n '2p'`
            #写入日志
            echo "clean time is $(date)" >>${CLEAN_LOG}
            echo "delResult is ${delResult}" >>${CLEAN_LOG}
        fi
    done
    

    四、添加到任务计划

    # 进入crontab编辑模式
    crontab -e 
    
    # 在crontab编辑模式中输入
    10 1 * * * sh /app/elk/es/es-index-clear.sh > /dev/null 2>&1
    

    五、其他任务命令

    # 查看任务计划
    crontab -u root -l
    
    # 清空任务计划
    crontab -r
    

    相关文章

      网友评论

      本文标题:Elasticsearch的索引自动清理及自定义清理

      本文链接:https://www.haomeiwen.com/subject/zaxrnxtx.html