Elasticsearch:Template
概述
-
Template(模板)规定了Elasticsearch在创建索引时是如何对其进行配置的;
-
如果索引与多个索引模板匹配,则使用优先级最高的索引模板。 模板的
priority
(旧版本中为order
)字段定义了模板的优先级。 -
索引在创建时显式声明的配置优先级高于其匹配的模板中的配置。
分类
模板有两种类型:Index template(索引模板)和Component templates(组件模板)。
- 组件模板是可以重用的构建组件,用于配置索引的Mappings、Settings和Aliases(别名)。 组件模板还可以用来构造索引模板,但它们不会直接应用于一组索引。
- 索引模板既可以是一个包含组件模板的集合,也可以直接指定索引的Mappings、Settings和Aliases。
应用
首先使用Elasticsearch API创建两个组件模板,它们分别对@timestamp
和ip_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要低于预创建的索引模板。
koktlzz.github.io