前言
当集群上的索引越来越多时,可以使用 Index Templates 帮助你设定 Mappings 和 Settings。并按照一定的规则,自动匹配到新创建的索引之上。
1. Index Template
集群上如果保存的是日志,为了更好的管理数据,需要每天都创建一个索引。创建索引需要创建 Settings 和 Mappings,那么可以使用 Index Template 来创建。
一、什么是 Index Template
帮助设定 Mappings 和 Settings,并按照一定的规则,自动匹配到新创建的索引之上。
- 模版仅在一个索引被新创建时,才会产生作用。修改模版不会影响已经创建的索引。
- 可以设定多个索引模板,这些设置会被 “merge” 在一起
- 可以指定 “order” 的数值,控制先合并哪些模板
当一个索引被新创建时:
- 第一应用 Elasticsearch 默认的 settings 和 mappings。
- 第二应用 order 数值低的 index template。
- 第三应用 order 高的 index template,之前的设定会被覆盖。
- 第四应用创建索引时,用户指定的 settings 和 mappings,会覆盖之前模版中的设定。
PUT _template/template_default
{
"index_patterns": ["*"],
"order": 0,
"version": 1,
"settings": {
"number_of_shards": 1,
"number_of_replicas": 1
}
}
PUT _template/template_default
{
"index_patterns": ["test*"],
"order": 1,
"version": 1,
"settings": {
"number_of_shards": 1,
"number_of_replicas": 2
},
"mappings": {
"date_detection": false,
"numeric_detection": true
}
}
二、查看 templates
设置好 template 之后,可以根据名字查看 template,查看所有 templates,命令_template/* 。创建完 template 之后,如果要验证模版的准确性,
2. Dynamic Template
Dynamic Template 根据 Elasticsearch 识别的数据类型,结合字段名称,来动态设定。例如,所有字符串类型都设定成 Keyword,或者关闭 keyword 字段;is 开头的字段都设置成 boolean;long_ 开头的都设置成 long 类型。
一、Dynamic Template 定义
定义在某个索引的 Mapping 中,模板有一个名称,匹配规则是一个数组。
PUT my_text_index
{
"mappings": {
"dynamic_templates": [
{
"full_name": {
"path_match": "name.*",
"path_unmatch": "*.middle",
"mapping": {
"type": "text",
"copy_to": "full_name"
}
}
}
]
}
}
二、匹配规则参数
match_mapping_type:匹配自动识别的字段类型,如 string, boolean 等。 match、unmatch:匹配字段名。 path_match、path_unmatch:匹配 path。
PUT my_index
{
"mappings": {
"dynamic_templates": [
{
"strings_as_boolean": {
"match_mapping_type": "string",
"match": "is*",
"mapping": {
"type": "boolean"
}
}
},
{
"strings_as_keywords": {
"match_mapping_type": "string",
"mapping": {
"type": "keyword"
}
}
}
]
}
}
总结
用模板可以在批量建索引和mapping时更方便,不过需要先对字段规则定义好。
|