はじめに
- Elasticsearch の検索クエリの実行結果を cURL と jq を使って加工して Elasticsearch にインポートする手順
検索クエリの実行
- 任意のクエリを実行して結果をファイルに保存する
curl -XGET 'http://localhost:9200/_search?size=1000' -o out.json
検索結果をインポート用のフォーマットに変換
- jq コマンドを使って検索結果を Bulk API でインポートできるようなフォーマットに整形する
cat out.json | jq -c '.hits.hits[] | {"index": {"_index": ._index, "_type": ._type, "_id": ._id}}, ._source' > import.json
- 簡単に解説すると
.hits.hits[] |
でマッチしたドキュメントの配列をイテレーティブに処理対象とし{"index": {"_index": ._index, "_type": ._type, "_id": ._id}}, ._source
で個々のドキュメントごとにインポートする際のメタデータとデータ本体を改行区切りで出力している - 結果として import.json は以下のようなファイルになる
{ "index" : { "_index" : "test", "_type" : "_doc", "_id" : "1" } }
{ "field1" : "value1" }
{ "index" : { "_index" : "test", "_type" : "_doc", "_id" : "2" } }
{ "field1" : "value1" }
{ "index" : { "_index" : "test", "_type" : "_doc", "_id" : "3" } }
{ "field1" : "value1" }
作成したファイルをインポートする
curl -XPOST http://localhost:9200/_bulk --data-binary @import.json