LoginSignup
47
43

More than 5 years have passed since last update.

【elasticsearch】idを指定せずに、bulk-insert

Posted at

id指定なし"bulk-insert"がわからなかったら...

調べた

bulkinsert
curl -XPOST 'localhost:9200/test_index/test_type/_bulk?pretty' -d '
    { "index" : {}       }
    { "name"  : "java"   }
    { "index" : {}       }
    { "name"  : "golang" }
'

折角なので bulk apiを軽く記述

bulk API

複数の処理をまとめて一つのリクエストで要求できるAPI
このAPIを利用することで一つずつリクエストする場合に比べ
処理速度を大幅に稼ぐことができる

適当に計測

100ドキュメントのデータをinsertしてみると
全然処理にかかる時間が違うのがわかる
いろんなデータストアはbulkを利用するほうがだいたい
性能を稼げるのでチェックするほうがいい

each row post use bulk api
0m1.618s 0m0.077s
sample-data
$ cat sample.json
{"name":{"last":"Lynch","first":"Marisol"}}
{"name":{"last":"Webster","first":"Abby"}}
{"name":{"last":"Malone","first":"Poole"}}
.
.
.
{"name":{"last":"Harrell","first":"Suzette"}}
{"name":{"last":"Myers","first":"Lakeisha"}}

一行ごとにポスト (each row post)

each-row-post.sh
#!/bin/bash
lineNum=1

cat $1 | while read JSON_DATA
do
    curl -XPUT "localhost:9200/bulk_table/users/${lineNum}" -d "${JSON_DATA}" 
    lineNum=$((lineNum + 1))
done

bulkAPIを利用してpost (use bulk api)

bulk-post.sh
curl -XPOST "localhost:9200/bulk_table/users_bulk/_bulk" --data-binary @test-bulk.json; echo

利用方法

entrypoint
# index, type指定
curl -XPOST 'localhost:9200/{index}/{type}/_bulk'

# type省略
curl -XPOST 'localhost:9200/{index}/_bulk'

# index, type省略
curl -XPOST 'localhost:9200/_bulk'

indexやtypeを指定すると続くアクションの
デフォルトとして利用される

アクション

  • index :ドキュメントがなければ新規登録、あればリプレース
  • create:ドキュメントがない場合だけ動作
  • delete:ドキュメントを削除
  • update:存在するドキュメントにマージする

記述方法

deleteは一行のみだけど残りは2行で一つのアクションを記述することになる

_bulk
{ "delete": { "_index": "test_index", "_type": "lang", "_id": "123" }} 
{ "create": { "_index": "test_index", "_type": "lang", "_id": "123" }}
{ "name":    "php5.3" }
{ "index":  { "_index": "test_index", "_type": "lang" }}
{ "title":    "php5.6" }
{ "update": { "_index": "test_index", "_type": "lang", "_id": "123", "_retry_on_conflict" : 3} }
{ "doc" : {"title" : "php7"} } 

参考

47
43
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
47
43