Elasticsearch读取查询结果

本文转载自

https://www.cnblogs.com/wpcnblog/p/7903693.html

在es中所有的查询结果都会保存在SearchResponse中,在从SearchResponse中读取数据的时候,有两种方式:第一种是对Query的结果进行读取,使用的是hit,每一条查询到的doc都是一个hit,可以将每个hit转换为map形式的数据,map的具体形式为<”field”,”value”>的形式,可以得到每一个字段的名称与内容(具体代码如下)

public static List<Product> getSC(SearchResponse sr) {
  List<Product> products = new ArrayList<Product>();
  for (SearchHit hit : sr.getHits()) {
   Map<String, Object> source = hit.getSource();
   if (!source.isEmpty()) {
    for (Iterator<Map.Entry<String, Object>> it = source.entrySet()
      .iterator(); it.hasNext();) {
     Map.Entry<String, Object> entry = it.next();
     if ("title".equals(entry.getKey())) {
      System.out.println("title: "
       + entry.getValue());
     }

第二种方式是针对查询中的聚合问题(aggregation),聚合完成后的每条doc都是一个bucket(桶),他的访问只能通过bucket来进行,而不能使用hit,其操作形式具体如下:

  Terms terms = response.getAggregations().get("hospital"); //hospital为查询聚合时,指定的聚合内容的名称
  DoctorFeeBean docBean = null;
  for (Bucket bucket : terms.getBuckets()) {
   docBean = new DoctorFeeBean();
   String name = bucket.getKey(); //按照聚合字段聚合完成后的名称
   long jiuzhencishu = bucket.getDocCount();//该字段的总共的次数
   Sum sum_money = bucket.getAggregations().get("sum_fee");
   double sum = sum_money.getValue();
   Cardinality cardinality = response.getAggregations().get("jiuzhenrenci");
   long num = cardinality.getValue();
   String temp [] = new String[2];
   temp = getInfo(client, name);
   String hospital = temp[0];
   String doctor_Department = temp[1];
   double feeAvgPerson = sum / num;
   
   docBean.setDoctor_Name(name);
   docBean.setDoctor_Hospital(hospital);
   docBean.setDoctor_Department(doctor_Department);
   docBean.setDoctor_Total_Fee(sum);
   docBean.setNumber_Of_Visit_Doctor((int)jiuzhencishu);
   docBean.setVisitPersonNumber((int)num);
   docBean.setFeeAvgPerson(feeAvgPerson);
   doctorFeeBeans.add(docBean);
  }
坚持原创技术分享,您的支持将鼓励我继续创作!