Bulk Api

299 阅读1分钟
  • 支持在一次API调用中,对不同的索引进行操作

  • 支持四种类型操作

    • Index
    • Create
    • Update
    • Delete
  • 可以在URL中指定Index,可以在请求的payload中进行

  • 操作中单条操作失败,并不会影响其他操作

  • 返回结果包括了每一条操作指定的结果

bulk的格式: {action:{metadata}}\n {requstbody}\n (请求体)

action:(行为),包含create(文档不存在时创建)、update(更新文档)、index(创建新文档或替换已用文档)、delete(删除一个文档)。 create和index的区别:如果如果指定了id数据存在,使用create操作失败,会提示文档已存在,使用index则可以成功执行。 metadata:(行为操作的具体索引信息),需要指明数据的_index、_id等信息。

POST _bulk
{"index":{"_index":"test","_id":1}}
{"field1":"value1"}
{"delete":{"_index":"test","_id":2}}
{"create":{"_index":"test2","_id":3}}
{"field1":"value3"}
{"update":{"_id":"1","_index":"test"}}
{"doc":{"filed2":"value2"}}

返回结果

{
  "took" : 3013,
  "errors" : false,
  "items" : [
    {
      "index" : {
        "_index" : "test",
        "_type" : "_doc",
        "_id" : "1",
        "_version" : 1,
        "result" : "created",
        "_shards" : {
          "total" : 2,
          "successful" : 2,
          "failed" : 0
        },
        "_seq_no" : 0,
        "_primary_term" : 1,
        "status" : 201
      }
    },
    {
      "delete" : {
        "_index" : "test",
        "_type" : "_doc",
        "_id" : "2",
        "_version" : 1,
        "result" : "not_found",
        "_shards" : {
          "total" : 2,
          "successful" : 2,
          "failed" : 0
        },
        "_seq_no" : 1,
        "_primary_term" : 1,
        "status" : 404
      }
    },
    {
      "create" : {
        "_index" : "test2",
        "_type" : "_doc",
        "_id" : "3",
        "_version" : 1,
        "result" : "created",
        "_shards" : {
          "total" : 2,
          "successful" : 2,
          "failed" : 0
        },
        "_seq_no" : 0,
        "_primary_term" : 1,
        "status" : 201
      }
    },
    {
      "update" : {
        "_index" : "test",
        "_type" : "_doc",
        "_id" : "1",
        "_version" : 2,
        "result" : "updated",
        "_shards" : {
          "total" : 2,
          "successful" : 2,
          "failed" : 0
        },
        "_seq_no" : 2,
        "_primary_term" : 1,
        "status" : 200
      }
    }
  ]
}

可以在url中指定index,这样就不用在请求体中放入_index

POST /users/_bulk
{"index":{}}
{"name":"fff", "city":"tianjin"}
{"index":{"_index":null}}
{"name":"ddd", "city":"hebei"}

也可以将参数指定文件

$ cat requests
{ "index" : { "_index" : "test", "_id" : "1" } }
{ "field1" : "value1" }
$ curl -s -H "Content-Type: application/x-ndjson" -XPOST localhost:9200/_bulk --data-binary "@requests"

\