ES语句和SQL语句对比
初始化Builder:SearchRequestBuilder sbuilder = client.prepareSearch("player").setTypes("player");
一、分组查询
1、根据team分组
(1)SQL写法
select team, count(*) as player_count from player group by team;
(2)ES写法
TermsBuilder teamAgg= AggregationBuilders.terms("player_count ").field("team");
sbuilder.addAggregation(teamAgg);
SearchResponse response = sbuilder.execute().actionGet();
2、根据team、position分组
(1)SQL写法
select team, position, count(*) as pos_count from player group by team, position;
(2)ES写法
TermsBuilder teamAgg= AggregationBuilders.terms("player_count ").field("team");
TermsBuilder posAgg= AggregationBuilders.terms("pos_count").field("position");
sbuilder.addAggregation(teamAgg.subAggregation(posAgg));
SearchResponse response = sbuilder.execute().actionGet();
3、根据team分组,并计算最大年龄
(1)SQL写法
select team, max(age) as max_age from player group by team;
(2)ES写法
TermsBuilder teamAgg= AggregationBuilders.terms("player_count ").field("team");
MaxBuilder ageAgg= AggregationBuilders.max("max_age").field("age");
sbuilder.addAggregation(teamAgg.subAggregation(ageAgg));
SearchResponse response = sbuilder.execute().actionGet();
聚合操作主要是调用了SearchRequestBuilder的addAggregation方法,通常是传入一个TermsBuilder,子聚合调用TermsBuilder的subAggregation方法,可以添加的子聚合有TermsBuilder、SumBuilder、AvgBuilder、MaxBuilder、MinBuilder等常见的聚合操作。
从实现上来讲,SearchRequestBuilder在内部保持了一个私有的 SearchSourceBuilder实例, SearchSourceBuilder内部包含一个List<AbstractAggregationBuilder>,每次调用addAggregation时会调用 SearchSourceBuilder实例,添加一个AggregationBuilder。
同样的,TermsBuilder也在内部保持了一个List<AbstractAggregationBuilder>,调用addAggregation方法(来自父类addAggregation)时会添加一个AggregationBuilder。
二、时间查询
dateHistogram 时间查询,区间上支持了日期的表达式,按月查询
{ "aggs":{ "articles_over_time":{ "date_histogram":{ "field":"date", "interval":"month" } } } }