1. 索引模板
索引模板,故名思议,就是创建索引的模板,模板中包含公共的配置(settings
)和映射(Mapping
),并包含一个简单触发条件,及条件满足时使用该模板创建一个新的索引。
注意:模板只在创建索引时应用。更改模板不会对现有索引产生影响。当使用
create index API
时,作为create index
调用的一部分定义的设置/映射
将优先于模板中定义的任何匹配设置/映射
。
2. 模板操作
ES的模板CRUD
可由ES REST API
或Kibana Dev Tools
进行操作:
2.1 查看模板
REST API
curl -XGET localhost:9200/_template/template_name
Dev Tools
GET _template/template_name
2.2 删除模板
REST API
curl -XDELETE localhost:9200/_template/template_name
Dev Tools
DELETE _template/template_name
3. 索引模板示例
template
为模板匹配规则:
order
为模板优先级(当索引同时匹配多个模板,先应用数值小的模板,再以数值大的模板配置进行覆盖
)properties
中指定特定类型,否则则会自动匹配为dynamic_templates
中的text
或keyword
类型
{
"kong_template" : {
"order" : 1,
"version" : 60001,
"index_patterns" : [
"kong-*"
],
"settings" : {
"index" : {
"refresh_interval" : "5s"
}
},
"mappings" : {
"_default_" : {
"dynamic_templates" : [
{
"message_field" : {
"path_match" : "message",
"match_mapping_type" : "string",
"mapping" : {
"type" : "text",
"norms" : false
}
}
},
{
"string_fields" : {
"match" : "*",
"match_mapping_type" : "string",
"mapping" : {
"type" : "text",
"norms" : false,
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
}
}
}
],
"properties" : {
"@timestamp" : {
"type" : "date"
},
"@version" : {
"type" : "keyword"
},
"request.headers.remoteip" : {
"type" : "ip"
},
"geoip" : {
"dynamic" : true,
"properties" : {
"ip" : {
"type" : "ip"
},
"location" : {
"type" : "geo_point"
},
"latitude" : {
"type" : "half_float"
},
"longitude" : {
"type" : "half_float"
}
}
}
}
}
},
"aliases" : { }
}
}
4. 那如果能匹配到多个模板呢?
多个索引模板可能匹配一个索引,可以使用order属性为索引模板指定顺序。从顺序较小的开始寻找,order越大,越优先(前提是匹配模板表达式)。
例如:
PUT /_template/template_1
{
"index_patterns" : ["*"],
"order" : 0,
"settings" : {
"number_of_shards" : 1
},
"mappings" : {
"_doc" : {
"_source" : { "enabled" : false }
}
}
}
PUT /_template/template_2
{
"index_patterns" : ["te*"],
"order" : 1,
"settings" : {
"number_of_shards" : 1
},
"mappings" : {
"_doc" : {
"_source" : { "enabled" : true }
}
}
}
首先从order=0
进行匹配,由于其表达式为*
,则默认会全匹配,故首先尝试使用该模板,然后再遍历下一个模板,也就是order=1
的模板,如果匹配,则使用第二个模板的配置,如果不匹配,则使用第一个模板的配置,依次类推。
其匹配的具体实现逻辑大概如下:
- 对所有的模板按照
order
属性进行升序排序。 - 遍历所有的模板,进行表达式匹配,匹配成功,则设置为当前匹配模板,然后判断下一个,直到把所有的模板都处理过。
3、选最后匹配的模板当成最后的模板。
那如果存在多个模板,其order
相同,那其顺序能保证吗?
答案是不能保证,因为对所有模板进行排序的过程中,如果order
相同,其顺序无法得到保证。