How to Use Index Template in Elasticsearch: Syntax and Example
In Elasticsearch, use
index templates to define settings and mappings that automatically apply to new indices matching a pattern. Create an index template with PUT _index_template/{template_name} including index_patterns, template settings, and mappings. This helps keep your indices consistent without manual setup each time.Syntax
An index template in Elasticsearch is created using the PUT _index_template/{template_name} API. It includes:
- template_name: The name you give your template.
- index_patterns: A list of index name patterns this template applies to.
- template: Contains
settingsandmappingsthat define how matching indices are created.
json
{
"index_patterns": ["pattern*"],
"template": {
"settings": {
"number_of_shards": 1
},
"mappings": {
"properties": {
"field1": { "type": "text" }
}
}
}
}Example
This example creates an index template named my_template that applies to all indices starting with logs-. It sets one shard and defines a text field called message.
json
PUT _index_template/my_template
{
"index_patterns": ["logs-*"] ,
"template": {
"settings": {
"number_of_shards": 1
},
"mappings": {
"properties": {
"message": {
"type": "text"
}
}
}
}
}Output
{
"acknowledged": true
}
Common Pitfalls
Common mistakes when using index templates include:
- Not matching the
index_patternscorrectly, so the template does not apply. - Forgetting to include
templatewrapper aroundsettingsandmappings. - Using deprecated
PUT _templateAPI instead of the newerPUT _index_template.
Always verify your template with a test index creation.
json
PUT _template/old_template
{
"index_patterns": ["test-*"],
"settings": {
"number_of_shards": 1
},
"mappings": {
"properties": {
"field": { "type": "keyword" }
}
}
}
# This is legacy and may not work as expected.
# Correct way:
PUT _index_template/new_template
{
"index_patterns": ["test-*"] ,
"template": {
"settings": {
"number_of_shards": 1
},
"mappings": {
"properties": {
"field": { "type": "keyword" }
}
}
}
}Quick Reference
| Term | Description |
|---|---|
| index_patterns | List of index name patterns the template applies to |
| template | Object containing settings and mappings for new indices |
| settings | Index configuration like number of shards and replicas |
| mappings | Field definitions and data types for the index |
| PUT _index_template/{name} | API to create or update an index template |
Key Takeaways
Use PUT _index_template/{name} to create index templates in Elasticsearch.
Define index_patterns to specify which indices the template applies to.
Include settings and mappings inside the template object for consistent index creation.
Avoid legacy PUT _template API; prefer the newer _index_template API.
Test your template by creating an index that matches the pattern to ensure it applies.