簡體   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