Skip to content

索引模版 ​

index Template ​

index Template 可以帮助你设定Mappings和Settings,并按照一定的规则,自动匹配倒新创建的索引之上

  • 模版仅在一个索引被新创建时,才会产生作用。修改模版不会影响已创建的索引。
  • 你可以设定多个索引模版,这些设置会被“merge”在一起
  • 你可以“order”的数值,控制“merging”的过程
bash
PUT /_template/template_default
{
  "index_patterns":["*"],
  "order":0,
  "version":1,
  "settings":{
    "number_of_shards":1,
    "number_of_replicas":1
  }
}


PUT /_template/temlplate_test
{
  "index_patterns":["test"],
  "order":1,
  "settings":{
    "number_of_shards":1,
    "number_of_replicas":1
  },
  "mappings":{
    "date_detection":false, # 关闭日期探测
    "numeric_detection":true
  }
}

Index Template 的工作方式 ​

当一个索引被新创建时:

  • 应用Elasticsearch默认的settings和mappings
  • 应用order数值低的index template中的设定
  • 应用order高的Index template中的设定,之前的设定会被覆盖
  • 应用创建索引时,用户所指定的settings和mappings,并覆盖模版中的设定
bash
# 查看template信息
GET /_template/template_default
GET /_template/temp*

# 详闭日期探测,createDate会推断为text类型
PUT /testtemplate/_doc/1
{
	"orderNo":1,
	"createDate":"2022/01/01"
}
GET /testtemplate/_mappings
GET /testtemplate/_settings

# 开启日期探测
PUT /test1
{
	"mappings":{
		"date_detection": true
	}
}

PUT /test1/_doc/1
{
	"orderNo":1,
	"createDate":"2022/01/01"
}

GET /test1/_mapping

Dynamic Template ​

根据Elasticsearch 识别的数据类型,结合字段名称,来动态设定字段类型

  • 所有的字符串类型都设定成keyword,或者关闭keyword字段
  • is开头的字段都设成boolean
  • long_开头的都设置成long类型
json
PUT /my_index_index
{
  "mappings":{
    "dynamic_templates":[{
      "full_name":{
        "path_match":"name.*",
        "path_unmatch":"*.middle",
        "mapping":{
          "type":"text",
          "copy_to":"full_name"
        }
      }
    }]
  }
}

PUT /my_test_index/_doc/1
{
  "name":{
    "first":"John",
    "middle":"Winston",
    "last":"Lennon"
  }
}

GET /my_test_index/_search
{
  "query":{
    "match":{
      "full_name":"John"
    }
  }
}