什么是Index Template
Index Template 帮助你设定Mapping 和Settings,并按照一定的规则,自动匹配到新创建的索引之上
- 模板仅在一个索引被创建时,才会产生作用,修改模板不会影响已创建的索引
- 你可以设置多个模板索引,这些设置会被”marge"在一起
- 你可以指定"order" 的数值,控制"merging“的过程
在我们创建索引时,设定索引的默认值
PUT _template/template_default
{
"index_patterns": ["*"],
"order": 0,
"version": 1,
"settings": {
"number_of_shards": 1,
"number_of_replicas": 1
}
}// 设定所有索引的主和副本数都为1
PUT _template/template_default
{
"index_patterns": ["test*"],
"order": 0,
"version": 1,
"settings": {
"number_of_shards": 1,
"number_of_replicas": 2
},
"mappings": {
"date_detection": false,
"numeric_detection": true
}
}// 设定以test 开头的索引主为1副本数为2,并且设定mappings中的字段类型
Index Template 的工作方式
- 应用Elasticsearch 默认的settings 和mappings
- 应用order 数值低的Index Template中的设定
- 应用order 高的Index Template中的设定,之前的设定会被覆盖
- 应用创建索引时,用户所指定的Setting 和Mappings,并覆盖之前模板中的设定
demo
PUT _template/template_default
{
"index_patterns": ["*"],
"order": 0,
"version": 1,
"settings": {
"number_of_shards": 1,
"number_of_replicas": 1
}
}
PUT _template/template_test
{
"index_patterns": ["test*"],
"order": 0,
"version": 1,
"settings": {
"number_of_shards": 1,
"number_of_replicas": 2
},
"mappings": {
"date_detection": false,
"numeric_detection": true
}
}
// 查看template
GET /_template/template_default
// 查看所有template
GET /_template/temp*
DELETE _template/template_default
// demo
PUT ttmp/_doc/1
{
"someNumber": "1",
"someDate": "2019/01/01"
}
GET ttmp/_mapping
// 日期推断为date类型,数字没有被推断为text类型
PUT testtmp/_doc/1
{
"someNumber": "1",
"someDate": "2019/01/01"
}
// 查看通过设定template后索引的mapping
GET testtmp/_mapping
GET testtmp/_settings
// 自己设置的索引的setting 覆盖template
PUT testmy
{
"settings": {
"number_of_replicas": 3
}
}
PUT testmy/_doc/1
{
"name": "mark"
}
GET testmy/_settings
什么是Dynamic Template
- 根据Elasticsearch 识别的数据类型,结合字段名称,来动态设定字段的类型
- 所有的字符串类型都设定成Keyword,或者关闭keyword字段
- is开头的字段设置成boolean
- long_开头的都设置成long类型
Dynamic Template
- Dyname Template 是定义在某个索引的Mapping中
- Template有一个名称
- 匹配规则是一个数组
- 为匹配到的字段设置Mapping
示例
PUT my_test_index
{
"mappings": {
"dynamic_templates": [
{
"full_name": {
"path_match": "name.*",
"path_unmatch": "*.middle",
"mapping": {
"type": "text",
"copy_to": "full_name"
}
}
}]
}
}
demo
// 创建一个dynamic template 匹配已is开头的字符串mapping设定为boolean类型
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"
}
}
}]
}
}
PUT my_index/_doc/1
{
"firstName": "Ruan",
"isVIP": "true"
}
GET my_index/_mapping
PUT my_index2
{
"mappings": {
"dynamic_templates": [
{
"full_name": {
"path_match": "name.*",
"path_unmatch": "*.middle",
"mapping": {
"type": "text",
"copy_to": "full_name"
}
}
}]
}
}
PUT my_index2/_doc/1
{
"name": {
"first": "John",
"middle": "Winston",
"last": "Lennon"
}
}
// 查看索引mapping
GET my_index2/_mapping
// 通过search 检索full_name 字段的John
GET my_index2/_search?q=full_name:John