| 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 |
// FilterAggregation defines a single bucket of all the documents |
| 8 |
// in the current document set context that match a specified filter. |
| 9 |
// Often this will be used to narrow down the current aggregation context |
| 10 |
// to a specific set of documents. |
| 11 |
// See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-filter-aggregation.html |
| 12 |
type FilterAggregation struct { |
| 13 |
filter Query |
| 14 |
subAggregations map[string]Aggregation |
| 15 |
meta map[string]interface{} |
| 16 |
} |
| 17 |
|
| 18 |
func NewFilterAggregation() *FilterAggregation { |
| 19 |
return &FilterAggregation{ |
| 20 |
subAggregations: make(map[string]Aggregation), |
| 21 |
} |
| 22 |
} |
| 23 |
|
| 24 |
func (a *FilterAggregation) SubAggregation(name string, subAggregation Aggregation) *FilterAggregation { |
| 25 |
a.subAggregations[name] = subAggregation |
| 26 |
return a |
| 27 |
} |
| 28 |
|
| 29 |
// Meta sets the meta data to be included in the aggregation response. |
| 30 |
func (a *FilterAggregation) Meta(metaData map[string]interface{}) *FilterAggregation { |
| 31 |
a.meta = metaData |
| 32 |
return a |
| 33 |
} |
| 34 |
|
| 35 |
func (a *FilterAggregation) Filter(filter Query) *FilterAggregation { |
| 36 |
a.filter = filter |
| 37 |
return a |
| 38 |
} |
| 39 |
|
| 40 |
func (a *FilterAggregation) Source() (interface{}, error) { |
| 41 |
// Example: |
| 42 |
// { |
| 43 |
// "aggs" : { |
| 44 |
// "in_stock_products" : { |
| 45 |
// "filter" : { "range" : { "stock" : { "gt" : 0 } } } |
| 46 |
// } |
| 47 |
// } |
| 48 |
// } |
| 49 |
// This method returns only the { "filter" : {} } part. |
| 50 |
|
| 51 |
src, err := a.filter.Source() |
| 52 |
if err != nil { |
| 53 |
return nil, err |
| 54 |
} |
| 55 |
source := make(map[string]interface{}) |
| 56 |
source["filter"] = src |
| 57 |
|
| 58 |
// AggregationBuilder (SubAggregations) |
| 59 |
if len(a.subAggregations) > 0 { |
| 60 |
aggsMap := make(map[string]interface{}) |
| 61 |
source["aggregations"] = aggsMap |
| 62 |
for name, aggregate := range a.subAggregations { |
| 63 |
src, err := aggregate.Source() |
| 64 |
if err != nil { |
| 65 |
return nil, err |
| 66 |
} |
| 67 |
aggsMap[name] = src |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
// Add Meta data if available |
| 72 |
if len(a.meta) > 0 { |
| 73 |
source["meta"] = a.meta |
| 74 |
} |
| 75 |
|
| 76 |
return source, nil |
| 77 |
} |