初识Elasticsearch,bulk 操作的遇到的那些事

bulk api可以在单个请求中一次执行多个文档的 create 、 index 、 update 或 delete 操作

批量操作的行为(action)必须是以下几种:
行为解释
create 当文档不存在时创建之。
index 创建新文档或替换已有文档。
update 局部更新文档。
delete 删除一个文档。

create 必须制定_id

index  不必指定_id  会自动创建一个_id

例如,一个 delete 请求看起来是这样的:

{ "delete": { "_index": "website", "_type": "blog", "_id": "123" }}
request body 行由文档的 _source 本身组成--文档包含的字段和值。它是 index 和 create 操作所必需的,这是有道理的:你必须提供文档以索引。

它也是 update 操作所必需的,并且应该包含你传递给 update API 的相同请求体: doc 、 upsert 、 script 等等。 删除操作不需要 request body 行。

{ "create":  { "_index": "website", "_type": "blog", "_id": "123" }}
{ "title":    "My first blog post" }
Index 如果不指定 _id ,将会自动生成一个 ID : {
"index": { "_index": "website", "_type": "blog" }} { "title": "My second blog post" } 为了把所有的操作组合在一起,一个完整的 bulk 请求 有以下形式: POST /_bulk { "delete": { "_index": "website", "_type": "blog", "_id": "123" }} { "create": { "_index": "website", "_type": "blog", "_id": "123" }} { "title": "My first blog post" } { "index": { "_index": "website", "_type": "blog" }} { "title": "My second blog post" } { "update": { "_index": "website", "_type": "blog", "_id": "123", "_retry_on_conflict" : 3} } { "doc" : {"title" : "My updated blog post"} }

bulk 参考示例:

$params['body'] = [];

//创建或替换文档操作
$params['body'][] = [
  'index' => [ #创建或替换
    '_index' => 'my_index',
    '_type' => 'my_type',
    '_id' => 1,
    '_routing' => 1,
  ]
];
$params['body'][] = [
  'name' => '杨',
  'age' => 23
];

//创建文档操作
$params['body'][] = [
  'create' => [ #创建
    '_index' => 'my_index',
    '_type' => 'my_type',
    '_id' => 2,
    '_routing' => 2,
  ]
];
$params['body'][] = [
  'name' => '郭',
  'age' => 19
];

//局部更新文档操作
$params['body'][] = [
  'update' => [ #局部更新
    '_index' => 'my_index',
    '_type' => 'my_type',
    '_id' => 3,
    '_routing' => 3,
  ]
];
$params['body'][] = [
  'doc' => [
    'age' => 19
  ]
];

//删除文档操作
$params['body'][] = [
  'delete' => [ #删除
    '_index' => 'my_index',
    '_type' => 'my_type',
    '_id' => 4,
    '_routing' => 4,
  ]
];
$client = ElasticsearchClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
$res = $client->bulk($params);

原文地址:https://www.cnblogs.com/cbugs/p/10394325.html