为什么Elasticsearch批量API无法解析我的JSON?

时间:2016-08-17 08:24:36

标签: json node.js amazon-web-services elasticsearch

我有类似JSON的数据,我通过HTTP请求PUT到Elasticsearch API / _bulk端点:

{"update":{"_id":1,"_type":"myType","_index":"myIndex"}}
{"doc":{"id":1,"name":"Foo"},"doc_as_upsert":true}
{"update":{"_id":2,"_type":"myType","_index":"myIndex"}}
{"doc":{"id":2,"name":"Bar"},"doc_as_upsert":true}

当我通过Postman(谷歌Chrome应用程序)PUT数据时,它可以成功运行。

当我通过我的Node.js脚本(PUT调用)request()数据时,我收到此错误:

{
  "error" : {
    "root_cause" : [ {
      "type" : "parse_exception",
      "reason" : "Failed to derive xcontent"
    } ],
    "type" : "parse_exception",
    "reason" : "Failed to derive xcontent"
  },
  "status" : 400
}

我发送(我假设的)两种方式完全相同的数据但只有Postman正在工作。我用\ n字符结束每一行(包括最后一行),我相信我的格式是正确的。

我做错了吗?

编辑:节点代码(简化):

var sourceData = JSON.parse(fs.readFileSync('test-data.json', 'utf8')),

sourceData.forEach(function(data) {
    var docid = data.id;

    updates.push(JSON.stringify({
        update: {
            _id: docid,
            _type: config.elasticsearch.type,
            _index: config.elasticsearch.index
        }
    }));

    updates.push(JSON.stringify({
        doc: data,
        doc_as_upsert: true
    }));
});

updates = updates.join("\n") + "\n";

request({
    uri: 'http://my-endpoint/_bulk',
    method: 'POST',
    data: updates,
    proxy: 'http://' + config.proxy.host + ':' + config.proxy.port
}, function() { ... });

1 个答案:

答案 0 :(得分:2)

您需要使用body参数发送更新,而不是data(用于多部分请求)

request({
    uri: 'http://my-endpoint/_bulk',
    method: 'POST',
    body: updates,               // <---- change this
    proxy: 'http://' + config.proxy.host + ':' + config.proxy.port
}, function() { ... });