除了可以索引,更新,和删除单个的文档之外,Elasticsearch 还提供了使用 _bulk API 来执行上面任何操作的批量方式的能力。这个功能是非常重要,它提供了一种非常有效的机制,以尽可能减少网络返回且尽可能快的执行多个操作。
    作为一个简单的例子,在一个批量操作中下面调用且索引了两个文档(ID 1 - John Doe 和 ID 2 - Jane Doe):

    1. curl -XPOST 'localhost:9200/customer/external/_bulk?pretty&pretty' -d'
    2. {"index":{"_id":"1"}}
    3. {"name": "John Doe" }
    4. {"index":{"_id":"2"}}
    5. {"name": "Jane Doe" }

    这个例子使用一个批量操作更新了第一个文档(ID 为 1),然后删除了第二个文档(ID 为 2) :

    1. ~$ curl -X POST "localhost:9200/megacorp/employee/_bulk?pretty" -H 'Content-Type: application/json' -d'
    2. {"update": {"_id": 3}}
    3. {"doc": {"last_name": "散散"}}
    4. {"delete": {"_id": 5}}
    5. {"create":{"_id": 5}}
    6. {"first_name":"张", "last_name":"三","age":23, "about":"I think this is test", "interests": ["sports", "music"]}
    7. '

    image.png

    返回结果:

    1. {
    2. "took": 18,
    3. "errors": false,
    4. "items": [
    5. {
    6. "update": {
    7. "_index": "megacorp",
    8. "_type": "employee",
    9. "_id": "3",
    10. "_version": 5,
    11. "result": "noop",
    12. "_shards": {
    13. "total": 2,
    14. "successful": 1,
    15. "failed": 0
    16. },
    17. "status": 200
    18. }
    19. },
    20. {
    21. "delete": {
    22. "_index": "megacorp",
    23. "_type": "employee",
    24. "_id": "5",
    25. "_version": 5,
    26. "result": "deleted",
    27. "_shards": {
    28. "total": 2,
    29. "successful": 1,
    30. "failed": 0
    31. },
    32. "_seq_no": 5,
    33. "_primary_term": 3,
    34. "status": 200
    35. }
    36. },
    37. {
    38. "create": {
    39. "_index": "megacorp",
    40. "_type": "employee",
    41. "_id": "5",
    42. "_version": 6,
    43. "result": "created",
    44. "_shards": {
    45. "total": 2,
    46. "successful": 1,
    47. "failed": 0
    48. },
    49. "_seq_no": 6,
    50. "_primary_term": 3,
    51. "status": 201
    52. }
    53. }
    54. ]
    55. }

    请注意上面的删除操作,在它后面没有相关的源文档,因为删除操作只需要文档的 ID 来删除。
    该 bulk API 以此按顺序执行所有的 action(动作)。如果一个单个的动作因任何原因而失败,它将继续处理它后面剩余的动作。当 bulk API 返回时,它将提供每个动作的状态(与发送的顺序相同),所以您可以检查是否一个指定的动作是不是失败了。

    我在使用该命令的时候不知道是我自己的原因还是什么,当我使用postman 去执行命令的时候,总是报错,然后我使用命令行的形式在终端执行,成功后再用postman执行竟然成功了。