我在elasticsearch中有一个类型,其中包含名为created
的字段(日期)。我需要在这个字段上进行dateHistogram
聚合。这是正确的方法吗?有人能为我提供更好的代码片段吗?
List<Result> results = new ArrayList<>();
NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
RangeFilterBuilder rangeBuilderForDate = FilterBuilder.getRangeBuilderForDate(searchCriteria.getCreatedFrom(), searchCriteria.getCreatedTo(), Field.CREATED.getFieldName());
TermFilterBuilder statusTermFilter = FilterBuilder.getTermFilter("Active", Field.STATUS.getFieldName());
BoolFilterBuilder boolFilterBuilder = boolFilter();
BoolFilterBuilder should = boolFilterBuilder.must(rangeBuilderForDate, statusTermFilter);
DateHistogramBuilder dateAggs = AggregationBuilders.dateHistogram("created").interval(getInterval(searchCriteria)).field("created");
FiltersAggregationBuilder filterAggs = AggregationBuilders.filters("dateRange").filter(should).subAggregation(dateAggs);
NativeSearchQuery searchQuery = nativeSearchQueryBuilder.withIndices(index).withTypes(type).addAggregation(filterAggs).build();
Aggregations aggregations = template.query(searchQuery, new ResultsExtractor<Aggregations>() {
@Override
public Aggregations extract(SearchResponse response) {
return response.getAggregations();
}
});
Map<String, Aggregation> asMap = aggregations.getAsMap();
InternalFilters aggregation = (InternalFilters)asMap.get("dateRange");
Collection<Bucket> buckets = aggregation.getBuckets();
for(Filters.Bucket filterBuckets : buckets) {
Aggregations subAggs = filterBuckets.getAggregations();
InternalDateHistogram dateSubAggs = (InternalDateHistogram) subAggs.asMap().get("created");
for(Histogram.Bucket bucket : dateSubAggs.getBuckets()) {
Result result = new Result();
DateHistogram.Bucket dateBucket = (DateHistogram.Bucket) bucket;
result.setAggCriteria(dateBucket.getKey());
result.setCount(dateBucket.getDocCount());
results.add(result);
}
}
return results;