search_aggs_bucket_global.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. package elastic
  5. // GlobalAggregation defines a single bucket of all the documents within
  6. // the search execution context. This context is defined by the indices
  7. // and the document types you’re searching on, but is not influenced
  8. // by the search query itself.
  9. // See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-global-aggregation.html
  10. type GlobalAggregation struct {
  11. subAggregations map[string]Aggregation
  12. meta map[string]interface{}
  13. }
  14. func NewGlobalAggregation() *GlobalAggregation {
  15. return &GlobalAggregation{
  16. subAggregations: make(map[string]Aggregation),
  17. }
  18. }
  19. func (a *GlobalAggregation) SubAggregation(name string, subAggregation Aggregation) *GlobalAggregation {
  20. a.subAggregations[name] = subAggregation
  21. return a
  22. }
  23. // Meta sets the meta data to be included in the aggregation response.
  24. func (a *GlobalAggregation) Meta(metaData map[string]interface{}) *GlobalAggregation {
  25. a.meta = metaData
  26. return a
  27. }
  28. func (a *GlobalAggregation) Source() (interface{}, error) {
  29. // Example:
  30. // {
  31. // "aggs" : {
  32. // "all_products" : {
  33. // "global" : {},
  34. // "aggs" : {
  35. // "avg_price" : { "avg" : { "field" : "price" } }
  36. // }
  37. // }
  38. // }
  39. // }
  40. // This method returns only the { "global" : {} } part.
  41. source := make(map[string]interface{})
  42. opts := make(map[string]interface{})
  43. source["global"] = opts
  44. // AggregationBuilder (SubAggregations)
  45. if len(a.subAggregations) > 0 {
  46. aggsMap := make(map[string]interface{})
  47. source["aggregations"] = aggsMap
  48. for name, aggregate := range a.subAggregations {
  49. src, err := aggregate.Source()
  50. if err != nil {
  51. return nil, err
  52. }
  53. aggsMap[name] = src
  54. }
  55. }
  56. // Add Meta data if available
  57. if len(a.meta) > 0 {
  58. source["meta"] = a.meta
  59. }
  60. return source, nil
  61. }