我正在尝试将 Elasticsearch Bulk API 与 guzzle 结合使用,但我不知道正文的正确格式是什么。
当我使用curl 执行此操作时,没有任何问题。
curl -X POST "http://localhost:9200/hakuna/matata/_bulk" -H 'Content-Type: application/json' -d'
{"index": {}}
{"title": "Abc", "category": "Alphabet", "tags": ["premier", "alphabet"], "duration": 40}
{"index": {}}
{"title": "Def", "category": "Alphabet", "tags": ["second", "alphabet"], "duration": 50}
{"index": {}}
{"title": "Ghi", "category": "Alphabet", "tags": ["troisieme", "alphabet"], "duration": 60}
'
当我用 guzzle 执行此操作时,我总是收到此错误
Client error: `POST http://localhost:9200/hakuna/matata/_bulk` resul
ted in a `400 Bad Request` response:
{"error":{"root_cause":[{"type":"action_request_validation_exception","reas
on":"Validation Failed: 1: no requests added; (truncated...)
这是php代码
$data = [
json_encode(['index' => []]),
json_encode(['title' => 'Abc', 'category' => 'Alphabet', 'tags' => ['premier', 'alphabet'], 'duration' => 40]),
json_encode(['index' => []]),
json_encode(['title' => 'Def', 'category' => 'Alphabet', 'tags' => ['second', 'alphabet'], 'duration' => 50]),
json_encode(['index' => []]),
json_encode(['title' => 'Ghi', 'category' => 'Alphabet', 'tags' => ['troisieme', 'alphabet'], 'duration' => 60]),
];
$data = join("\n", $data);
$response = $client->post('hakuna/matata/_bulk', [
'headers' => ['Content-Type' => 'application/json'],
'json' => $data,
]);
我尝试过使用没有 json_encode 和字符串转换的普通数组,但我总是得到相同的错误。
编辑:最终工作代码
$data = [
json_encode(['index' => []], JSON_FORCE_OBJECT),
json_encode(['title' => 'Abc', 'category' => 'Alphabet', 'tags' => ['premier', 'alphabet'], 'duration' => 40]),
json_encode(['index' => []], JSON_FORCE_OBJECT),
json_encode(['title' => 'Def', 'category' => 'Alphabet', 'tags' => ['second', 'alphabet'], 'duration' => 50]),
json_encode(['index' => []], JSON_FORCE_OBJECT),
json_encode(['title' => 'Ghi', 'category' => 'Alphabet', 'tags' => ['troisieme', 'alphabet'], 'duration' => 60]),
];
$data = join("\n", $data);
$response = $client->post('hakuna/matata/_bulk', [
'headers' => ['Content-Type' => 'application/json'],
'body' => $data."\n",
]);
最佳答案
您走在正确的道路上,到目前为止付出了很大的努力!
现在您需要做的就是在每行末尾添加一个换行符包括最后一个,如下所示:
$data = [
json_encode(['index' => []]),
json_encode(['title' => 'Abc', 'category' => 'Alphabet', 'tags' => ['premier', 'alphabet'], 'duration' => 40]),
json_encode(['index' => []]),
json_encode(['title' => 'Def', 'category' => 'Alphabet', 'tags' => ['second', 'alphabet'], 'duration' => 50]),
json_encode(['index' => []]),
json_encode(['title' => 'Ghi', 'category' => 'Alphabet', 'tags' => ['troisieme', 'alphabet'], 'duration' => 60]),
];
$data = join("\n", $data);
$response = $client->post('hakuna/matata/_bulk', [
'headers' => ['Content-Type' => 'application/json'],
'body' => $data . '\n'; <--- change this line
]);
关于php - Guzzle - Elasticsearch - 批量 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51157843/