ElasticSearch读取查询结果(search)

在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,其操作形式具体如下:

 //hospital为查询聚合时,指定的聚合内容的名称
Terms terms = response.getAggregations().get("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);
  }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值