Elasticsearchの基本操作(メモ)


Elasticsearch 7.8.0での実行結果です。

起動・停止

CentOS 7の場合

# systemctl stop elasticsearch
# systemctl start elasticsearch

起動状態確認

# curl -XGET http://localhost:9200/
{
  "name" : "elasticserver1",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "ZUiSSmOETuOAnZp2Adz9dQ",
  "version" : {
    "number" : "7.8.0",
    "build_flavor" : "default",
    "build_type" : "rpm",
    "build_hash" : "757314695644ea9a1dc2fecd26d1a43856725e65",
    "build_date" : "2020-06-14T19:35:50.234439Z",
    "build_snapshot" : false,
    "lucene_version" : "8.5.1",
    "minimum_wire_compatibility_version" : "6.8.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}

ドキュメント・インデックスの基本操作

インデックス一覧

# curl -XGET http://localhost:9200/_cat/indices?v
health status index                              uuid                   pri rep docs.count docs.deleted store.size pri.store.size
yellow open   wildfly-2020.08.02                 hMo3FkigSHagpObrXciudA   1   1         49            0    166.2kb        166.2kb
yellow open   apm-7.8.0-span-000007              jn25WnnNQzC6_00n95fB6g   1   1          0            0       208b           208b
yellow open   apm-7.8.0-span-000006              MqGk0MJ0Qm2Ekqvi7Jp_lA   1   1          0            0       208b           208b
yellow open   apm-7.8.0-span-000009              zs7_STpuQ5WOrheh4W6p8g   1   1          2            0     16.2kb         16.2kb
yellow open   apm-7.8.0-span-000008              dQbcbqrFTTuJ8LOcvSUEfA   1   1          0            0       208b           208b
yellow open   filebeat-7.8.0-2020.08.28-000010   YhxncPSCSf-98qNuS1npig   1   1          0            0       208b           208b
yellow open   apm-7.8.0-profile-000006           acEqEikUSjGv2gwRJvNj6Q   1   1          0            0       208b           208b

インデックス作成

# curl -XPUT http://localhost:9200/hoge_index?pretty
{
  "acknowledged" : true,
  "shards_acknowledged" : true,
  "index" : "hoge_index"
}
# curl -H "Content-Type: application/json" -XPUT http://localhost:9200/hoge_index?pretty -d '
{
    "settings": {
        "number_of_shards": 2,
        "index.number_of_replicas" : 1
    }
}'

{
  "acknowledged" : true,
  "shards_acknowledged" : true,
  "index" : "hoge_index"
}

インデックス削除

# curl -XDELETE http://localhost:9200/hoge_index?pretty
{
  "acknowledged" : true
}

インデックス作成とマッピングの定義

curl -H "Content-Type: application/json" -XPUT 'http://localhost:9200/hoge_index?pretty' -d '
{
    "mappings" : {
        "properties" : {
            "id" : { "type" : "long" },
            "hoge_field" : { "type" : "text" },
            "hoge_keyword" : { "type" : "keyword" }
        }
    }
}'

{
  "acknowledged" : true,
  "shards_acknowledged" : true,
  "index" : "hoge_index"
}

インデックスの設定情報を取得

curl -H "Content-Type: application/json" -XGET 'http://localhost:9200/hoge_index/_settings?pretty'

{
  "hoge_index" : {
    "settings" : {
      "index" : {
        "creation_date" : "1596962203207",
        "number_of_shards" : "1",
        "number_of_replicas" : "1",
        "uuid" : "qUNvLbN8SHW0he4f62BpxA",
        "version" : {
          "created" : "7080099"
        },
        "provided_name" : "hoge_index"
      }
    }
  }
}

マッピング定義の確認

curl -H "Content-Type: application/json" -XGET 'http://localhost:9200/hoge_index/_mapping?pretty'

{
  "hoge_index" : {
    "mappings" : {
      "properties" : {
        "hoge_field" : {
          "type" : "text"
        },
        "hoge_keyword" : {
          "type" : "keyword"
        },
        "id" : {
          "type" : "long"
        }
      }
    }
  }
}

インデックスのドキュメント数の確認

# curl -XGET http://localhost:9200/hoge_index/_count?pretty
{
  "count" : 461,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  }
}

ドキュメント登録

# curl -H "Content-Type: application/json" -XPOST http://localhost:9200/hoge_index/_doc/?pretty -d '{
  "id": 1,
  "hoge_field": "hoge1",
  "hoge_keyword" : "hoge_test"
}'

