Elasticsearch:Template

概述#

  • Template(模板)规定了Elasticsearch在创建索引时是如何对其进行配置的;

  • 如果索引与多个索引模板匹配,则使用优先级最高的索引模板。 模板的priority(旧版本中为order)字段定义了模板的优先级。

  • 索引在创建时显式声明的配置优先级高于其匹配的模板中的配置。

分类#

模板有两种类型:Index template(索引模板)和Component templates(组件模板)。

  • 组件模板是可以重用的构建组件,用于配置索引的Mappings、Settings和Aliases(别名)。 组件模板还可以用来构造索引模板,但它们不会直接应用于一组索引。
  • 索引模板既可以是一个包含组件模板的集合,也可以直接指定索引的Mappings、Settings和Aliases。

应用#

首先使用Elasticsearch API创建两个组件模板,它们分别对@timestampip_address字段的Mapping方式进行了配置:

PUT _component_template/component_template1   
{
  "template": {
    "mappings": {
      "properties": {
        "@timestamp": {
          "type": "date"
        }
      }
    }
  }
}

PUT _component_template/other_component_template
{
  "template": {
    "mappings": {
      "properties": {
        "ip_address": {
          "type": "ip"
        }
      }
    }
  }
}

然后我们创建一个索引模板,它是上述两个组件模板的集合,同时还对索引的分片数、别名以及host_name字段的Mapping方式进行了相关配置:

PUT _index_template/template_1
{
  "index_patterns": ["te*", "bar*"],       // 索引名称开头为te和bar的索引将会匹配该模板
  "template": {
    "settings": {
      "number_of_shards": 1
    },
    "mappings": {
      "properties": {
        "host_name": {
          "type": "keyword"
        }
    },
    "aliases": {
      "mydata": { }
    }
  },
  "priority": 200,
  "composed_of": ["component_template1", "other_component_template"],
  "version": 3,
  "_meta": {
    "description": "my custom"
  }
}

测试#

simulation API可以帮助我们测试索引模板的应用效果,主要有以下几种方式:

测试索引模板对某一类样式索引的配置效果。例如我们之前创建的索引模板template_1 ,其index_patterns参数为["te*", "bar*"],那么便可以使用这种方式来测试其对名称开头为"te"的索引的配置效果(索引te-01并不存在):

POST /_index_template/_simulate_index/te-000001

测试一个现有模板(template_1)的配置效果:

POST /_index_template/_simulate/template_1

为了保证创建的索引模板符合预期,我们还可以模拟定义一个索引模板:

POST /_index_template/_simulate
{
  "index_patterns": ["te*"],
  "template": {
    "settings" : {
        "index.number_of_shards" : 3
    }
  },
  "composed_of": ["component_template1", "other_component_template"]
}

返回结果:

{
  "template" : {
    "settings" : {
      "index" : {
        "number_of_shards" : "3"    // 模板创建时显式声明的配置优先级高于组件模板中的配置
      }
    },
    "mappings" : {                  // 继承自组件模板
      "properties" : {   
        "@timestamp" : {
          "type" : "date"
        },
        "ip_address" : {
          "type" : "ip"
        }
      }
    },
    "aliases" : { }
  },
  "overlapping" : [
    {
      "name" : "template_1",
      "index_patterns" : [
        "bar*",
        "te*"
      ]
    }
  ]
}

我们预创建的索引模板匹配了名称开头为te的索引,而已存在的模板template_1也与之匹配,因此返回结果中出现了overlapping的相关信息。在模拟中,其他重叠模板的priority要低于预创建的索引模板。

posted @   koktlzz  阅读(740)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示
主题色彩