繁体   English   中英

无法使用node.js http.request将记录插入ElasticSearch-MapperParsingException [无法解析]

[英]Unable to insert a record into ElasticSearch using node.js http.request - MapperParsingException[failed to parse]

尝试使用node.js的http模块( 使用3rd party模块 )将记录插入ElasticSearch中

设置 :在端口9200上本地运行ElasticSearch的实例(默认)

Node.js代码:

var querystring = require('querystring'); // to build our post string
var http = require('http');

// Build the post string from an object
var data = querystring.stringify({
  "text" :"hello world"
});

// An object of options to indicate where to post to
var post_options = {
    host: 'localhost',
    port: '9200',
    path: '/twitter/tweets/1',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(data)
    }
};

// Set up the request
var post_req = http.request(post_options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log('Response: ' + chunk);
    });
});

// post the data
post_req.write(data);
post_req.end();

我收到以下错误

{"error":"MapperParsingException[failed to parse]; nested: 
ElasticsearchParseException[Failed to derive xcontent 
from (offset=0, length=18): [116, 101, 120, 116, 61, 104, 
101, 108, 108, 111, 37, 50, 48, 119, 111, 114, 108, 100]]; ",
"status":400}

但是执行以下CURL可以按预期工作:

curl -XPOST 'http://localhost:9200/twitter/tweet/1' -d '{"message" : "hello world"}'

我查看了以下具有类似错误消息的StackOverflow问题:

这些都没有回答我的问题。

任何帮助,不胜感激。 谢谢

注意 :我故意 使用Node.js Coreno 3rd party )模块使用ElasticSearch REST API(请不要建议使用elasticsearch-jsesrequest等)

回想起来很明显
使用querystring模块是错误的。
ElasticSearch 希望数据以JSON(“ Stringified”)的形式发送

所以代码需要是:

var http = require('http');

// ElasticSearch Expects JSON not Querystring!
var data = JSON.stringify({
  "text" :"everything is awesome"
});

// An object of options to indicate where to post to
var post_options = {
    host: 'localhost',
    port: '9200',
    path: '/twitter/tweets/1234',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(data)
    }
};

// Set up the request
var post_req = http.request(post_options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log('Response: ' + chunk);
    });
});

// post the data
post_req.write(data);
post_req.end();

按预期工作 确认使用:

curl -GET http://localhost:9200/twitter/tweets/1234?pretty

感谢@FelipeAlmeida帮助我意识到这一点)

尽管可以使用formencoding在Elasticsearch上为数据建立索引(我不确定,我必须对此进行研究),但是99%与Elasticsearch的对话方式是通过纯JSON请求。

因此,尝试将'Content-Type': 'application/x-www-form-urlencoded'更改为'Content-type': 'application/json'并告诉我是否可行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM