从ElasticSearch获取json的子集

时间:2015-08-19 14:18:21

标签: javascript json angularjs elasticsearch

我想从ElasticSearch服务器获得json响应的子集。我是ElasticSearch和JavaScript的新手。请看一看。 json文件是ElasticSearch doc的示例文件here。这是一个示例:

{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 1000,
    "max_score" : 1.0,
    "hits" : [ {
      "_index" : "bank",
      "_type" : "account",
      "_id" : "4",
      "_score" : 1.0,
      "_source":{"account_number":4,"balance":27658,"firstname":"Rodriquez","lastname":"Flores","age":31,"gender":"F","address":"986 Wyckoff Avenue","employer":"Tourmania","email":"rodriquezflores@tourmania.com","city":"Eastvale","state":"HI"}
    }, {
      "_index" : "bank",
      "_type" : "account",
      "_id" : "9",
      "_score" : 1.0,
      "_source":{"account_number":9,"balance":24776,"firstname":"Opal","lastname":"Meadows","age":39,"gender":"M","address":"963 Neptune Avenue","employer":"Cedward","email":"opalmeadows@cedward.com","city":"Olney","state":"OH"}
    }
................................
]
  }
}

如何提取account_number,balance和lastname数组,例如[{"account_number":9,"balance":24776,"lastname":"Meadows"},{"account_number":4,"balance":27658,"lastname":"Flores"}, ......... ]

以下是我使用的代码:

var deferred = $q.defer();          
          $http.get("http://localhost:9200/bank/_search?q=*").success(function(data){          

          var country=data.hits.hists.map( function (count) {
                return {
                 account_number:  count._source.account_number,
                 balance:  count._source.balance,
                 lastname: count._source.lastname                    
                  };
              });    

          deferred.resolve(country);
          });

          return deferred.promise; 

我从类似的代码中获取灵感,例如此one用于REST调用。我得到的data似乎是undefined。是否有ES方面的配置?

1 个答案:

答案 0 :(得分:1)

您可以指示ES仅使用source filtering返回这些字段:

$http.get("http://localhost:9200/bank/_search?_source=account_number,balance,lastname&q=*").success(function(data){          

这样你就不必自己过滤掉这些字段了。

然后您在下一行有拼写错误:hists应该阅读hits

var country=data.hits.hits.map( function (count) {

请试一试。