51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

elasticsearch按月建索引,定时删除3个月前索引

1.建模板


#log_template为模板名称可更改

PUT /_template/log_template?pretty

{

#以log开头的索引都会使用此模板创建

  "template": "log*",

 

  "settings": {

#设置es分片数量,可不设

    "number_of_shards": 10

 

  },

 

  "mappings": {

#设置模板中属性,可不设置

      "properties": {

 

        "name": {

 

          "type": "text",

 

          "index": "true"

 

        }

      }

  },

#索引别名,查询时可使用别名查询索引

  "aliases": {"log":{}}

 

}

2.创建索引时携带年月(如果按日删除需携带年月日) 


例: log-202208


3.根据别名查询数据


#log为别名

GET /log/_search

4.定时删除过期数据,本文使用shell脚本


#!/bin/bash

  

function delete_indices() {

#comp_date=`date -d "7 day ago" +"%Y-%m-%d"`  7天前

    comp_date=`date -d "3 month ago" +"%Y-%m-%d"`

    date1="$1"

    date2="$comp_date"

 

    t1=`date -d "$date1" +%s`

    t2=`date -d "$date2" +%s`

    if [ $t1 -le $t2 ]; then

        echo "$1时间早于$comp_date,进行索引删除"

        #转换一下格式,将类似2022-10-01格式转化为20221001

        curl -XDELETE http://192.168.3.111:9200/*$2

    fi

}

#如果按日删除 需将grep '[[:digit:]]\{6\}' 改为grep '[[:digit:]]\{8\}'

curl -XGET http://192.168.3.111:9200/_cat/indices | awk -F" " '{print $3}' | awk -F"-" '{print $NF}' | grep '[[:digit:]]\{6\}' | sort | uniq  | while read line

do

 #如果按日删除 需将p="${line:0:4}-${line:4:2}-01" 改为 p="${line:0:4}-${line:4:2}-${line:6}"

    p="${line:0:4}-${line:4:2}-01"

    o="${line}"

    #调用索引删除函数

    delete_indices $p $o

done

————————————————


                            版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

                        

原文链接:https://blog.csdn.net/weixin_57581505/article/details/126588346


赞(3)
未经允许不得转载:工具盒子 » elasticsearch按月建索引,定时删除3个月前索引