Elasticsearch批量API发布请求中的NewLine错误 [英] NewLine error in Elasticsearch bulk API post request

查看:97
本文介绍了Elasticsearch批量API发布请求中的NewLine错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用elasticsearch批量api将多个记录插入索引中.我的JSON看起来像这样:请求json

I am trying to use the elasticsearch bulk api to insert multiple records into an index. My JSON looks something like this: request json

我在文档末尾插入了新行( \\ n ),但仍然出现换行错误.

I am inserting a new line (\\n) at the end of the document but I'm still getting the newline error.

    Error: {
        "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
    }

推荐答案

基于我之前的回答和 https://stackoverflow.com/a/50754789/8160318 :

const AWS = require('aws-sdk');
const creds = new AWS.EnvironmentCredentials('AWS');

const INDEX_NAME = 'index_name';

const esDomain = {
    region: 'us-east-1',
    endpoint: 'yoursearchdomain.region.amazonaws.com',
    index: 'myindex',
    doctype: 'mytype'
};

const endpoint = new AWS.Endpoint(esDomain.endpoint);
const req = new AWS.HttpRequest(endpoint);


const docs_as_body_params = JSON.parse(
    '[' +
    `{"index":{}} {"tags":["ab","cd"],"question":"test this","answer":"answer first"} {"index":{}} {"tags":["de","fg"],"question":"test second","answer":"answer second"}`.split(
        /(\s?{"index":{}} )/g
    )
    .filter(match => match.length)
    .filter((_, index) => index % 2 !== 0) +
    ']'
);

const bulk_body = [];
docs_as_body_params.map((doc) => {
    bulk_body.push({
        index: {
            _index: INDEX_NAME,
            _id: doc.id || null
        }
    });
    bulk_body.push(doc);
});

/// THE MOST IMPORTANT PART -- getting to a valid ndjson
const ndjson_payload = bulk_body.map(JSON.stringify).join('\n') + '\n'

req.method = 'POST';
req.path = '_bulk'
req.region = esDomain.region;
req.headers['presigned-expires'] = false;
req.headers['Host'] = endpoint.host;
req.headers['Content-Type'] = 'application/json';
req.body = ndjson_payload;

var signer = new AWS.Signers.V4(req, 'es');
signer.addAuthorization(creds, new Date());

var send = new AWS.NodeHttpClient();
send.handleRequest(req, null, function (httpResp) {
    var respBody = '';
    httpResp.on('data', function (chunk) {
        respBody += chunk;
    });
    httpResp.on('end', function (chunk) {
        console.log('Response: ' + respBody);
        context.succeed('Lambda added document ' + doc);
    });
}, function (err) {
    console.log('Error: ' + err);
    context.fail('Lambda failed with error ' + err);
});

这篇关于Elasticsearch批量API发布请求中的NewLine错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