0
0
Elasticsearchquery~5 mins

Why templates standardize index creation in Elasticsearch

Choose your learning style9 modes available
Introduction

Templates help create indexes in a consistent way automatically. This saves time and avoids mistakes.

When you want all new indexes to have the same settings and mappings.
When you add new data regularly and want it organized the same way.
When you want to avoid manually setting up each index.
When you want to apply rules to indexes based on their names.
When you want to ensure data is searchable and stored correctly every time.
Syntax
Elasticsearch
PUT _index_template/template_name
{
  "index_patterns": ["pattern*"],
  "template": {
    "settings": { ... },
    "mappings": { ... }
  }
}
Use index_patterns to match index names the template applies to.
The template section defines settings and mappings for matching indexes.
Examples
This template applies to all indexes starting with logs-. It sets 1 shard and defines two fields.
Elasticsearch
PUT _index_template/my_template
{
  "index_patterns": ["logs-*"],
  "template": {
    "settings": {
      "number_of_shards": 1
    },
    "mappings": {
      "properties": {
        "timestamp": {"type": "date"},
        "message": {"type": "text"}
      }
    }
  }
}
This template ensures all user-data-* indexes have 2 replicas and specific fields.
Elasticsearch
PUT _index_template/user_data_template
{
  "index_patterns": ["user-data-*"],
  "template": {
    "settings": {
      "number_of_replicas": 2
    },
    "mappings": {
      "properties": {
        "user_id": {"type": "keyword"},
        "signup_date": {"type": "date"}
      }
    }
  }
}
Sample Program

This creates a template for indexes named test-index-*. Then it creates an index test-index-001 with data. Finally, it gets the mapping to show the template applied.

Elasticsearch
PUT _index_template/sample_template
{
  "index_patterns": ["test-index-*"],
  "template": {
    "settings": {
      "number_of_shards": 1
    },
    "mappings": {
      "properties": {
        "name": {"type": "text"},
        "created_at": {"type": "date"}
      }
    }
  }
}

POST test-index-001/_doc
{
  "name": "Alice",
  "created_at": "2024-01-01"
}

GET test-index-001/_mapping
OutputSuccess
Important Notes

Templates apply only to new indexes created after the template is set.

You can update templates anytime to change future index creation.

Templates help keep data organized and searchable in the same way.

Summary

Templates automatically set index settings and mappings for matching index names.

This saves time and avoids errors when creating many indexes.

Use templates to keep your data consistent and easy to search.