Debian Codegraph @

search_aggs_metrics_max.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 // MaxAggregation is a single-value metrics aggregation that keeps track and
8 // returns the maximum value among the numeric values extracted from
9 // the 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-max-aggregation.html
13 type MaxAggregation struct {
14 field string
15 script *Script
16 format string
17 subAggregations map[string]Aggregation
18 meta map[string]interface{}
19 }
20
21 func NewMaxAggregation() *MaxAggregation {
22 return &MaxAggregation{
23 subAggregations: make(map[string]Aggregation),
24 }
25 }
26
27 func (a *MaxAggregation) Field(field string) *MaxAggregation {
28 a.field = field
29 return a
30 }
31
32 func (a *MaxAggregation) Script(script *Script) *MaxAggregation {
33 a.script = script
34 return a
35 }
36
37 func (a *MaxAggregation) Format(format string) *MaxAggregation {
38 a.format = format
39 return a
40 }
41
42 func (a *MaxAggregation) SubAggregation(name string, subAggregation Aggregation) *MaxAggregation {
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 *MaxAggregation) Meta(metaData map[string]interface{}) *MaxAggregation {
49 a.meta = metaData
50 return a
51 }
52 func (a *MaxAggregation) Source() (interface{}, error) {
53 // Example:
54 // {
55 // "aggs" : {
56 // "max_price" : { "max" : { "field" : "price" } }
57 // }
58 // }
59 // This method returns only the { "max" : { "field" : "price" } } part.
60
61 source := make(map[string]interface{})
62 opts := make(map[string]interface{})
63 source["max"] = opts
64
65 // ValuesSourceAggregationBuilder
66 if a.field != "" {
67 opts["field"] = a.field
68 }
69 if a.script != nil {
70 src, err := a.script.Source()
71 if err != nil {
72 return nil, err
73 }
74 opts["script"] = src
75 }
76 if a.format != "" {
77 opts["format"] = a.format
78 }
79
80 // AggregationBuilder (SubAggregations)
81 if len(a.subAggregations) > 0 {
82 aggsMap := make(map[string]interface{})
83 source["aggregations"] = aggsMap
84 for name, aggregate := range a.subAggregations {
85 src, err := aggregate.Source()
86 if err != nil {
87 return nil, err
88 }
89 aggsMap[name] = src
90 }
91 }
92
93 // Add Meta data if available
94 if len(a.meta) > 0 {
95 source["meta"] = a.meta
96 }
97
98 return source, nil
99 }