POSTではなくPUTにすると、ドキュメントがない場合は新規登録。あれば更新になる。

# curl -H "Content-Type: application/json" -XPUT http://localhost:9200/hoge_index/_doc/1?pretty -d '{
  "id": 1,
  "hoge_field": "hoge1",
  "hoge_keyword" : "hoge_test"
}'

ドキュメントの更新

一部のフィールドだけを修正する。

# curl -H "Content-Type: application/json" -XPOST http://localhost:9200/hoge_index/_update/1?pretty -d '{
  "doc": {
    "hoge_field": "hoge22222"
  }
}'

ドキュメントを削除する

# curl -H "Content-Type: application/json" -XDELETE http://localhost:9200/hoge_index/_doc/1?pretty

ドキュメントを削除する(全件)

curl -H "Content-Type: application/json" -XPOST http://localhost:9200/hoge_index/_delete_by_query?pretty -d'
{
  "query": { 
    "match_all": {
    }
  }
}
'

ドキュメントを取得

# curl -XGET http://localhost:9200/hoge_index/_search?pretty
{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "hoge_index",
        "_type" : "_doc",
        "_id" : "kccgf3QB70T0H8p1FHT8",
        "_score" : 1.0,
        "_source" : {
          "id" : 1,
          "hoge_field" : "hoge1",
          "hoge_keyword" : "hoge_test"
        }
      }
    ]
  }
}

ドキュメントを検索

# curl -H "Content-Type: application/json" -XGET http://localhost:9200/hoge_index/_doc/1?pretty -d '
{
  "query": {
    "match": {
      "id": 1
    }
  }
}'

sourceにするとユーザーが登録したデータだけ表示される。

# curl -H "Content-Type: application/json" -XGET http://localhost:9200/hoge_index/_source/1?pretty -d '
{
  "query": {
    "match": {
      "id": 1
    }
  }
}'

インデックスのコピー

# curl -H "Content-Type: application/json" -XPOST http://localhost:9200/_reindex?pretty -d '
{
  "source": {"index": "hoge_index"},
  "dest": {"index": "hoge_index_dest"}
}'

{
  "took" : 234,
  "timed_out" : false,
  "total" : 1,
  "updated" : 0,
  "created" : 1,
  "deleted" : 0,
  "batches" : 1,
  "version_conflicts" : 0,
  "noops" : 0,
  "retries" : {
    "bulk" : 0,
    "search" : 0
  },
  "throttled_millis" : 0,
  "requests_per_second" : -1.0,
  "throttled_until_millis" : 0,
  "failures" : [ ]
}

Bulk API

Bulk APIを使用することで、1回のリクエストで複数ドキュメントを追加・更新・削除する。1ドキュメントずつリクエストするよりパフォーマンスが高い。

以下の4つのアクションを指定する。

  • index: ドキュメントが存在しない場合は新規登録、存在する場合は更新
  • create: ドキュメントが存在しない場合だけ登録
  • update: ドキュメントを更新
  • delete: ドキュメントを削除

インデックスを指定する場合、指定しない場合の例は以下のとおり。

# index指定あり
curl -H "Content-Type: application/json" -XPOST http://localhost:9200/hoge_index/_bulk?pretty --data-binary @hoge.json

# @hoge.jsonの内容は以下のとおり
{"index": {"_id":"1"}}
{"hoge_field": "hoge1", "hoge_keyword" : "hoge_test"}
{"create":{"_id":"2"}}
{"hoge_field": "hoge21", "hoge_keyword" : "hoge_test2"}
{"delete":{"_id":"2"}}
{"update":{"_id": "1"}}
{"doc": {"hoge_keyword": "hoge_test_update"}}
# index指定なし
curl -H "Content-Type: application/json" -XPOST http://localhost:9200/_bulk?pretty --data-binary @hoge_noindex.json

# @hoge_noindex.jsonの内容は以下のとおり
{"index": {"_index": "hoge_index", "_id":"1"}}
{"hoge_field": "hoge1", "hoge_keyword" : "hoge_test"}
{"create":{"_index": "hoge_index", "_id":"2"}}
{"hoge_field": "hoge21", "hoge_keyword" : "hoge_test2"}
{"delete":{"_index": "hoge_index", "_id":"2"}}
{"update":{"_index": "hoge_index", "_id": "1"}}
{"doc": {"hoge_keyword": "hoge_test_update"}}

