聚合(aggregations)可以实现对文档数据的统计、分析、运算。聚合常见的有三类:
-
桶(Bucket)聚合:用来对文档做分组
-
TermAggregation:按照文档字段值分组Date
-
Histogram:按照日期阶梯分组,例如一周为一组,或者一月为一组
-
-
度量(Metric)聚合:用以计算一些值,比如:最大值、最小值、平均值等
-
Avg:求平均值
-
Max:求最大值
-
Min:求最小值
-
Stats:同时求max、min、avg、sum等
-
-
管道(pipeline)聚合:其它聚合的结果为基础做聚合
参与聚合的字段类型必须是:
-
keyword
-
数值
-
日期
-
布尔
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
@Configuration
public class ElasticsearchConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
return new RestHighLevelClient(RestClient.builder(
HttpHost.create("http://192.168.150.101:9200")
));
}
}
@Data
public class Demo {
private String brand;
private String city;
private String starName;
}
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
@Service
public class DemoService extends ServiceImpl<DemoMapper, Demo> implements IDemoService {
@Autowired
private RestHighLevelClient restHighLevelClient;
@Override
public Map<String, List<String>> getFilters(RequestParams params) {
try {
// 1.准备请求
SearchRequest request = new SearchRequest("demo");
// 2.请求参数
// 2.2.size
request.source().size(0);
// 2.3.聚合
buildAggregations(request);
// 3.发出请求
SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
// 4.解析结果
Aggregations aggregations = response.getAggregations();
Map<String, List<String>> filters = new HashMap<>(3);
// 4.1.解析品牌
List<String> brandList = getAggregationByName(aggregations, "brandAgg");
filters.put("brand", brandList);
// 4.2.解析城市
List<String> cityList = getAggregationByName(aggregations, "cityAgg");
filters.put("city", cityList);
// 4.3.解析星级
List<String> starList = getAggregationByName(aggregations, "starAgg");
filters.put("starName", starList);
return filters;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void buildAggregations(SearchRequest request) {
request.source().aggregation(
AggregationBuilders.terms("brandAgg").field("brand").size(100));
request.source().aggregation(
AggregationBuilders.terms("cityAgg").field("city").size(100));
request.source().aggregation(
AggregationBuilders.terms("starAgg").field("starName").size(100));
}
private List<String> getAggregationByName(Aggregations aggregations, String aggName) {
// 4.1.根据聚合名称,获取聚合结果
Terms terms = aggregations.get(aggName);
// 4.2.获取buckets
List<? extends Terms.Bucket> buckets = terms.getBuckets();
// 4.3.遍历
List<String> list = new ArrayList<>(buckets.size());
for (Terms.Bucket bucket : buckets) {
String brandName = bucket.getKeyAsString();
list.add(brandName);
}
return list;
}
}