如需要统计某件商品的数量,最高价格,最低价格等就用到了聚合查询,就像数据库中的group by
首先需要注入ElasticsearchTemplate
@Autowired private ElasticsearchTemplate elasticsearchTemplate;
然后开始操作
//聚合 @Test public void polymerizationQuery() { NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder(); //terms表示有多少种类型以及每种类型的数量,此处是以手机的品牌来分组 ValuesSourceAggregationBuilder s = AggregationBuilders.terms("brands").field("brand"); builder.addAggregation(s); Aggregations aggregations = elasticsearchTemplate.query(builder.build(), new ResultsExtractor<Aggregations>() { @Override public Aggregations extract(SearchResponse searchResponse) { return searchResponse.getAggregations(); } }); Map<String, Aggregation> stringAggregationMap = aggregations.asMap(); System.out.println(stringAggregationMap.get("brands")); }
结果
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