Question: Elasticsearch show only the name of all indices with node js

Question

Elasticsearch show only the name of all indices with node js

Answers 1
Added at 2016-12-27 15:12
Tags
Question

I am using ejs framework with node js. I can get all the index names in json format. But what I want is just the names of the indices. My code looks like as follows-

var client = require('../routes/Connection.js');

//display all indexes
module.exports.allIndexes = function (searchData, callback) {
    client.indices.getAliases({
        index: "_all",
        level: "indices"
    }, function (error, response, status) {
        if (error) {
            console.log("search error: " + error)
        }
        else {
            //callback(response);---> this works
            callback(response.hits.hits); // ---> this doesn't
        }
    });
}

if I use response in callback, I get the following output:

{
  "index-1": {
    "aliases": {}
  },
  "index-2": {
    "aliases": {}
  },
  "index-3": {
    "aliases": {}
  },
  "index-4": {
    "aliases": {}
  }
}

and when I use response.hits.hits in callback I get the error:"cannot read property 'hits' of undefined". I want to show only the index names as a list. FYI, in front end, I passed the response say as "results" :

        <h1>Index</h1>
        <% for(var i=0; i < results.length; i++) { %>
          <%= results[i].indices %>
        <% } %>

which shows nothing ofcourse.

edit_1:

I import the module as follows: in my index.js:

router.post('/indexes', function (req, res) {
    elasticModule.allIndexes(req.body, function (data) {
        res.render('elasticGui', { title: 'Elasticsearch GUI', results: data });
    });
});
Answers
nr: #1 dodano: 2016-12-27 15:12

When looking at your response structure

{
  "index-1": {
    "aliases": {}
  },
  "index-2": {
    "aliases": {}
  },
  "index-3": {
    "aliases": {}
  },
  "index-4": {
    "aliases": {}
  }
}

you don't see any hits, do you? So response.hits is undefined and the error happens when trying to reference hits out of response.hits

You simply need to change your code like this:

callback(Object.keys(response));

And then in your view you can iterate over that array like this:

    <% results.forEach(function(index) { %>
      <%= index %>
    <% }); %>
Source Show
◀ Wstecz