8. 使用Bulk API实现批量操作:
(1). bulk的格式:
{action:{metadata}}\n // json格式
{requstbody}\n // 请求体
注:
①. Bulk是通过\n来进行解析的.
②. action(行为),表示什么操作:
a. create:文档不存在时创建
b. update:更新文档
c. index:创建新文档或替换已有文档
d. delete:删除一个文档
e. 如果数据存在,使用create操作失败,会提示文档已经存在,使用index则可以成功替换执行.
③. metadata,要操作的数据,需要指定_index、_type、_id.
(2). 批量添加:
curl -XPOST 'http://localhost:9200/lib2/books/_bulk?pretty' -H 'Content-Type: application/json' -d'{"index":{"_id":1}}
{"title":"Java","price":55}
{"index":{"_id":2}}
{"title":"Html5","price":45}
{"index":{"_id":3}}
{"title":"Php","price":35}
{"index":{"_id":4}}
{"title":"Python","price":50}
'
结果:
{
"took" : 773,
"errors" : false, // false表示成功了.
"items" : [
{
"index" : {
"_index" : "lib2",
"_type" : "books",
"_id" : "1",
"_version" : 1, // 这个版本号就是后面讲的版本控制有关系
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 0,
"_primary_term" : 1,
"status" : 201
}
},
...
]
}
或
cat data.json
{"index":{"_id":5}}
{"title":"Java","price":55}
{"index":{"_id":6}}
{"title":"Html5","price":45}
{"index":{"_id":7}}
{"title":"Php","price":35}
{"index":{"_id":8}}
{"title":"Python","price":50} // 注意下面要一个空行
curl -XPOST 'http://localhost:9200/lib2/books/_bulk?pretty' -H 'Content-Type: application/json' --data-binary @data.json