ES 条形图 histogram
- ES 中的聚合还有一个优点,可以很容易的转化成图表和图形,直方图
histogram
数据准备
-
PUT cars { "mappings": { "transactions": { "properties": { "color": { "type": "keyword" }, "make": { "type": "keyword" }, "price": { "type": "long" }, "sold": { "type": "date" } } } } }
-
POST /cars/transactions/_bulk { "index": {}} { "price" : 10000, "color" : "red", "make" : "honda", "sold" : "2014-10-28" } { "index": {}} { "price" : 20000, "color" : "red", "make" : "honda", "sold" : "2014-11-05" } { "index": {}} { "price" : 30000, "color" : "green", "make" : "ford", "sold" : "2014-05-18" } { "index": {}} { "price" : 15000, "color" : "blue", "make" : "toyota", "sold" : "2014-07-02" } { "index": {}} { "price" : 12000, "color" : "green", "make" : "toyota", "sold" : "2014-08-19" } { "index": {}} { "price" : 20000, "color" : "red", "make" : "honda", "sold" : "2014-11-05" } { "index": {}} { "price" : 80000, "color" : "red", "make" : "bmw", "sold" : "2014-01-01" } { "index": {}} { "price" : 25000, "color" : "blue", "make" : "ford", "sold" : "2014-02-12" }
使用
-
需求:为售价创建一个直方图,可以将间隔设为 20,000,对每个区间内已售汽车的售价求和
-
GET /cars/transactions/_search { "size" : 0, "aggs":{ "price":{ "histogram":{ "field": "price", "interval": 20000 }, "aggs":{ "revenue": { "sum": { "field" : "price" } } } } } }
-
返回结果 "aggregations": { "price": { "buckets": [ { "key": 0, "doc_count": 3, "revenue": { "value": 37000 } }, { "key": 20000, "doc_count": 4, "revenue": { "value": 95000 } }, { "key": 40000, "doc_count": 0, "revenue": { "value": 0 } }, { "key": 60000, "doc_count": 0, "revenue": { "value": 0 } }, { "key": 80000, "doc_count": 1, "revenue": { "value": 80000 } } ] } }
-
@Test public void test05(){ HistogramAggregationBuilder histogramAggregationBuilder = AggregationBuilders.histogram("popular_price").field("price").interval(20000); SumAggregationBuilder sumAggregationBuilder = AggregationBuilders.sum("revenue").field("price"); histogramAggregationBuilder.subAggregation(sumAggregationBuilder); SearchResponse searchResponse = elasticsearchTemplate.getClient().prepareSearch("cars") .setTypes("transactions") .addAggregation(histogramAggregationBuilder) .execute() .actionGet(); InternalHistogram internalHistogram = searchResponse.getAggregations().get("popular_price"); List<InternalHistogram.Bucket> buckets = internalHistogram.getBuckets(); for (InternalHistogram.Bucket bucket : buckets){ String keyAsString = bucket.getKeyAsString(); System.out.print(keyAsString+"---"); InternalSum internalSum = bucket.getAggregations().get("revenue"); double value = internalSum.getValue(); System.out.println(value); } }
-
返回结果 0.0---37000.0 20000.0---95000.0 40000.0---0.0 60000.0---0.0 80000.0---80000.0
-
-
histogram
桶要求两个参数:一个数值字段以及一个定义桶大小间隔。 -
sum
度量嵌套在每个售价区间内,用来显示每个区间内的总收入。 -
直方图的键值是区间的下限。键
0
代表区间0-19,999
,键20000
代表区间20,000-39,999
等等