☕ XOPSSCHOOL — LEARNING MADE AFFORDABLE
Build the Skills Your Next Career Move Demands.
For the Price of One Coffee a Month.
Why spend hundreds on individual courses? Unlock an entire year of technical learning with one Coffee Pass.
US$4.90 /month
US$58.80/year
₹499 + GST/month
₹5,988 + GST/year
€4.90 /month
€58.80/year
12 Months of Access • Billed Annually • No Automatic Renewal
DevOps • Cloud • SRE • Kubernetes • Terraform • DevSecOps • AI • AIOps • MLOps • LLMOps • FinOps • GitOps • Platform Engineering & Much More
192
Premium Courses
1,085
Video Sessions
99
Ops Disciplines
86
Tool Courses
340
Assignments
227
Quizzes
✓ QR-Verifiable Certificates   ✓ Learn at Your Own Pace   ✓ Hands-on Learning   ✓ New Courses Included
Learn from real-world, instructor-led video sessions by
Rajesh Kumar
Principal Architect • Trainer • Mentor • 15+ Years of Industry Experience
☕ Get My Coffee Pass — Start Learning Today →
One Payment. Every Premium Course. One Full Year.
The best investment you can make is in the person you are becoming.

Elasticsearch templates

An Elasticsearch index template holds the settings, mappings and aliases that Elasticsearch applies when it creates a new index or data stream backing index whose name matches the template's pattern. Component templates are reusable pieces that index templates combine through composed_of. This page explains how the two fit together, gives a corrected and runnable version of the example above, and shows how to test templates, use them with data streams and fix the errors you are most likely to hit.

An index template is a way to tell Elasticsearch how to configure an index when it is created.

For data streams, the index template configures the stream’s backing indices as they are created.
Templates are configured prior to index creation. When an index is created – either manually or through indexing a document – the template settings are used as a basis for creating the index.

There are two types of templates:

  • index templates and
  • component templates.

Component templates are reusable building blocks that configure mappings, settings, and aliases. While you can use component templates to construct index templates, they aren’t directly applied to a set of indices.

Index templates can contain a collection of component templates, as well as directly specify settings, mappings, and aliases.

The following requests create two component templates


How index templates and component templates fit together

The _index_template and _component_template APIs are called composable templates. They replaced the older _template API, which is now called legacy templates and is deprecated. If a composable template and a legacy template both match a new index, the composable template is used.

Component templateIndex template
API endpoint_component_template/<name>_index_template/<name>
Has index_patternsNoYes, required
Applied to indices directlyNo, only through composed_ofYes, when the index is created
Can contain settings, mappings, aliasesYesYes, plus a list of component templates
How many apply to one indexAny number, through the matching index templateExactly one, the highest-priority match

When an index is created, Elasticsearch builds its configuration in this order. Each layer overrides the one before it:

  1. Component templates, in the order listed in composed_of. A later component overrides an earlier one.
  2. The template block of the index template itself.
  3. Any settings, mappings or aliases sent in the create index request.

Note: Templates are only used when an index is created. Changing a template does not change existing indices. To pick up the new configuration, roll the data stream or alias over to a new index, or reindex the data.

Corrected, runnable version of the example

The gist above shows the index template first, but template_1 refers to component_template1 and runtime_component_template, so the component templates must be created before the index template. Otherwise Elasticsearch rejects the request. The gist also mixes Kibana Dev Tools syntax with curl. Below are all three requests in Dev Tools syntax, in the order you have to run them.

PUT _component_template/component_template1
{
  "template": {
    "mappings": {
      "properties": {
        "@timestamp": { "type": "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))"
          }
        }
      }
    }
  }
}

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" }
}Code language: JavaScript (javascript)

Each request should return {"acknowledged": true}.

The curl commands in the gist call http://localhost:9200 without credentials. Elasticsearch 8.x turns security on by default, which means HTTPS and authentication, so those commands fail with a connection error or a 401 security_exception. On a default 8.x install, use the generated CA certificate and a user:

curl --cacert http_ca.crt -u elastic \
  -X PUT "https://localhost:9200/_component_template/component_template1?pretty" \
  -H 'Content-Type: application/json' -d'
{
  "template": {
    "mappings": {
      "properties": {
        "@timestamp": { "type": "date" }
      }
    }
  }
}'Code language: PHP (php)

Note: In the gist, the Painless script uses ' in place of '. This is deliberate. The curl body sits inside a shell single-quoted string, so a literal single quote would end it early. JSON decodes ' back to '. In Kibana Dev Tools you can write doc['@timestamp'] directly.

What each field in template_1 does

FieldPurpose
index_patternsWildcard patterns matched against the new index name. te* matches test-1, temp and team-logs, so keep patterns narrow.
template.settingsIndex settings, here one primary shard.
template.mappingsField mappings. created_at accepts dates such as Mon Jan 15 10:30:00 +0000 2024.
template.aliasesEvery matching index is added to the mydata alias.
priorityDecides which index template wins when several match. Higher wins. The default is 0.
composed_ofOrdered list of component templates to merge in. All of them must already exist.
versionA number you manage for your own tracking. Elasticsearch does not increment it or use it.
_metaFree-form metadata for your own use, such as owner or description.

Test the template before relying on it

The simulate API shows the final configuration an index name would get, without creating anything:

POST _index_template/_simulate_index/test-1

The response contains the merged settings, mappings (with @timestamp, host_name, created_at and the day_of_week runtime field) and aliases, plus an overlapping array listing lower-priority templates that also matched. Next, index a real document and check the result:

