以下是一个使用Elasticsearch的Java API实现包括0值的平均桶聚合的示例代码:
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.metrics.Avg;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import java.io.IOException;
public class AverageBucketAggregationExample {
public static void main(String[] args) {
try (RestHighLevelClient client = new RestHighLevelClient()) {
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.matchAllQuery());
sourceBuilder.sort(SortBuilders.fieldSort("timestamp").order(SortOrder.ASC));
Histogram histogramAgg = AggregationBuilders.histogram("timestamp_histogram")
.field("timestamp")
.interval(DateHistogramInterval.DAY)
.minDocCount(0) // 包括0值
.subAggregation(AggregationBuilders.avg("average_price").field("price"));
sourceBuilder.aggregation(histogramAgg);
SearchResponse response = client.search(sourceBuilder, RequestOptions.DEFAULT);
Histogram agg = response.getAggregations().get("timestamp_histogram");
for (Histogram.Bucket entry : agg.getBuckets()) {
String key = entry.getKeyAsString();
long docCount = entry.getDocCount();
Avg averagePrice = entry.getAggregations().get("average_price");
double avgPrice = averagePrice.getValue();
System.out.println("Key: " + key + ", Doc Count: " + docCount + ", Average Price: " + avgPrice);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
在上述示例中,我们首先创建一个SearchSourceBuilder
对象,配置查询条件和排序方式。然后,我们创建一个Histogram
聚合,指定要聚合的字段(timestamp
)、时间间隔(DateHistogramInterval
)以及是否包括0值(minDocCount
)。接下来,我们在Histogram
聚合中创建一个Avg
聚合,指定要计算平均值的字段(price
)。最后,我们将Histogram
聚合添加到SearchSourceBuilder
中,并使用RestHighLevelClient
执行查询。
在查询响应中,我们可以使用response.getAggregations().get("timestamp_histogram")
获取Histogram
聚合对象,然后遍历桶列表获取每个桶的键、文档计数和平均值。
下一篇:包括<header>路径和起始点