Elasticsearchのindex templateを試す

index templateを使うと、インデックスの各種設定値をあらかじめ決めておくことができます。

https://www.elastic.co/guide/en/elasticsearch/reference/current/index-templates.html

index templateは、複数のcomposed templateを含めることができます。composed templateはインデックス設定項目のうち、次の内容を再利用できるよう独立して定義できるものです。

  • mappings
  • settings
  • aliases

composed templateは使いまわすことができるので、共通の設定値を定義しておくといった使い方ができそうです。

次のdocker-compose.ymlを使用して、index templateとcomposed templateを使ってみます。

version: '2.2'
services:
  es01:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.16.2
    ports:
      - 9200:9200
      - 9300:9300
    environment:
      - discovery.type=single-node
      - action.destructive_requires_name=true
    networks:
      - elastic
  ki01:
    image: docker.elastic.co/kibana/kibana:7.16.2
    environment:
      ELASTICSEARCH_HOSTS: "http://es01:9200"
    ports:
      - 5601:5601
    networks:
      - elastic
networks:
  elastic:
    driver: bridge

kibanaのDevTools画面から操作しました。

composed templateを定義します。

PUT _component_template/component_template1
{
  "template": {
    "mappings": {
      "properties": {
        "@timestamp": {
          "type": "date"
        }
      }
    }
  }
}

定義を確認します。

GET _component_template/component_template1

// レスポンス
{
  "component_templates" : [
    {
      "name" : "component_template1",
      "component_template" : {
        "template" : {
          "mappings" : {
            "properties" : {
              "@timestamp" : {
                "type" : "date"
              }
            }
          }
        }
      }
    }
  ]
}

この、 component_template1 を使って、index templateを定義します。

PUT _index_template/template1
{
  "index_patterns": ["te*"],
  "template": {
    "settings": {
      "number_of_shards": 3
    },
    "mappings": {
      "_source": {
        "enabled": true
      },
      "properties": {
        "host_name": {
          "type": "keyword"
        },
        "created_at": {
          "type": "date",
          "format": "strict_date"
        }
      }
    }
  },
  "composed_of": ["component_template1"]
}

index templateは次の設定にしました。

  • index_patterns : このindex templateが適用される、インデックス名です。ワイルドカードで、 te から始まるインデックスに対して、適用されるようにしました。複数のインデックス名を指定することもできます。
  • template.settings.number_of_shards : シャード数を3にしています。
  • template.mappings : フィールドのデータ型を定義します。 created_at には、日付の型を定義し、フォーマットで strict_date を指定しました。
  • composed_of : composed indexを列挙します。

インデックスを作成し、各設定を見てみます。

PUT test_index1

GET test_index1/_mapping

// レスポンス
{
  "test_index1" : {
    "mappings" : {
      "properties" : {
        "@timestamp" : {
          "type" : "date"
        },
        "created_at" : {
          "type" : "date",
          "format" : "strict_date"
        },
        "host_name" : {
          "type" : "keyword"
        }
      }
    }
  }
}

index templateとcomposed templateで設定した各項目が反映されているのがわかります。