---
type: api
title: Create or update a legacy index template
description: **All methods and paths for this operation:**
url: https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/operation/operation-indices-put-template
resource: https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/operation/operation-indices-put-template
products:
  - Elasticsearch
---

# Create or update a legacy index template


deprecated

Availability:

## Paths

- `POST` (also `PUT`) `/_template/{name}`

- [Api key auth](/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/authentication#apikeyauth)
- [Basic auth](/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/authentication#basicauth)
- [Bearer auth](/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/authentication#bearerauth)

#### Path Parameters

- `name` (string Name)
  The name of the template

## Description

Index templates define settings, mappings, and aliases that can be applied automatically to new indices.
Elasticsearch applies templates to new indices based on an index pattern that matches the index name.

IMPORTANT: This documentation is about legacy index templates, which are deprecated and will be replaced by the composable templates introduced in Elasticsearch 7.8.

Composable templates always take precedence over legacy templates.
If no composable template matches a new index, matching legacy templates are applied according to their order.

Index templates are only applied during index creation.
Changes to index templates do not affect existing indices.
Settings and mappings specified in create index API requests override any settings or mappings specified in an index template.

You can use C-style `/* *\/` block comments in index templates.
You can include comments anywhere in the request body, except before the opening curly bracket.

**Indices matching multiple templates**

Multiple index templates can potentially match an index, in this case, both the settings and mappings are merged into the final configuration of the index.
The order of the merging can be controlled using the order parameter, with lower order being applied first, and higher orders overriding them.
NOTE: Multiple matching templates with the same order value will result in a non-deterministic merging order.

## Required authorization

* Cluster privileges: `manage_index_templates`,`manage`

[Learn more about templates](https://www.elastic.co/docs/manage-data/data-store/templates)

## Query String Parameters

- `create` (boolean · default: false)
  If true, this request cannot replace or update existing index templates.
- `master_timeout` (string Duration · default: 30s)
  Period to wait for a connection to the master node. If no response is
received before the timeout expires, the request fails and returns an error.
- `order` (number)
  Order in which Elasticsearch applies this template if index
matches multiple templates.

Templates with lower 'order' values are merged first. Templates with higher
'order' values are merged later, overriding templates with lower values.
- `cause` (string)
  User defined reason for creating or updating the index template

## Request Body

`application/json`

- `aliases` (map string to Alias) — optional
  Aliases for the index.
  Map values ({} Alias)
  - `filter` ({} QueryContainer) — optional
    Query used to limit documents the alias can access.
    See [QueryContainer](https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/types/_types-query_dsl-querycontainer)
  - `index_routing` (string) — optional
    Value used to route indexing operations to a specific shard.
If specified, this overwrites the `routing` value for indexing operations.
  - `is_hidden` (boolean · default: false) — optional
    If `true`, the alias is hidden.
All indices for the alias must have the same `is_hidden` value.
  - `is_write_index` (boolean · default: false) — optional
    If `true`, the index is the write index for the alias.
  - `routing` (string) — optional
    Value used to route indexing and search operations to a specific shard.
  - `search_routing` (string) — optional
    Value used to route search operations to a specific shard.
If specified, this overwrites the `routing` value for search operations.
- `index_patterns` (union string | [] string) — optional
  Array of wildcard expressions used to match the names
of indices during creation.
- `mappings` ({} TypeMapping) — optional
  Mapping for fields in the index.
  - `all_field` ({} AllField) — optional
    - `analyzer` (string) — required
    - `enabled` (boolean) — required
    - `omit_norms` (boolean) — required
    - `search_analyzer` (string) — required
    - `similarity` (string) — required
    - `store` (boolean) — required
    - `store_term_vector_offsets` (boolean) — required
    - `store_term_vector_payloads` (boolean) — required
    - `store_term_vector_positions` (boolean) — required
    - `store_term_vectors` (boolean) — required
  - `date_detection` (boolean) — optional
  - `dynamic` (enum DynamicMapping) — optional
    Values: `strict`, `runtime`, `true`, `false`
  - `dynamic_date_formats` ([] string) — optional
  - `dynamic_templates` ([] string to DynamicTemplate) — optional
  - `_field_names` ({} FieldNamesField) — optional
    - `enabled` (boolean) — required
  - `index_field` ({} IndexField) — optional
    - `enabled` (boolean) — required
  - `_meta` (Metadata) — optional
  - `numeric_detection` (boolean) — optional
  - `properties` (map string to Property) — optional
  - `_routing` ({} RoutingField) — optional
    - `required` (boolean) — required
  - `_size` ({} SizeField) — optional
    - `enabled` (boolean) — required
  - `_source` ({} SourceField) — optional
    - `enabled` (boolean) — optional
    - `excludes` ([] string) — optional
    - `includes` ([] string) — optional
    - `mode` (enum SourceFieldMode) — optional
      

Supported values include:
  - `disabled`
  - `stored`
  - `columnar_stored`
  - `synthetic`: Instead of storing source documents on disk exactly as you send them,
 Elasticsearch can reconstruct source content on the fly upon retrieval.
      Values: `disabled`, `stored`, `columnar_stored`, `synthetic`
  - `runtime` (map string to RuntimeField) — optional
    Map values ({} RuntimeField)
    - `fields` (map string to CompositeSubField) — optional
      For type `composite`
      Map values ({} CompositeSubField)
      - `type` (enum RuntimeFieldType) — required
        Values: `boolean`, `composite`, `date`, `double`, `geo_point`, `geo_shape`, `ip`, `keyword`, `long`, `lookup`
    - `fetch_fields` ([] RuntimeFieldFetchFields) — optional
      For type `lookup`
      - `field` (string Field) — required
      - `format` (string) — optional
    - `format` (string) — optional
      A custom format for `date` type runtime fields.
    - `input_field` (string Field) — optional
      For type `lookup`
    - `target_field` (string Field) — optional
      For type `lookup`
    - `target_index` (string IndexName) — optional
      For type `lookup`
    - `script` (string Script) — optional
      Painless script executed at query time.
    - `on_script_error` (enum OnScriptError) — optional
      Values: `fail`, `continue`
    - `type` (enum RuntimeFieldType) — required
      Field type, which can be: `boolean`, `composite`, `date`, `double`, `geo_point`, `ip`,`keyword`, `long`, or `lookup`.
      Values: `boolean`, `composite`, `date`, `double`, `geo_point`, `geo_shape`, `ip`, `keyword`, `long`, `lookup`
  - `enabled` (boolean) — optional
  - `subobjects` (enum Subobjects) — optional
    Values: `true`, `false`
  - `_data_stream_timestamp` ({} DataStreamTimestamp) — optional
    - `enabled` (boolean) — required
- `order` (number) — optional
  Order in which Elasticsearch applies this template if index
matches multiple templates.

Templates with lower 'order' values are merged first. Templates with higher
'order' values are merged later, overriding templates with lower values.
- `settings` (IndexSettings) — optional
  Configuration options for the index.
- `version` (number VersionNumber) — optional
  Version number used to manage index templates externally. This number
is not automatically generated by Elasticsearch.
To unset a version, replace the template without specifying one.

## Response

`application/json`

- `acknowledged` (boolean)
  For a successful response, this value is always true. On failure, an exception is returned instead.
## Code Examples

#### Console

```console
POST _template/template_1
{
  "index_patterns": [
    "te*",
    "bar*"
  ],
  "settings": {
    "number_of_shards": 1
  },
  "mappings": {
    "_source": {
      "enabled": false
    },
    "properties": {
      "host_name": {
        "type": "keyword"
      },
      "created_at": {
        "type": "date",
        "format": "EEE MMM dd HH:mm:ss Z yyyy"
      }
    }
  }
}
```

#### JavaScript

```javascript
const response = await client.indices.putTemplate({
  name: "template_1",
  index_patterns: ["te*", "bar*"],
  settings: {
    number_of_shards: 1,
  },
  mappings: {
    _source: {
      enabled: false,
    },
    properties: {
      host_name: {
        type: "keyword",
      },
      created_at: {
        type: "date",
        format: "EEE MMM dd HH:mm:ss Z yyyy",
      },
    },
  },
});
```

#### Python

```python
resp = client.indices.put_template(
    name="template_1",
    index_patterns=[
        "te*",
        "bar*"
    ],
    settings={
        "number_of_shards": 1
    },
    mappings={
        "_source": {
            "enabled": False
        },
        "properties": {
            "host_name": {
                "type": "keyword"
            },
            "created_at": {
                "type": "date",
                "format": "EEE MMM dd HH:mm:ss Z yyyy"
            }
        }
    },
)
```

#### curl

```curl
curl -X POST "$ELASTICSEARCH_URL/_template/template_1" \
  -H "Authorization: ApiKey $ELASTIC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "index_patterns": [
      "te*",
      "bar*"
    ],
    "settings": {
      "number_of_shards": 1
    },
    "mappings": {
      "_source": {
        "enabled": false
      },
      "properties": {
        "host_name": {
          "type": "keyword"
        },
        "created_at": {
          "type": "date",
          "format": "EEE MMM dd HH:mm:ss Z yyyy"
        }
      }
    }
  }'
```

#### Java

```java
client.indices().putTemplate(p -> p
    .indexPatterns(List.of("te*","bar*"))
    .mappings(m -> m
        .properties(Map.of("created_at", Property.of(pr -> pr
                .date(d -> d
                    .format("EEE MMM dd HH:mm:ss Z yyyy")
                )
            ),"host_name", Property.of(pro -> pro
                .keyword(k -> k)
            )))
        .source(s -> s
            .enabled(false)
        )
    )
    .name("template_1")
    .settings(s -> s
        .otherSettings(Map.of())
        .numberOfShards("1")
    )
);
```

#### C#

```c#
var response = await client.Indices
    .PutTemplateAsync(name: "template_1", d1 => d1
        .IndexPatterns("te*", "bar*")
        .Mappings(d2 => d2
            .Properties(d3 => d3
                .Keyword(x => x.HostName)
                .Date(x => x.CreatedAt, d4 => d4
                    .Format("EEE MMM dd HH:mm:ss Z yyyy")
                )
            )
            .Source(d3 => d3
                .Enabled(false)
            )
        )
        .Settings(d2 => d2
            .NumberOfShards(1)
        )
    );
```

#### PHP

```php
$resp = $client->indices()->putTemplate([
    "name" => "template_1",
    "body" => [
        "index_patterns" => array(
            "te*",
            "bar*",
        ),
        "settings" => [
            "number_of_shards" => 1,
        ],
        "mappings" => [
            "_source" => [
                "enabled" => false,
            ],
            "properties" => [
                "host_name" => [
                    "type" => "keyword",
                ],
                "created_at" => [
                    "type" => "date",
                    "format" => "EEE MMM dd HH:mm:ss Z yyyy",
                ],
            ],
        ],
    ],
]);
```

#### Ruby

```ruby
response = client.indices.put_template(
  name: "template_1",
  body: {
    "index_patterns": [
      "te*",
      "bar*"
    ],
    "settings": {
      "number_of_shards": 1
    },
    "mappings": {
      "_source": {
        "enabled": false
      },
      "properties": {
        "host_name": {
          "type": "keyword"
        },
        "created_at": {
          "type": "date",
          "format": "EEE MMM dd HH:mm:ss Z yyyy"
        }
      }
    }
  }
)
```

