search_aggs_bucket_nested.go 2.1 KB

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