1// Copyright 2012-2015 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 5package 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: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-metrics-avg-aggregation.html 13type AvgAggregation struct { 14 field string 15 script string 16 scriptFile string 17 lang string 18 format string 19 params map[string]interface{} 20 subAggregations map[string]Aggregation 21} 22 23func NewAvgAggregation() AvgAggregation { 24 a := AvgAggregation{ 25 params: make(map[string]interface{}), 26 subAggregations: make(map[string]Aggregation), 27 } 28 return a 29} 30 31func (a AvgAggregation) Field(field string) AvgAggregation { 32 a.field = field 33 return a 34} 35 36func (a AvgAggregation) Script(script string) AvgAggregation { 37 a.script = script 38 return a 39} 40 41func (a AvgAggregation) ScriptFile(scriptFile string) AvgAggregation { 42 a.scriptFile = scriptFile 43 return a 44} 45 46func (a AvgAggregation) Lang(lang string) AvgAggregation { 47 a.lang = lang 48 return a 49} 50 51func (a AvgAggregation) Format(format string) AvgAggregation { 52 a.format = format 53 return a 54} 55 56func (a AvgAggregation) Param(name string, value interface{}) AvgAggregation { 57 a.params[name] = value 58 return a 59} 60 61func (a AvgAggregation) SubAggregation(name string, subAggregation Aggregation) AvgAggregation { 62 a.subAggregations[name] = subAggregation 63 return a 64} 65 66func (a AvgAggregation) Source() interface{} { 67 // Example: 68 // { 69 // "aggs" : { 70 // "avg_grade" : { "avg" : { "field" : "grade" } } 71 // } 72 // } 73 // This method returns only the { "avg" : { "field" : "grade" } } part. 74 75 source := make(map[string]interface{}) 76 opts := make(map[string]interface{}) 77 source["avg"] = opts 78 79 // ValuesSourceAggregationBuilder 80 if a.field != "" { 81 opts["field"] = a.field 82 } 83 if a.script != "" { 84 opts["script"] = a.script 85 } 86 if a.scriptFile != "" { 87 opts["script_file"] = a.scriptFile 88 } 89 if a.lang != "" { 90 opts["lang"] = a.lang 91 } 92 if a.format != "" { 93 opts["format"] = a.format 94 } 95 if len(a.params) > 0 { 96 opts["params"] = a.params 97 } 98 99 // AggregationBuilder (SubAggregations) 100 if len(a.subAggregations) > 0 { 101 aggsMap := make(map[string]interface{}) 102 source["aggregations"] = aggsMap 103 for name, aggregate := range a.subAggregations { 104 aggsMap[name] = aggregate.Source() 105 } 106 } 107 108 return source 109} 110