springboot整合es实现聚合搜索(api搜索版)

注: 希望大家先了解es聚合的桶和指标的概念
可以看我的这篇文章

kibana理解Elasticsearch中搜索,聚合的一些概念

1.在es服务器上准备好数据

此处省略嗷~
以下是我的数据。
在这里插入图片描述

2.相关的pom依赖

<dependency>
      <groupId>org.elasticsearch</groupId>
      <artifactId>elasticsearch</artifactId>
      <version>5.5.3</version>
</dependency>
<dependency>
      <groupId>org.elasticsearch.client</groupId>
      <artifactId>transport</artifactId>
      <version>5.5.3</version>
</dependency>
<dependency>
      <groupId>org.elasticsearch.plugin</groupId>
      <artifactId>transport-netty4-client</artifactId>
      <version>5.5.3</version>
</dependency>

3.api(可能会出的异常看第五点)

 TransportClient client1 = new PreBuiltTransportClient(Settings.EMPTY);
 client1.addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress("xxxxxxxx", 9300)));

 SearchRequestBuilder searchRequestBuilder = client1.prepareSearch("emindex").setTypes("product")
                .addAggregation(AggregationBuilders.terms("group").field("productCategory.keyword").size(1000)
                        .subAggregation(AggregationBuilders.sum("sum").field("productPrice")));

 SearchResponse response = searchRequestBuilder.execute().actionGet();
 Terms terms = response.getAggregations().get("group");

 List<? extends Terms.Bucket> buckets = terms.getBuckets();
 for (Terms.Bucket bucket : buckets) {
       InternalSum sum = bucket.getAggregations().get("sum");
       map.put(bucket.getKeyAsString(), (long) sum.getValue());
  }

es对应的搜索语句相当于SQL

select productCategory as group,sum(productPrice) as sum from product group by productCategory;

4.结果

在这里插入图片描述

5.可能会出现的异常

在这里插入图片描述

注意,这里写的是terms("group").field("productCategory")
java.lang.IllegalArgumentException: Fielddata is disabled on text fields by default. 
Set fielddata=true on [productCategory] in order to load fielddata in memory by uninverting the inverted index. 
Note that this can however use significant memory. Alternatively use a keyword field instead.

大概意思是说你用来分组的那个字段[productCategory]不支持使用默认的索引方法搜索,你这个字段的类型可能用的是text,提示的也很明确了,Alternatively use a keyword。应该写成这样

terms("group").field("productCategory.keyword")

猜你喜欢

转载自blog.csdn.net/weixin_46269980/article/details/106077252