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

# Create or update a component template


Availability: 7.8+

## Paths

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

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

#### Path Parameters

- `name` (string Name)
  Name of the component template to create.
Elasticsearch includes the following built-in component templates: `logs-mappings`; `logs-settings`; `metrics-mappings`; `metrics-settings`;`synthetics-mapping`; `synthetics-settings`.
Elastic Agent uses these templates to configure backing indices for its data streams.
If you use Elastic Agent and want to overwrite one of these templates, set the `version` for your replacement template higher than the current version.
If you don’t use Elastic Agent and want to disable all built-in component and index templates, set `stack.templates.enabled` to `false` using the cluster update settings API.

## Description

Component templates are building blocks for constructing index templates that specify index mappings, settings, and aliases.

An index template can be composed of multiple component templates.
To use a component template, specify it in an index template’s `composed_of` list.
Component templates are only applied to new data streams and indices as part of a matching index template.

Settings and mappings specified directly in the index template or the create index request override any settings or mappings specified in a component template.

Component templates are only used during index creation.
For data streams, this includes data stream creation and the creation of a stream’s backing indices.
Changes to component templates do not affect existing indices, including a stream’s backing indices.

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

**Applying component templates**

You cannot directly apply a component template to a data stream or index.
To be applied, a component template must be included in an index template's `composed_of` list.

## Required authorization

* Cluster privileges: `manage_index_templates`

## Query String Parameters

- `create` (boolean · default: false)
  If `true`, this request cannot replace or update existing component templates.
- `cause` (string · default: api)
  User defined reason for create the component template.
- `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.

## Request Body

`application/json`

- `template` ({} IndexTemplateMapping) — required
  The template to be applied which includes mappings, settings, or aliases configuration.
  - `aliases` (map string to Alias) — optional
    Aliases to add.
If the index template includes a `data_stream` object, these are data stream aliases.
Otherwise, these are index aliases.
Data stream aliases ignore the `index_routing`, `routing`, and `search_routing` options.
    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/v8/types/_types-query_dsl-querycontainer)
    - `index_routing` (string Routing) — 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 Routing) — optional
      Value used to route indexing and search operations to a specific shard.
    - `search_routing` (string Routing) — optional
      Value used to route search operations to a specific shard.
If specified, this overwrites the `routing` value for search operations.
  - `mappings` ({} TypeMapping) — optional
    Mapping for fields in the index.
If specified, this mapping can include field names, field data types, and mapping parameters.
    - `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
      - `compress` (boolean) — optional
      - `compress_threshold` (string) — optional
      - `enabled` (boolean) — optional
      - `excludes` ([] string) — optional
      - `includes` ([] string) — optional
      - `mode` (enum SourceFieldMode) — optional
        

Supported values include:
  - `disabled`
  - `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`, `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
  - `settings` (IndexSettings) — optional
    Configuration options for the index.
  - `lifecycle` ({} DataStreamLifecycle) — optional
    - `data_retention` (string Duration) — optional
      If defined, every document added to this data stream will be stored at least for this time frame.
Any time after this duration the document could be deleted.
When empty, every document in this data stream will be stored indefinitely.
    - `effective_retention` (string Duration) — optional
      The least amount of time data should be kept by elasticsearch.
    - `retention_determined_by` (enum RetentionSource) — optional
      Configuration source that can influence the retention of a data stream.
      Values: `data_stream_configuration`, `default_global_retention`, `max_global_retention`, `default_failures_retention`
    - `downsampling` ([] DownsamplingRound) — optional
      The list of downsampling rounds to execute as part of this downsampling configuration
      - `after` (string Duration) — required
        The duration since rollover when this downsampling round should execute
      - `config` ({} DownsampleConfig) — required
        The downsample configuration to execute.
        - `fixed_interval` (string) — required
          The interval at which to aggregate the original time series index.
    - `enabled` (boolean · default: true) — optional
      If defined, it turns data stream lifecycle on/off (`true`/`false`) for this data stream. A data stream lifecycle
that's disabled (enabled: `false`) will have no effect on the data stream.
  - `data_stream_options` (union oneOf) — optional — nullable
    - **DataStreamOptionsTemplate**
      Data stream options template contains the same information as DataStreamOptions but allows them to be set explicitly to null.
      - `failure_store` (union oneOf) — optional — nullable
        - **DataStreamFailureStoreTemplate**
          Template equivalent of DataStreamFailureStore that allows nullable values.
          - `enabled` (union boolean | string · default: true) — optional — nullable
            If defined, it turns the failure store on/off (`true`/`false`) for this data stream. A data stream failure store
that's disabled (enabled: `false`) will redirect no new failed indices to the failure store; however, it will
not remove any existing data from the failure store.
          - `lifecycle` (union oneOf) — optional — nullable
            If defined, it specifies the lifecycle configuration for the failure store of this data stream.
            - **FailureStoreLifecycleTemplate**
              Template equivalent of FailureStoreLifecycle that allows nullable values.
              - `data_retention` (union Duration | string) — optional — nullable
                If defined, every document added to this data stream will be stored at least for this time frame.
Any time after this duration the document could be deleted.
When empty, every document in this data stream will be stored indefinitely.
              - `enabled` (boolean · default: true) — optional
                If defined, it turns data stream lifecycle on/off (`true`/`false`) for this data stream. A data stream lifecycle
that's disabled (enabled: `false`) will have no effect on the data stream.
            - **string**
        - **string**
    - **string**
- `version` (number VersionNumber) — optional
  Version number used to manage component templates externally.
This number isn't automatically generated or incremented by Elasticsearch.
To unset a version, replace the template without specifying a version.
- `_meta` (Metadata) — optional
  Optional user metadata about the component template.
It may have any contents. This map is not automatically generated by Elasticsearch.
This information is stored in the cluster state, so keeping it short is preferable.
To unset `_meta`, replace the template without specifying this information.
- `deprecated` (boolean) — optional
  Marks this index template as deprecated. When creating or updating a non-deprecated index template
that uses deprecated components, Elasticsearch will emit a deprecation warning.

## 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 _component_template/template_1
{
  "template": {
    "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.cluster.putComponentTemplate({
  name: "template_1",
  template: {
    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.cluster.put_component_template(
    name="template_1",
    template={
        "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/_component_template/template_1" \
  -H "Authorization: ApiKey $ELASTIC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "template": {
      "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"
          }
        }
      }
    }
  }'
```

#### C#

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

#### PHP

```php
$resp = $client->cluster()->putComponentTemplate([
    "name" => "template_1",
    "body" => [
        "template" => [
            "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.cluster.put_component_template(
  name: "template_1",
  body: {
    "template": {
      "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"
          }
        }
      }
    }
  }
)
```

