0
0
Elasticsearchquery~5 mins

Index templates in Elasticsearch

Choose your learning style9 modes available
Introduction

Index templates help you set rules for new indexes automatically. This saves time and keeps data organized.

You want all new indexes with similar names to have the same settings.
You want to apply common mappings to many indexes without repeating work.
You want to control how data is stored and searched in new indexes.
You want to add default settings like number of shards or replicas for new indexes.
You want to ensure consistency across many indexes created over time.
Syntax
Elasticsearch
PUT _index_template/template_name
{
  "index_patterns": ["pattern*"],
  "template": {
    "settings": { ... },
    "mappings": { ... },
    "aliases": { ... }
  },
  "priority": number
}

index_patterns defines which index names the template applies to.

template holds settings, mappings, and aliases for the index.

Examples
This template applies to all indexes starting with 'logs-'. It sets 1 shard and a date field called timestamp.
Elasticsearch
PUT _index_template/my_template
{
  "index_patterns": ["logs-*"],
  "template": {
    "settings": {
      "number_of_shards": 1
    },
    "mappings": {
      "properties": {
        "timestamp": {"type": "date"}
      }
    }
  }
}
This template applies to indexes starting with 'user-data-'. It sets 2 replicas and adds an alias for easy searching.
Elasticsearch
PUT _index_template/user_data_template
{
  "index_patterns": ["user-data-*"],
  "template": {
    "settings": {
      "number_of_replicas": 2
    },
    "aliases": {
      "user_data_alias": {}
    }
  },
  "priority": 10
}
Sample Program

This creates an index template named 'sample_template' for indexes starting with 'test-index-'. It sets shards, replicas, mappings for user, message, and created_at fields, and adds an alias.

Elasticsearch
PUT _index_template/sample_template
{
  "index_patterns": ["test-index-*"],
  "template": {
    "settings": {
      "number_of_shards": 2,
      "number_of_replicas": 1
    },
    "mappings": {
      "properties": {
        "user": {"type": "keyword"},
        "message": {"type": "text"},
        "created_at": {"type": "date"}
      }
    },
    "aliases": {
      "test_alias": {}
    }
  },
  "priority": 5
}
OutputSuccess
Important Notes

Templates only affect indexes created after the template is set.

Priority helps when multiple templates match the same index; higher priority wins.

You can update templates anytime to change future index settings.

Summary

Index templates automate settings and mappings for new indexes.

They use patterns to match index names.

Templates keep your data organized and consistent.