ネットワークエンジニアのアレ

技術情報メインの備忘系ブログです

ElasticsearchのデフォルトMapping Typeを定義する

f:id:naitwo2:20180916201247j:plain

ElasticsearchはスキーマレスなDBなので、各フィールドの型を明示的に指定する必要がありません。
とはいえ、確実に型を指定したい場合も多く、その場合はindex templateを使って指定します。

今回の記事は、少し古いバージョンのElasticsearch 2.4系をもとに書いています。


例えば、何も設定せずに以下のようにindexを作成した場合、field01は文字列(string)、field02は数値(integer)として判断されます。

curl -XPOST localhost:9200/test_index/hoge -d '{"field01":"100","field02":100}'


明示的にType を指定する

timeフィールドは”data type”、statusフィールドは”string type”と指定するには以下のように設定します。

curl -XPUT localhost:9200/_template/template -d '
{
  "template" : "log_*",
  "settings" : {
    "number_of_shards" : 1,
    "number_of_replicas" : 0
  },
  "mappings" : {
    "_default_" : {
     "properties": {
      "time": {"type":"date","format":"strict_date_optional_time||epoch_second"},
      "status" : {"type":"string","index":"not_analyzed"}
       }
    }
  }
}'


格納されるフィールドが事前に全て分かっている場合は、上記のように1つ1つ定義することで、明示的にTypeを設定できます。
しかし、格納される全てのフィールドが事前に分からない場合は定義することができません。

そのような時は、Dynamic templatesを使用することで対処できます。

ダイナミックテンプレート(Dynamic Templates)

ダイナミックテンプレート(Dynamic Templates)は、フィールド名を対象にしたルールを定義し、インデックス作成時に動的にマッピングを行う機能です。

フィールド名がhogehogeだったら、このマッピングルールを適用するーーーみたいな感じです。



以下の例では、全てのフィールド("match": "*")をstring type("type": "string")にし、要素解析されないよう("index": "not_analyzed")に設定しています。
※「properties」項目で個別にフィールドとマッピングを指定している場合はそちらが優先されます

curl -XPUT localhost:9200/_template/template -d '
{
  "template" : "log_*",
  "settings" : {
    "number_of_shards" : 1,
    "number_of_replicas" : 0
  },
  "mappings" : {
    "_default_" : {
      "dynamic_templates": [{
        "notanalyzed": {
          "match": "*",
          "mapping": {"type": "string", "index": "not_analyzed"}
        }
      }],
     "properties": {
      "time": {"type":"date","format":"strict_date_optional_time||epoch_second"},
      "status" : {"type":"string","index":"not_analyzed"}
      }
    }
  }
}'


ダイナミックテンプレートの指定は、上記のこの(↓)部分です。

 "dynamic_templates": [{
   "notanalyzed": {
     "match": "*",
     "mapping": {"type": "string", "index": "not_analyzed"}
   }
 }],



Elasticsearch実践ガイド (impress top gear)

Elasticsearch実践ガイド (impress top gear)