Debian Codegraph @

search_aggs_bucket_nested.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 // NestedAggregation is a special single bucket aggregation that enables
8 // aggregating nested documents.
9 // See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-nested-aggregation.html
10 type NestedAggregation struct {
11 path string
12 subAggregations map[string]Aggregation
13 meta map[string]interface{}
14 }
15
16 func NewNestedAggregation() *NestedAggregation {
17 return &NestedAggregation{
18 subAggregations: make(map[string]Aggregation),
19 }
20 }
21
22 func (a *NestedAggregation) SubAggregation(name string, subAggregation Aggregation) *NestedAggregation {
23 a.subAggregations[name] = subAggregation
24 return a
25 }
26
27 // Meta sets the meta data to be included in the aggregation response.
28 func (a *NestedAggregation) Meta(metaData map[string]interface{}) *NestedAggregation {
29 a.meta = metaData
30 return a
31 }
32
33 func (a *NestedAggregation) Path(path string) *NestedAggregation {
34 a.path = path
35 return a
36 }
37
38 func (a *NestedAggregation) Source() (interface{}, error) {
39 // Example:
40 // {
41 // "query" : {
42 // "match" : { "name" : "led tv" }
43 // }
44 // "aggs" : {
45 // "resellers" : {
46 // "nested" : {
47 // "path" : "resellers"
48 // },
49 // "aggs" : {
50 // "min_price" : { "min" : { "field" : "resellers.price" } }
51 // }
52 // }
53 // }
54 // }
55 // This method returns only the { "nested" : {} } part.
56
57 source := make(map[string]interface{})
58 opts := make(map[string]interface{})
59 source["nested"] = opts
60
61 opts["path"] = a.path
62
63 // AggregationBuilder (SubAggregations)
64 if len(a.subAggregations) > 0 {
65 aggsMap := make(map[string]interface{})
66 source["aggregations"] = aggsMap
67 for name, aggregate := range a.subAggregations {
68 src, err := aggregate.Source()
69 if err != nil {
70 return nil, err
71 }
72 aggsMap[name] = src
73 }
74 }
75
76 // Add Meta data if available
77 if len(a.meta) > 0 {
78 source["meta"] = a.meta
79 }
80
81 return source, nil
82 }