如需要统计某件商品的数量,最高价格,最低价格等就用到了聚合查询,就像数据库中的group by
首先需要注入ElasticsearchTemplate
@Autowired private ElasticsearchTemplate elasticsearchTemplate;
然后开始操作
//聚合 public Map<String, Integer> polymerizationQuery() { String aggName = "popularBrand"; NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder(); //聚合 queryBuilder.addAggregation(AggregationBuilders.terms("popularBrand").field("brand")); //查询并返回带聚合结果 AggregatedPage<Item> result = elasticsearchTemplate.queryForPage(queryBuilder.build(), Item.class); //解析聚合 Aggregations aggregations = result.getAggregations(); //获取指定名称的聚合 StringTerms terms = aggregations.get(aggName); //获取桶 List<StringTerms.Bucket> buckets = terms.getBuckets(); //遍历打印 Map<String, Integer> map = new HashMap<>(); for (StringTerms.Bucket bucket : buckets) { map.put(bucket.getKeyAsString(), (int) bucket.getDocCount()); System.out.println("key = " + bucket.getKeyAsString()); System.out.println("DocCount = " + bucket.getDocCount()); } return map; }
elasticseach的可视化数据
其他方法
(1)统计某个字段的数量 ValueCountAggregationBuilder vcb= AggregationBuilders.count("自定义").field("uid"); (2)去重统计某个字段的数量 CardinalityAggregationBuilder cb= AggregationBuilders.cardinality("distinct_count_uid").field("uid"); (3)聚合过滤 FilterAggregationBuilder fab= AggregationBuilders.filter("uid_filter").filter(QueryBuilders.queryStringQuery("uid:001")); (4)按某个字段分组 TermsAggregationBuilder tb= AggregationBuilders.terms("group_name").field("name"); (5)求和 SumAggregationBuilder sumBuilder= AggregationBuilders.sum("sum_price").field("price"); (6)求平均 AvgAggregationBuilder ab= AggregationBuilders.avg("avg_price").field("price"); (7)求最大值 MaxAggregationBuilder mb= AggregationBuilders.max("max_price").field("price"); (8)求最小值 MinAggregationBuilder min= AggregationBuilders.min("min_price").field("price"); (9)按日期间隔分组 DateHistogramAggregationBuilder dhb= AggregationBuilders.dateHistogram("dh").field("date"); (10)获取聚合里面的结果 TopHitsBuilder thb= AggregationBuilders.topHits("top_result"); (11)嵌套的聚合 NestedAggregationBuilder nb= AggregationBuilders.nested("negsted_path").path("quests"); (12)反转嵌套 AggregationBuilders.reverseNested("res_negsted").path("kps ");
注:使用聚合查询时不能使用分词,因此字段需要设置为type = FieldType.Keyword