Sajeetharan Sajeetharan - 4 months ago 73
Javascript Question

How can i get all index on elastic search using elastic.js?

With my angular application i need to display all indexes on elastic search. I am able to query a particular index using the documentation, not able to get all the indexes on the elastic search.

Here is the



Here is my code:

$scope.getallIndex = function(){
$scope.Indexes = ejs.Request().query(ejs.MatchAllQuery()
.doSearch().then(function (body) {
$scope.Indexes = body.hits.hits;
console.log($scope.Indexes);
}

Answer

I am using elasticsearch.js which is the Browser build for Elastic Search that can be used in the browser . Refer link . I have maintained a factory :

 .factory('ElasticService', [ 'esFactory', function (elasticsearch) {
    var client = elasticsearch({
      host: ip + ':' + port,
    });  

client.cat.indices("b",function(r,q){
  console.log(r,q);
}) }]);

That will return all the indices .Refer link for full configuration.

Edited : Below is the full factory for retrieving data from a specific index .

 .factory('ElasticService', ['$q', 'esFactory', '$location', function ($q, elasticsearch, $location) {
var client = elasticsearch({
  host: ip + ':' + port
});


var search = function (index, body) {
  var deferred = $q.defer();
  client.search({
    index: index,
    type: type,
    body: body
  }).then(function (result) {
    var took = result.took;
    var size = result.hits.total;
    var ii = 0, hits_in, hits_out = [],aggs = [], highlight = [];
    hits_in = (result.hits || {}).hits || [];
    /* For the timebeing i have maintained this variable to save the aggregations */
    aggs = result.aggregations;
    for (; ii < hits_in.length; ii++) {
      hits_in[ii].fields.id = hits_in[ii]._id;
      hits_out.push(hits_in[ii].fields);
      // hits_out[hits_in[ii]._id]=hits_in[ii].fields: use this method if you wanna keep _id as the index

      // if there is a highlight coming along with the data we add a field highlight and push it to built an array
      if (hits_in[ii].highlight) {
        highlight.push(hits_in[ii].highlight);
      }
    }
    if (highlight.length) {
      deferred.resolve({hits: hits_out, highlight: highlight,aggs:aggs, size: size, took: took});
    }
    else {
      deferred.resolve({hits: hits_out, size: size,aggs:aggs, took: took});
    }

  }, deferred.reject);
  return deferred.promise;
};
return {search: search};  }]);

And so the controller you can use this factory for fetching data from a particular index

  ElasticService.search('<index>', <query>).then(function (resp) {
    // resp has the content
  });
Comments