search_aggs_bucket_children.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. // ChildrenAggregation is a special single bucket aggregation that enables
  6. // aggregating from buckets on parent document types to buckets on child documents.
  7. // It is available from 1.4.0.Beta1 upwards.
  8. // See: https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-bucket-children-aggregation.html
  9. type ChildrenAggregation struct {
  10. typ string
  11. subAggregations map[string]Aggregation
  12. meta map[string]interface{}
  13. }
  14. func NewChildrenAggregation() *ChildrenAggregation {
  15. return &ChildrenAggregation{
  16. subAggregations: make(map[string]Aggregation),
  17. }
  18. }
  19. func (a *ChildrenAggregation) Type(typ string) *ChildrenAggregation {
  20. a.typ = typ
  21. return a
  22. }
  23. func (a *ChildrenAggregation) SubAggregation(name string, subAggregation Aggregation) *ChildrenAggregation {
  24. a.subAggregations[name] = subAggregation
  25. return a
  26. }
  27. // Meta sets the meta data to be included in the aggregation response.
  28. func (a *ChildrenAggregation) Meta(metaData map[string]interface{}) *ChildrenAggregation {
  29. a.meta = metaData
  30. return a
  31. }
  32. func (a *ChildrenAggregation) Source() (interface{}, error) {
  33. // Example:
  34. // {
  35. // "aggs" : {
  36. // "to-answers" : {
  37. // "children": {
  38. // "type" : "answer"
  39. // }
  40. // }
  41. // }
  42. // }
  43. // This method returns only the { "type" : ... } part.
  44. source := make(map[string]interface{})
  45. opts := make(map[string]interface{})
  46. source["children"] = opts
  47. opts["type"] = a.typ
  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. src, err := aggregate.Source()
  54. if err != nil {
  55. return nil, err
  56. }
  57. aggsMap[name] = src
  58. }
  59. }
  60. // Add Meta data if available
  61. if len(a.meta) > 0 {
  62. source["meta"] = a.meta
  63. }
  64. return source, nil
  65. }