【问题标题】:Indexing documents to elasticsearch using nodejs使用nodejs将文档索引到elasticsearch
【发布时间】:2012-04-07 03:38:54
【问题描述】:

我正在尝试使用 nodejs 将文档索引到 elasticsearch。我使用http library from node.js。当我执行我的测试时,我得到:

> node test2.js
data=(bodyText=bodytext)
STATUS: 400
HEADERS: {"content-type":"application/json; charset=UTF-8","content-length":"906"}
response: {"error":"ElasticSearchParseException[Failed to derive xcontent from (offset=0, length=17): [98, 111, 100, 121, 84, 101, 120, 116, 61, 98, 111, 100, 121, 116, 101, 120, 116, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]","status":400}

但是,对 curl 的调用按预期工作:

curl -XPOST 'http://localhost:9200/google/mail' -d '{
"bodytext": "bodytext"
}'
{ok":true,"_index":"google","_type":"mail","_id":"DMJXn80xTmqdny9l6BwV7w","_version":1}

代码

//elasticsearch.js

http = require('http');
stringify = require('querystring').stringify;

exports.indexDocument = function(document) {


    var data = stringify(document);
    //data = document;

    var options = {
    host: 'localhost',
    port: '9200',
    path: 'google/mail',
    method: 'POST'
    };

    var request = http.request(options, function(res) {
                   console.log('STATUS: ' + res.statusCode);
                   console.log('HEADERS: ' + JSON.stringify(res.headers));
                   res.setEncoding('utf8');
                   res.on('data', function (response) {
                          console.log('response: ' + response);
                      });

                   });

    console.log('data=('+data+')');
    request.write(data);
    request.end();
}

//test2.js

completeMsg = {
    bodyText: "bodytext"
};

require('./elasticsearch').indexDocument(completeMsg);

【问题讨论】:

    标签: javascript http node.js http-post elasticsearch


    【解决方案1】:

    在 curl 示例中,您发送的是 JSON 字符串,但在您的节点示例中,您发送的是查询字符串编码的字符串。我希望替换:

    var data = stringify(document)
    

    ...与...

    var data = JSON.stringify(document)
    

    会做你想做的。

    【讨论】:

      猜你喜欢
      • 2012-12-12
      • 1970-01-01
      • 1970-01-01
      • 2021-10-31
      • 1970-01-01
      • 1970-01-01
      • 2015-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多