FilterAggregationBuilder:是elasticsearch 中過濾後,聚合一個神奇工具,官網例子:java
POST /sales/_search?size=0 { "aggs" : { "t_shirts" : { "filter" : { "term": { "type": "t-shirt" } }, "aggs" : { "avg_price" : { "avg" : { "field" : "price" } } } } } }
顯示 類型 t-shirt 的平均價格,先根據類型過濾,而後在進行聚合計算api
在java api 中使用的例子:其中某些值須要使用者,修改,elasticsearch
AggregationBuilder aggregation= AggregationBuilders.terms("customer").field("province.raw"); //新增客戶 BoolQueryBuilder addCustomer=QueryBuilders.boolQuery(); addCustomer.must(QueryBuilders.rangeQuery("start_time").from(System.currentTimeMillis()-(10*1000 * 60 * 60 * 24)).to( Instant.now().toEpochMilli())); FilterAggregationBuilder addAggregationBuilder= AggregationBuilders.filter("add", addCustomer).subAggregation(aggregation); //新增簽約 BoolQueryBuilder addSignBuilder=QueryBuilders.boolQuery(); //客戶id addSignBuilder.must(QueryBuilders.termsQuery("id.raw","36v91l0mrP_76359904-5274-4a0a-a4ac-9cffb64ef079")); //客戶建立時間 addSignBuilder.must(QueryBuilders.rangeQuery("start_time").from(System.currentTimeMillis()-(10*1000 * 60 * 60 * 24)).to( Instant.now().toEpochMilli())); FilterAggregationBuilder addSignAggBuilder= AggregationBuilders.filter("add_sign", addSignBuilder).subAggregation(aggregation); //簽約客戶 BoolQueryBuilder sign=QueryBuilders.boolQuery(); //客戶id sign.must(QueryBuilders.termsQuery("id.raw","36v91l0mrP_76359904-5274-4a0a-a4ac-9cffb64ef079")); // FilterAggregationBuilder signAggBuilder= AggregationBuilders.filter("sign", sign).subAggregation(aggregation); SearchRequestBuilder searchRequestBuilder=EsClient.client.filterWithHeader(headers).prepareSearch("customer_36v91l0mrp*").setTypes("customer"). setSize(5).setQuery(boolQueryBuilder).setFetchSource(new String[]{"customer_id"},null) .addAggregation(addSignAggBuilder).addAggregation(addAggregationBuilder).addAggregation(signAggBuilder); LOGGER.info("查詢條件:"+searchRequestBuilder.toString()); SearchResponse searchResponse=searchRequestBuilder.execute().actionGet();