赞
踩
这里分组根据时间字符串 SearchResponse searchResponse = client.prepareSearch("company") .addAggregation(AggregationBuilders.terms("group_country").field("country") .subAggregation(AggregationBuilders .terms("group_join") .field("join_date") .subAggregation(AggregationBuilders.avg("avg_age").field("age")) ) ).execute().actionGet(); StringTerms group_country = (StringTerms)searchResponse.getAggregations().asMap().get("group_country"); Terms group_country1 = searchResponse.getAggregations().get("group_country"); Iterator<Terms.Bucket> iterator = group_country1.getBuckets().iterator(); while (iterator.hasNext()){ Terms.Bucket next = iterator.next(); System.out.println(next.getKey()+":\t"+next.getDocCount()); Terms join_date = next.getAggregations().get("group_join"); Iterator<Terms.Bucket> iterator1 = join_date.getBuckets().iterator(); while (iterator1.hasNext()){ Terms.Bucket next1 = iterator1.next(); System.out.println(next1.getKey()+":\t"+next1.getDocCount()); Avg avg_age = (Avg)next1.getAggregations().asMap().get("avg_age"); System.out.println(avg_age.getValue()); } }
这里的分组根据date格式 SearchResponse searchResponse = client.prepareSearch("company") .addAggregation(AggregationBuilders.terms("group_country").field("country") .subAggregation(AggregationBuilders .dateHistogram("group_join") .field("join_date") .dateHistogramInterval(DateHistogramInterval.YEAR)//根据年分组 .subAggregation(AggregationBuilders.avg("avg_age").field("age"))) ) .execute().actionGet(); Map<String, Aggregation> aggrMap = searchResponse.getAggregations().asMap(); StringTerms groupByCountry = (StringTerms) aggrMap.get("group_country"); Iterator<Bucket> groupByCountryBucketIterator = groupByCountry.getBuckets().iterator(); while(groupByCountryBucketIterator.hasNext()) { Bucket groupByCountryBucket = groupByCountryBucketIterator.next(); System.out.println(groupByCountryBucket.getKey() + ":" + groupByCountryBucket.getDocCount()); Histogram groupByJoinDate = (Histogram) groupByCountryBucket.getAggregations().asMap().get("group_join"); Iterator<Histogram.Bucket> groupByJoinDateBucketIterator = groupByJoinDate.getBuckets().iterator(); while(groupByJoinDateBucketIterator.hasNext()) { org.elasticsearch.search.aggregations.bucket.histogram.Histogram.Bucket groupByJoinDateBucket = groupByJoinDateBucketIterator.next(); System.out.println(groupByJoinDateBucket.getKey() + ":" +groupByJoinDateBucket.getDocCount()); Avg avg = (Avg) groupByJoinDateBucket.getAggregations().asMap().get("avg_age"); System.out.println(avg.getValue()); } }
主要是为了学习searchResponse.getAggregations().get("xxx") 返回类型可以转换为Terms
同时也有Histogram(时间格式) Avg(求平均数) StringTerms(字符串)
通过报错信息看出当前的类型
如:ClassCastException: org.elasticsearch.search.aggregations.bucket.terms.LongTerms cannot be cast to
这时候选Terms
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。