Dynamic templates help you tell Elasticsearch how to automatically set the type and settings for fields when new data comes in. This saves time and keeps your data organized without manually defining every field.
Dynamic templates in Elasticsearch
{
"mappings": {
"dynamic_templates": [
{
"template_name": {
"match": "pattern*",
"mapping": {
"type": "type_name",
"other_setting": "value"
}
}
}
]
}
}dynamic_templates is an array of templates.
Each template has a name and defines a match pattern and the mapping to apply.
keyword type automatically.{
"mappings": {
"dynamic_templates": [
{
"strings_as_keywords": {
"match_mapping_type": "string",
"mapping": {
"type": "keyword"
}
}
}
]
}
}_date and maps it as a date with a specific format.{
"mappings": {
"dynamic_templates": [
{
"dates": {
"match": "*_date",
"mapping": {
"type": "date",
"format": "yyyy-MM-dd"
}
}
}
]
}
}id_ as long integers.{
"mappings": {
"dynamic_templates": [
{
"long_fields": {
"match": "id_*",
"mapping": {
"type": "long"
}
}
}
]
}
}This example shows two dynamic templates: one that maps all string fields as keyword type, and another that maps fields ending with _date as dates with a specific format. When you index a document with these fields, Elasticsearch applies these rules automatically.
{
"mappings": {
"dynamic_templates": [
{
"strings_as_keywords": {
"match_mapping_type": "string",
"mapping": {
"type": "keyword"
}
}
},
{
"dates": {
"match": "*_date",
"mapping": {
"type": "date",
"format": "yyyy-MM-dd"
}
}
}
]
}
}
// Example document to index:
// {
// "user": "alice",
// "signup_date": "2024-06-01",
// "comment": "hello world"
// }
// Resulting mapping:
// "user" and "comment" fields are mapped as keyword (because they are strings)
// "signup_date" is mapped as date with format yyyy-MM-ddDynamic templates are checked in order, so the first matching template is applied.
You can use match, unmatch, match_mapping_type to control which fields the template applies to.
Dynamic templates help avoid mapping conflicts and make your index flexible.
Dynamic templates let Elasticsearch automatically map new fields based on rules you set.
They save time and keep your data organized without manual mapping for every field.
Use patterns to match field names or types and define how they should be indexed.