Debian Codegraph @

search_aggs_metrics_avg.go

raw
1 // Copyright 2012-present Oliver Eilhard. All rights reserved.
2 // Use of this source code is governed by a MIT-license.
3 // See http://olivere.mit-license.org/license.txt for details.
4
5 package elastic
6
7 // AvgAggregation is a single-value metrics aggregation that computes
8 // the average of numeric values that are extracted from the
9 // aggregated documents. These values can be extracted either from
10 // specific numeric fields in the documents, or be generated by
11 // a provided script.
12 // See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-avg-aggregation.html
13 type AvgAggregation struct {
14 field string
15 script *Script
16 format string
17 subAggregations map[string]Aggregation
18 meta map[string]interface{}
19 }
20
21 func NewAvgAggregation() *AvgAggregation {
22 return &AvgAggregation{
23 subAggregations: make(map[string]Aggregation),
24 }
25 }
26
27 func (a *AvgAggregation) Field(field string) *AvgAggregation {
28 a.field = field
29 return a
30 }
31
32 func (a *AvgAggregation) Script(script *Script) *AvgAggregation {
33 a.script = script
34 return a
35 }
36
37 func (a *AvgAggregation) Format(format string) *AvgAggregation {
38 a.format = format
39 return a
40 }
41
42 func (a *AvgAggregation) SubAggregation(name string, subAggregation Aggregation) *AvgAggregation {
43 a.subAggregations[name] = subAggregation
44 return a
45 }
46
47 // Meta sets the meta data to be included in the aggregation response.
48 func (a *AvgAggregation) Meta(metaData map[string]interface{}) *AvgAggregation {
49 a.meta = metaData
50 return a
51 }
52
53 func (a *AvgAggregation) Source() (interface{}, error) {
54 // Example:
55 // {
56 // "aggs" : {
57 // "avg_grade" : { "avg" : { "field" : "grade" } }
58 // }
59 // }
60 // This method returns only the { "avg" : { "field" : "grade" } } part.
61
62 source := make(map[string]interface{})
63 opts := make(map[string]interface{})
64 source["avg"] = opts
65
66 // ValuesSourceAggregationBuilder
67 if a.field != "" {
68 opts["field"] = a.field
69 }
70 if a.script != nil {
71 src, err := a.script.Source()
72 if err != nil {
73 return nil, err
74 }
75 opts["script"] = src
76 }
77
78 if a.format != "" {
79 opts["format"] = a.format
80 }
81
82 // AggregationBuilder (SubAggregations)
83 if len(a.subAggregations) > 0 {
84 aggsMap := make(map[string]interface{})
85 source["aggregations"] = aggsMap
86 for name, aggregate := range a.subAggregations {
87 src, err := aggregate.Source()
88 if err != nil {
89 return nil, err
90 }
91 aggsMap[name] = src
92 }
93 }
94
95 // Add Meta data if available
96 if len(a.meta) > 0 {
97 source["meta"] = a.meta
98 }
99
100 return source, nil
101 }