search_aggs_nested.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. package elastic
  5. // NestedAggregation is a special single bucket aggregation that enables
  6. // aggregating nested documents.
  7. // See: http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-aggregations-bucket-nested-aggregation.html
  8. type NestedAggregation struct {
  9. path string
  10. subAggregations map[string]Aggregation
  11. }
  12. func NewNestedAggregation() NestedAggregation {
  13. a := NestedAggregation{
  14. subAggregations: make(map[string]Aggregation),
  15. }
  16. return a
  17. }
  18. func (a NestedAggregation) SubAggregation(name string, subAggregation Aggregation) NestedAggregation {
  19. a.subAggregations[name] = subAggregation
  20. return a
  21. }
  22. func (a NestedAggregation) Path(path string) NestedAggregation {
  23. a.path = path
  24. return a
  25. }
  26. func (a NestedAggregation) Source() interface{} {
  27. // Example:
  28. // {
  29. // "query" : {
  30. // "match" : { "name" : "led tv" }
  31. // }
  32. // "aggs" : {
  33. // "resellers" : {
  34. // "nested" : {
  35. // "path" : "resellers"
  36. // },
  37. // "aggs" : {
  38. // "min_price" : { "min" : { "field" : "resellers.price" } }
  39. // }
  40. // }
  41. // }
  42. // }
  43. // This method returns only the { "nested" : {} } part.
  44. source := make(map[string]interface{})
  45. opts := make(map[string]interface{})
  46. source["nested"] = opts
  47. opts["path"] = a.path
  48. // AggregationBuilder (SubAggregations)
  49. if len(a.subAggregations) > 0 {
  50. aggsMap := make(map[string]interface{})
  51. source["aggregations"] = aggsMap
  52. for name, aggregate := range a.subAggregations {
  53. aggsMap[name] = aggregate.Source()
  54. }
  55. }
  56. return source
  57. }