SQL场景:带过滤条件的聚合查询
SELECT COUNT(color) FROM table where price >= 10000 and price < 35000 GROUP BY color
查询在一定价格区间内的销售车辆颜色分布
Aggregation API:
在API实现上是先做过滤再聚合
GET /cars/transactions/_search
{
"size": 0,
"query": {
"range" : {
"price" : {
"gte" : 10000,
"lt" : 35000
}
}
},
"aggs" : {
"popular_colors" : {
"terms" : {
"field" : "color"
}
}
}
}
java API:
def aggTest2(): Unit = {
import scala.collection.JavaConverters._
// 构造RangeQuery
val rangeQuery = QueryBuilders.rangeQuery("price").gte(10000).lt(35000)
// 构造Aggregation
val agg = AggregationBuilders
.terms("color")
.field("color")
.order(Terms.Order.count(false))
// 组合&执行查询
val searchRes = queryBuilder
.setQuery(rangeQuery)
.addAggregation(agg)
.execute()
.actionGet()
searchRes.getAggregations.get("color").asInstanceOf[Terms].getBuckets.asScala.foreach{ bucket =>
println(s"key: ${bucket.getKeyAsString}, value ${bucket.getDocCount}")
}
}
网友评论