Elasticsearch Bulk API 批量增删改查
Elasticsearch 中有了批量查询 mget,当然也要有 mset ——只有程序员才能想到的冷笑话,正确答案是用 Bulk API 实现批量增删改查。文字内容整理自 B 站中华石杉的 Elasticsearch 顶尖高手系列课程核心知识篇
Bulk 语法
先实操一下
POST /_bulk
{"delete": {"_index":"test_index", "_id":"1"}}
{"create": {"_index":"test_index", "_id":"21" }}
{"test_filed": "test21"}
{"index": {"_index":"test_index", "_id":"2"}}
{"test_filed1": "replaced test2"}
{"update": {"_index":"test_index", "_id":"1", "retry_on_conflict":3}}
{"doc":{"test_field2": "bulk update test"}}
每一个操作要两个 json 串,语法如下:
{"action": {"metadata"}}
{"data"}
举例,比如你现在要创建一个文档,放bulk里面,看起来会是这样子的:
{"index": {"_index": "test_index", "_type", "test_type", "_id": "1"}}
{"test_field1": "test1", "test_field2": "test2"}
也可以指定操作一个某索引
POST /_bulk
POST //_bulk
有哪些类型的操作可以执行呢?
delete:删除一个文档,只要1个json串就可以了
create:类似于 PUT /index/_doc/id/_create,强制创建
index:普通的put操作,可以是创建文档,也可以是全量替换文档
update:执行的 partial update 操作
bulk api 对 JSON 的语法,有严格的要求,每个JSON 串不能换行,只能放一行,同时一个JSON 串和一个JSON 串之间,必须有一个换行,否则就会看到如下报错信息:
{
"error": {
"root_cause": [
{
"type": "json_e_o_f_exception",
"reason": "Unexpected end-of-input: expected close marker for Object (start marker at [Source: org.elasticsearch.transport.netty4.ByteBufStreamInput@5a5932cd; line: 1, column: 1])\n at [Source: org.elasticsearch.transport.netty4.ByteBufStreamInput@5a5932cd; line: 1, column: 3]"
...
The actions are specified in the request body using a newline delimited JSON (NDJSON) structure:
action_and_meta_data\n
optional_source\n
action_and_meta_data\n
optional_source\n
....
action_and_meta_data\n
optional_source\n
create fails if a document with the same ID already exists in the target, index adds or replaces a document as necessary.
bulk 操作中,任意一个操作失败,是不会影响其他的操作的,但是在返回结果里,会告诉你异常日志。
重复执行之前的 bulk 语句,会发现
result: not_found; status: 404,之前已经被删除了
status: 409,create 之前已经创建过,version conflict
status: 404,没有找到要更新的文档,document missing
如果执行顺利的化,可以看到的 result 就是:deleted、created、updated,而 status 是:200 或 201
Bulk 最佳大小
bulk request 会加载到内存里,如果太大的话,性能反而会下降,因此需要反复尝试一个最佳的 bulk size。一般从1000~5000 条数据开始,尝试逐渐增加。另外,如果看大小的话,最好是在 5~15 MB 之间。