Elasticsearchでデータを修正する方法を以下に記す。
公式ドキュメント Modifying Your Data を参考にした。 www.elastic.co
検証環境: Elasticsearch 6.0.0-rc1
Elasticsearchはほぼリアルタイムでデータ操作と検索機能を提供している。デフォルトでは、データをインデックス登録/更新/削除してから検索結果に表示されるまでに1秒の遅延(更新間隔)を必要とする。
インデックス/ドキュメントの置換 1つのドキュメントを登録する方法は以下のようであった。
bash-3.2$ curl -XPUT 'localhost:9200/customer/doc/1?pretty&pretty' -H 'Content-Type: application/json' -d' > { > "name": "John Doe" > } > ' { "_index" : "customer", "_type" : "doc", "_id" : "1", "_version" : 1, "result" : "created", "_shards" : { "total" : 2, "successful" : 1, "failed" : 0 }, "_seq_no" : 0, "_primary_term" : 1 }
上記のコマンドは、idが1のもの(customer/doc/1の1を指している)をインデックスするものであった。 同じコマンドで上記のJohn Doeの情報を違うものに上書きするとどうなるであるだろうか。
bash-3.2$ curl -XPUT 'localhost:9200/customer/doc/1?pretty&pretty' -H 'Content-Type: application/json' -d' > { > "name": "Jane Doe" > } > ' { "_index" : "customer", "_type" : "doc", "_id" : "1", "_version" : 2, "result" : "updated", "_shards" : { "total" : 2, "successful" : 1, "failed" : 0 }, "_seq_no" : 1, "_primary_term" : 1 } bash-3.2$ curl -XGET 'localhost:9200/customer/doc/1?pretty&pretty' { "_index" : "customer", "_type" : "doc", "_id" : "1", "_version" : 2, "found" : true, "_source" : { "name" : "Jane Doe" } }
きちんとJohn DoeからJane Doeに情報が上書きされており、_versionも1から2になっている。 もちろん別のidを指定して、インデックスすると新たにそのidの文章がインデックスされる。 例えばidが2の場合を試してみる。
bash-3.2$ curl -XPUT 'localhost:9200/customer/doc/2?pretty&pretty' -H 'Content-Type: application/json' -d' > { > "name": "Jane Doe" > } > ' { "_index" : "customer", "_type" : "doc", "_id" : "2", "_version" : 1, "result" : "created", "_shards" : { "total" : 2, "successful" : 1, "failed" : 0 }, "_seq_no" : 0, "_primary_term" : 1 }
きちんとidが2のときインデックスされている。
インデックスを作成する時、idはオプションである。idが指定されていない場合、ランダムIDを生成してインデックスする。 以下の例は明示的にidを指定せずにドキュメントをインデックスする方法である。
bash-3.2$ curl -XPOST 'localhost:9200/customer/doc?pretty&pretty' -H 'Content-Type: application/json' -d' > { > "name": "Jane Doe" > } > ' { "_index" : "customer", "_type" : "doc", "_id" : "G7pTV18BwA-nxasIpIds", "_version" : 1, "result" : "created", "_shards" : { "total" : 2, "successful" : 1, "failed" : 0 }, "_seq_no" : 1, "_primary_term" : 1 }
idの部分がG7pTV18BwA-nxasIpIdsとなっておりランダムなものが生成されている。