Debian Codegraph @

search_aggs_metrics_min.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 // MinAggregation is a single-value metrics aggregation that keeps track and
8 // returns the minimum value among numeric values extracted from the
9 // aggregated documents. These values can be extracted either from
10 // specific numeric fields in the documents, or be generated by a
11 // provided script.
12 // See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-metrics-min-aggregation.html
13 type MinAggregation struct {
14 field string
15 script *Script
16 format string
17 subAggregations map[string]Aggregation
18 meta map[string]interface{}
19 }
20
21 func NewMinAggregation() *MinAggregation {
22 return &MinAggregation{
23 subAggregations: make(map[string]Aggregation),
24 }
25 }
26
27 func (a *MinAggregation) Field(field string) *MinAggregation {
28 a.field = field
29 return a
30 }
31
32 func (a *MinAggregation) Script(script *Script) *MinAggregation {
33 a.script = script
34 return a
35 }
36
37 func (a *MinAggregation) Format(format string) *MinAggregation {
38 a.format = format
39 return a
40 }
41
42 func (a *MinAggregation) SubAggregation(name string, subAggregation Aggregation) *MinAggregation {
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 *MinAggregation) Meta(metaData map[string]interface{}) *MinAggregation {
49 a.meta = metaData
50 return a
51 }
52
53 func (a *MinAggregation) Source() (interface{}, error) {
54 // Example:
55 // {
56 // "aggs" : {
57 // "min_price" : { "min" : { "field" : "price" } }
58 // }
59 // }
60 // This method returns only the { "min" : { "field" : "price" } } part.
61
62 source := make(map[string]interface{})
63 opts := make(map[string]interface{})
64 source["min"] = 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 if a.format != "" {
78 opts["format"] = a.format
79 }
80
81 // AggregationBuilder (SubAggregations)
82 if len(a.subAggregations) > 0 {
83 aggsMap := make(map[string]interface{})
84 source["aggregations"] = aggsMap
85 for name, aggregate := range a.subAggregations {
86 src, err := aggregate.Source()
87 if err != nil {
88 return nil, err
89 }
90 aggsMap[name] = src
91 }
92 }
93
94 // Add Meta data if available
95 if len(a.meta) > 0 {
96 source["meta"] = a.meta
97 }
98
99 return source, nil
100 }