Search code examples
elasticsearchelastic-stack

Elastic search get the index template


I want to find out with a rest call to which template an index is bound to. So basically pass the index name and get which template it belongs to.

Basically, I know I can list all the templates and see by patterns what indices will bind to the template, but we have so many templates and so many orderings on them that it's hard to tell.


Solution

  • You can use the _meta mapping field for this in order to attach any custom information to your indexes.

    So let's say you have an index template like this

    PUT _index_template/template_1
    {
      "index_patterns": ["index*"],
      "template": {
        "settings": {
          "number_of_shards": 1
        },
        "mappings": {
          "_meta": {                        <---- add this
            "template": "template_1"        <---- add this
          },                                <---- add this
          "_source": {
            "enabled": true
          },
          "properties": {
            "host_name": {
              "type": "keyword"
            },
            "created_at": {
              "type": "date",
              "format": "EEE MMM dd HH:mm:ss Z yyyy"
            }
          }
        },
        "aliases": {
        }
      },
      "_meta": {
        "description": "my custom template"
      }
    }
    

    Once you create and index that matches that template's pattern, the _meta field will also make it into the new index you're creating.

    PUT index1
    

    Then if you get that new index settings, you'll see from which template it was created:

    GET index1?filter_path=**._meta.template
    

    =>

    {
      "index1" : {
        "mappings" : {
          "_meta" : {
            "template" : "template_1"            <---- you get this
          },