嘗試使用elasticsearch bulk api。例如以下批量請求成功
$ curl -X POST "localhost:9200/test/_bulk?pretty" -H 'Content-Type: application/json' -d '
{"index":{"_id":1}}
{"foo":"foo"}
{"index":{"_id":2}}
{"baz":"baz"}
'
{
"took" : 569,
"errors" : false,
"items" : [
{
"index" : {
"_index" : "test",
"_id" : "1",
"_version" : 5,
"result" : "updated",
"_shards" : {
"total" : 2,
"successful" : 2,
"failed" : 0
},
"_seq_no" : 4852,
"_primary_term" : 1,
"status" : 200
}
},
{
"index" : {
"_index" : "test",
"_id" : "2",
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 2,
"failed" : 0
},
"_seq_no" : 4853,
"_primary_term" : 1,
"status" : 201
}
}
]
}
從 curl 切換到 nodejs,會引發錯誤。例如,給定檔案bulk.js
// bulk.js
import axios from "axios";
const run = async () => {
const buff = [
{ index: { "_id": 1 } },
{ foo: "foo" },
{ index: { "_id": 2 } },
{ baz: "baz" }
]
.map(doc => JSON.stringify(doc))
.join("\n")
"\n";
console.log(buff);
const client = axios.create({
baseURL: "http://localhost:9200",
headers: { "Content-Type": "application/json" },
});
try {
const response = await client.post("test/_bulk", buff);
console.log(response.data);
} catch(err) {
console.log(JSON.stringify(err.response.data, null, 2));
}
}
run();
當它運行時,錯誤回傳
$ node bulk.js
{"index":{"_id":1}}
{"foo":"foo"}
{"index":{"_id":2}}
{"baz":"baz"}
{
"error": {
"root_cause": [
{
"type": "illegal_argument_exception",
"reason": "The bulk request must be terminated by a newline [\\n]"
}
],
"type": "illegal_argument_exception",
"reason": "The bulk request must be terminated by a newline [\\n]"
},
"status": 400
}
是什么導致了這個問題?
uj5u.com熱心網友回復:
我認為 axios在將內容型別指定為時會嘗試清理 JSON 字串application/json
嘗試application/x-ndjson改用它,因為它也被ES _bulk 端點接受,并且 axios 可能不會將它作為 JSON 處理。
headers: { "Content-Type": "application/x-ndjson" },
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/444321.html
標籤:javascript 弹性搜索
上一篇:elasticsearchupdateByQuery語法的作業原理
下一篇:以不同方式分析單個彈性搜索欄位