参考:https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html

インデックステンプレートの操作

インデックステンプレートの作成

# curl -H "Content-Type: application/json" -XPUT http://localhost:9200/_template/hoge_template?pretty -d '
{
  "index_patterns": "hoge_test-*",
  "settings": {
    "number_of_shards": 1
  },
  "mappings" : {
    "properties" : {
      "hoge_field" : {
        "type" : "text"
      },
      "hoge_keyword" : {
        "type" : "keyword"
      },
      "id" : {
        "type" : "long"
      }
    }
  }
}'

{
  "acknowledged" : true
}

ドキュメントを登録し、インデックステンプレートが適用されていることを確認する。

# curl -H "Content-Type: application/json" -XPOST http://localhost:9200/hoge_test-2020.08.09/_doc/?pretty -d '{
  "id": 1,
  "hoge_field": "hoge1",
  "hoge_keyword" : "hoge_test"
}'

{
  "_index" : "hoge_test-2020.08.09",
  "_type" : "_doc",
  "_id" : "-99-0nMBiNcEvOmwjIsG",
  "_version" : 1,
  "result" : "created",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 0,
  "_primary_term" : 1
}

インデックステンプレートの確認

# curl -H "Content-Type: application/json" -XGET 'http://localhost:9200/_template/hoge_template?pretty'

{
  "hoge_template" : {
    "order" : 0,
    "index_patterns" : [
      "hoge_test-*"
    ],
    "settings" : {
      "index" : {
        "number_of_shards" : "1"
      }
    },
    "mappings" : {
      "properties" : {
        "hoge_keyword" : {
          "type" : "keyword"
        },
        "hoge_field" : {
          "type" : "text"
        },
        "id" : {
          "type" : "long"
        }
      }
    },
    "aliases" : { }
  }
}

インデックステンプレートの削除

# curl -H "Content-Type: application/json" -XDELETE 'http://localhost:9200/_template/hoge_template?pretty'

{
  "acknowledged" : true
}

クラスタ稼働状況

# curl -H "Content-Type: application/json" -XGET 'http://localhost:9200/_cat/health?v'
epoch      timestamp cluster       status node.total node.data shards pri relo init unassign pending_tasks max_task_wait_time active_shards_percent
1597019738 00:35:38  elasticsearch yellow          1         1     31  31    0    0       22             0                  -                 58.5%
# curl -H "Content-Type: application/json" -XGET 'http://localhost:9200/_cat/indices?v&bytes=mb'
health status index                              uuid                   pri rep docs.count docs.deleted store.size pri.store.size
yellow open   wildfly-2020.08.02                 hMo3FkigSHagpObrXciudA   1   1         49            0          0              0
yellow open   filebeat-7.8.1-2020.08.09-000002   HshlEt_KRVe_VDW7jsFflQ   1   1        559            0          0              0
yellow open   filebeat-7.8.0-2020.08.10-000003   bOoVzcaIQlGxWE46wMKrHA   1   1          0            0          0              0
yellow open   apm-7.8.0-onboarding-2020.07.18    aFYySZOpQzui-4lRQx4uEw   1   1          5            0          0              0
yellow open   apm-7.8.0-error-000001             FeBssDadR4Sbkp50EC079A   1   1         53            0          0              0
yellow open   filebeat-7.8.0-2020.07.24-000001   eewEazkCR2CIhBKhAVYC3Q   1   1         24            0          0              0

Elasticsearchの設定

ディスク使用率の閾値の変更

シャードの新規割り当て、再配置はディスクの使用率が高いと自動で無効化されます。

  • cluster.routing.allocation.disk.threshold_enabled

自動割り当てを有効・無効化する。デフォルトは有効(true)。

  • cluster.routing.allocation.disk.watermark.low

デフォルトで85%を超過すると新規のシャード割り当てを行わない。

  • cluster.routing.allocation.disk.watermark.high

ディスク使用率が90%を超えるノードからシャードを再配置しようとする。

  • cluster.routing.allocation.disk.watermark.flood_stage

デフォルトは95%で、超過するとインデックスが読み取り専用に設定される。

# curl -XPUT 'http://localhost:9200/_cluster/settings' -H 'Content-Type: application/json' -d '{
"transient" : {
"cluster.routing.allocation.disk.watermark.flood_stage" : "99%",
"cluster.routing.allocation.disk.watermark.high" : "95%",
"cluster.routing.allocation.disk.watermark.low" : "90%"
}
}'