-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
aggregation.go
66 lines (55 loc) · 1.36 KB
/
aggregation.go
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
package opensearch_query
import (
"encoding/json"
"fmt"
)
type AggregationRequest interface {
AddAggregation(string, string, string) error
}
type NestedAggregation interface {
Nested(string, AggregationRequest)
Missing(string)
Size(int)
}
type aggregationFunction struct {
aggType string
field string
size int
missing string
nested AggregationRequest
}
func (a *aggregationFunction) MarshalJSON() ([]byte, error) {
agg := make(map[string]interface{})
field := map[string]interface{}{"field": a.field}
if t, _ := getAggregationFunctionType(a.aggType); t == "bucket" {
// We'll use the default size of 10 if it hasn't been set; size == 0 is illegal in a bucket aggregation
if a.size == 0 {
a.size = 10
}
field["size"] = a.size
}
if a.missing != "" {
field["missing"] = a.missing
}
agg[a.aggType] = field
if a.nested != nil {
agg["aggregations"] = a.nested
}
return json.Marshal(agg)
}
func (a *aggregationFunction) Size(size int) {
a.size = size
}
func (a *aggregationFunction) Missing(missing string) {
a.missing = missing
}
func getAggregationFunctionType(field string) (string, error) {
switch field {
case "avg", "sum", "min", "max", "value_count", "stats", "extended_stats", "percentiles":
return "metric", nil
case "terms":
return "bucket", nil
default:
return "", fmt.Errorf("invalid aggregation function %s", field)
}
}