MENU

ElasticSearch(ES)中的模板、索引库别名

April 23, 2019 • 学习记录

Index Template(索引模板)

  • 在工作中针对一批大量数据存储的时候需要使用多个索引库,如果手工指定每个索引库的配置信息(settings和mappings)的话就很麻烦了。

创建模板

注意:order值大的模板内容会覆盖order值小的。

参考官网

curl -H "Content-Type: application/json" -XPUT localhost:9200/_template/template_1 -d '
{
    "template" : "*",
    "order" : 0,
    "settings" : {
        "number_of_shards" : 1
    },
    "mappings" : {
        "type1" : {
            "_source" : { "enabled" : false }
        }
    }
}
'
curl -XPUT localhost:9200/_template/template_2 -d '
{
    "template" : "te*",
    "order" : 1,
    "settings" : {
        "number_of_shards" : 1
    },
    "mappings" : {
        "type1" : {
            "_source" : { "enabled" : true }
        }
    }
}
'

查看模板

curl -XGET hadoop120:9200/_template/temp*?pretty

删除模板

curl -XDELETE hadoop120:9200/_template/temp_1

Index alias(索引别名)

索引别名应用场景

  • 公司使用es收集应用的运行日志,每个星期创建一个索引库,这样时间长了就会创建很多的索引库,操作和管理的时候很不方便。
  • 由于新增索引数据只会操作当前这个星期的索引库,所以就创建了两个别名
  • curr_week:这个别名指向这个星期的索引库,新增数据操作这个索引库。
  • last_3_month:这个别名指向最近三个月的所有索引库,因为我们的需求是查询最近三个月的日志信息。
  • 后期只需要修改这两个别名和索引库之间的指向关系即可。应用层代码不需要任何改动。
  • 还要把三个月以前的索引库close掉,留存最近一年的日志数据,一年以前的数据删除掉。
  • ES默认对查询的索引分片总数量有限制,默认是1000个,使用通配符查询多个索引库的时候会发生这个问题,通过别名可以解决这个问题。

代码:

#增加索引别名
curl -H "Content-Type: application/json" -XPOST 'http://localhost:9200/_aliases' -d '
{
    "actions" : [
        { "add" : { "index" : "test1", "alias" : "alias1" } }
    ]
}'
#删除索引别名
curl -H "Content-Type: application/json" -XPOST 'http://localhost:9200/_aliases' -d '
{
    "actions" : [
        { "remove" : { "index" : "test1", "alias" : "alias1" } }
    ]
}'
#可以同时增加多个索引别名

curl -H "Content-Type: application/json" -XPOST 'http://localhost:9200/_aliases' -d '
{
    "actions" : [
        { "add" : { "index" : "test1", "alias" : "alias1" } },
        { "add" : { "index" : "test2", "alias" : "alias1" } }
    ]
}'