POST test-1/_doc?refresh
{
  "@timestamp": "2024-01-15T10:30:00Z",
  "host_name": "web-01",
  "created_at": "Mon Jan 15 10:30:00 +0000 2024"
}

GET test-1/_mapping
GET test-1/_alias

GET test-1/_search
{
  "_source": false,
  "fields": ["day_of_week", "host_name"]
}Code language: JavaScript (javascript)

The search hit should contain "day_of_week": ["Monday"], and _alias should list mydata. That confirms that both component templates and the index template's own block were applied.

To inspect or remove templates:

GET _index_template/template_1
GET _component_template/component_template1

DELETE _index_template/template_1
DELETE _component_template/runtime_component_template

Using index templates with data streams

A data stream needs a matching index template that contains a data_stream object, and the documents need an @timestamp field mapped as date or date_nanos. The component_template1 above already provides that mapping, so it can be reused:

PUT _index_template/my-app-logs-template
{
  "index_patterns": ["my-app-logs*"],
  "data_stream": {},
  "composed_of": ["component_template1"],
  "priority": 500
}

POST my-app-logs/_doc
{
  "@timestamp": "2024-01-15T10:30:00Z",
  "message": "service started"
}

GET _data_stream/my-app-logsCode language: JavaScript (javascript)

The first document creates the data stream and a hidden backing index named like .ds-my-app-logs-<date>-000001. Every backing index created later, for example on rollover, gets the configuration from the template as it is at that moment. That is how template changes reach a data stream.

Note: Elasticsearch ships built-in index templates at priority 100 for patterns such as logs-*-*, metrics-*-* and synthetics-*-*. If your own template matches those names, give it a higher priority or choose a different naming scheme.

Common errors and fixes

SymptomCauseFix
Index template is rejected because its component templates do not existcomposed_of lists a component template that has not been created yet, or its name is misspelledCreate the component templates first and check the names
Error that multiple index templates may not match with the same priorityAnother template has overlapping patterns and the same priorityGive the templates different priorities or make the patterns not overlap
New index does not have the expected mappingThe index existed before the template, the name does not match the pattern, or a higher-priority template wonRun _simulate_index for the name. Recreate, reindex or roll over the index
Component template cannot be deletedAn index template still references it in composed_ofUpdate or delete the index template first
Search fails on day_of_weekA document has no @timestamp value, so doc['@timestamp'].value throwsGuard the script, e.g. if (doc['@timestamp'].size() > 0) { emit(...) }
401 security_exception from curlSecurity is enabled (the 8.x default)Use https, --cacert and -u or an API key

Best practices

  • Put shared pieces, such as the @timestamp mapping, ILM settings (index.lifecycle.name) or common keyword fields, in component templates and reuse them across index templates.
  • Use narrow, specific index_patterns. Broad patterns like te* or * catch indices you did not intend to configure.
  • Set an explicit priority on every index template, and leave gaps (for example 200, 300, 500) so new templates can be slotted in later.
  • Store templates as files in version control and apply them from CI or tools like Terraform, so changes are reviewed and repeatable.
  • Always run _simulate_index before rolling a template change into production.
  • Move any remaining legacy _template definitions to composable templates.

Frequently asked questions

What is the difference between legacy templates and composable index templates?

Legacy templates use the deprecated _template API, and several of them can merge into one index by order. Composable templates use _index_template and _component_template. Only one index template applies, chosen by priority, and it reuses component templates. Composable templates win when both types match.

Does updating an index template change existing indices?

No. Templates are only applied when an index is created. Existing indices keep their settings and mappings until you reindex them or roll over to a new index.

What happens if two index templates match the same index name?

The template with the higher priority is used and the other is ignored. Elasticsearch rejects a new template if it overlaps an existing one at the same priority.

In what order are component templates applied?

They are merged in the order listed in composed_of, so later ones override earlier ones. The index template's own template block then overrides all of them, and the create index request overrides everything.

How can I see which template an index will use?

Run POST _index_template/_simulate_index/<index-name>. It returns the merged configuration and lists any overlapping templates that lost on priority.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services — all in one place.

Explore Hospitals

Related Posts

Elasticsearch Lab#5 – Example of Popular Query

This lab creates an Elasticsearch index with a set number of primary shards and replicas, then runs the queries you'll use most often against it. The example…

Read More

Elasticsearch Lab#4 – DSL Query Collection Part#2

This lab covers the Elasticsearch full-text queries match, match_phrase and match_phrase_prefix, using the customers sample index. Below the gist you will find how these queries differ from…

Read More

Elasticsearch Lab#3 – DSL Query Collection Part#1

This lab covers the two ways to send a search to Elasticsearch's _search API: URI query parameters (?q=) and a JSON Query DSL request body. It goes…

Read More

Elasticsearch Lab#2 – Bulk indexing document using mget & bulk api

This lab uses the Elasticsearch _mget API to fetch several documents in one request and the _bulk API to index, create, update and delete many documents in…

Read More

Elastic Tutorial: Elasticsearch 8.X Installation & CRUD in Linux

This page shows how to install Elasticsearch 8.x from the official tar.gz archive on Linux, start it as a non-root user, and connect over HTTPS with the…

Read More

How to configure Elastic filebeat 8.3 with Elasticseach?

This guide shows how to install Filebeat 8.3 from the tarball, collect log files with the filestream input, and send them to an Elasticsearch 8 cluster that…

Read More