簡體   English   中英

使用Node.js將文檔索引到Elasticsearch

[英]Indexing documents to elasticsearch using nodejs

我正在嘗試使用nodejs將文檔索引到elasticsearch。 我使用來自node.jshttp庫 當我執行測試時,我得到:

> 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);

在curl示例中,您正在發送JSON字符串,但是在節點示例中,您正在發送查詢字符串編碼的字符串。 我希望替換為:

var data = stringify(document)

...與...

var data = JSON.stringify(document)

會做你想要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM