ElasticSearch Composite Aggregation

Intro ElasticSearch Composite Aggregation

這篇介紹ElasticSearch Composite Aggregation。

KQL

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
GET /_search
{
"aggs" : {
"my_buckets": {
"composite" : {
"sources" : [
{ "product": { "terms": {"field": "product" } } }
]
},
"aggregations": {
"price": {
"sum": { "field": "price" }
}
}
}
}
}

return:
{
...
"aggregations": {
"my_buckets": {
"after_key": {
"product": "rocky"
},
"buckets": [
{
"key": {
"product": "apocalypse now"
},
"doc_count": 1,
"price": {
"value": 10.0
}
},
{
"key": {
"product": "mad max"
},
"doc_count": 1,
"price": {
"value": 27.0
}
},
{
"key": {
"product" : "mad max"
},
"doc_count": 2,
"price": {
"value": 22.5
}
},
{
"key": {
"product": "rocky"
},
"doc_count": 1,
"price": {
"value": 10.0
}
}
]
}
}
}

RestHighLevelApi Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
List<CompositeValuesSourceBuilder<?>> sources = new ArrayList<>();
sources.add(new TermsValuesSourceBuilder("product").field("product").missingBucket(true));

CompositeAggregationBuilder composite = new CompositeAggregationBuilder("my_bucket", sources);
composite.size(10000);
composite.subAggregation(AggregationBuilders.sum("price").field("price"));
sourceBuilder.aggregation(composite);
sourceBuilder.size(0);

SearchResponse searchResponse = ELKManager.search(sourceBuilder);

CompositeAggregation compositeAggregation = searchResponse.getAggregations().get("my_bucket");
if (compositeAggregation.getBuckets().size() > 0) {
for (CompositeAggregation.Bucket bucket : compositeAggregation.getBuckets()) {
Map<String, Object> resultKey = bucket.getKey();
Aggregations sumReward = bucket.getAggregations();
Sum sum = sumReward.get("price");
System.out.println((String) resultKey.get("product") + " ; " + BigDecimal.valueOf(sum.getValue()));
}
}