索引模板是一种在创建索引时告诉 Elasticsearch 如何配置索引的方法。
创建索引模板 index_template
包括,设置模板的mappings
,settings
, aliases
,以及模板的 匹配规则 index_patterns
。这些元素可以直接指定,也可通过模板组件 component_template
组合得到。
定义模板组件 component_template
PUT _component_template/component_template1
{
"template": {
"mappings": {
"properties": {
"@timestamp": {
"type": "date"
}
}
}
}
}
当新索引与模板匹配时,此组件模板会添加一个名为 @timestamp
映射的date
字段。
PUT _component_template/runtime_component_template
{
"template": {
"mappings": {
"runtime": {
"day_of_week": {
"type": "keyword",
"script": {
"source": "emit(doc['@timestamp'].value.dayOfWeekEnum.getDisplayName(TextStyle.FULL, Locale.ROOT))"
}
}
}
}
}
}
当新索引与模板匹配时,此组件模板会添加一个名为 day_of_week
映射的runtime
字段。
通过模板组件 component_template
组成 索引模板index_template
PUT _index_template/template_1
{
"index_patterns": ["te*", "bar*"],
"template": {
"settings": {
"number_of_shards": 1
},
"mappings": {
"_source": {
"enabled": true
},
"properties": {
"host_name": {
"type": "keyword"
},
"created_at": {
"type": "date",
"format": "EEE MMM dd HH:mm:ss Z yyyy"
}
}
},
"aliases": {
"mydata": { }
}
},
"priority": 500,
"composed_of": ["component_template1", "runtime_component_template"],
"version": 3,
"_meta": {
"description": "my custom"
}
}
index_patterns
:设置索引模板的匹配规则
template.settings
:设置索引模板的settings
template.mappings
:设置索引模板的mappings
template.aliases
:设置索引模板的aliases
priority
:设置索引模板的匹配优先级
composed_of
: 模板组件集合
索引模板使用
当ES索引新文档时, 会根据索引名匹配索引模板, 为指定的mapping字段生成对于的字段类型