Java时间聚合
AggregationBuilder 构建聚合查询;
AggregationBuilders 类可以调用很多聚合的方法,dateRange 可以对时间范围进行聚合。
示例如下:
public class EsAggregation{
public void searchAggregation(TransportClient client){
AggregationBuilder aggregation = AggregationBuilders
.dateRange("agg")
.field("inputtime")
.format("yyyy-MM-dd HH:mm:ss")
// from 1950 to 1960 (excluded)
.addRange("2016-7-21 00:00:01", "2016-7-21 00:00:02");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.aggregation(aggregation);
System.out.println(sourceBuilder.toString());
SearchResponse response = client
.prepareSearch("pointdata")
.setTypes("pointdata")
.setQuery(QueryBuilders.queryStringQuery
("W3.UNIT1.10LBG01CP301"))
.setSource(sourceBuilder)
.execute()
.actionGet();
SearchHits hits = response.getHits();
for(int i = 0; i < hits.getHits().length; i++) {
System.out.println(i+":"+hits.getHits()[i].getSourceAsString());
}
// sr is here your SearchResponse object
Range agg = response.getAggregations().get("agg");
// For each entry
for (Range.Bucket entry : agg.getBuckets()) {
// Date range as key
String key = entry.getKeyAsString();
// Date bucket from as a Date 引用import org.joda.time.DateTime;
DateTime fromAsDate = (DateTime) entry.getFrom();
// Date bucket to as a Date
DateTime toAsDate = (DateTime) entry.getTo();
// Doc count
long docCount = entry.getDocCount();
System.out.println("key [{"+key+"}], from [{"+fromAsDate+"}], "+
"to [{"+toAsDate+"}], doc_count [{"+docCount+"}]");
}
}
}
版权声明:本文不是「本站」原创文章,版权归原作者所有 | 原文地址: