forste
forste

Reputation: 1133

Indexing documents to elasticsearch using nodejs

I am trying to index documents to elasticsearch using nodejs. I use the http library from node.js. When I execute my test I get:

> 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}

However, a call to curl works as expected:

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

The code

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

Upvotes: 0

Views: 3259

Answers (1)

Steve Campbell
Steve Campbell

Reputation: 3605

In the curl example, you are sending a JSON string, but in your node example you are sending a querystring-encoded string. I expect that replacing:

var data = stringify(document)

...with...

var data = JSON.stringify(document)

will do what you want.

Upvotes: 5

Related Questions