[英]Guzzle - Elasticsearch - Bulk API
我試圖使用Elasticsearch Bulk API和guzzle,但我不知道正文的格式是什么。
當我用卷曲做的時候,我沒有任何問題。
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
]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.