search_aggs_metrics_geo_centroid.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. // GeoCentroidAggregation is a metric aggregation that computes the weighted centroid
  6. // from all coordinate values for a Geo-point datatype field.
  7. // See: https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-aggregations-metrics-geocentroid-aggregation.html
  8. type GeoCentroidAggregation struct {
  9. field string
  10. script *Script
  11. subAggregations map[string]Aggregation
  12. meta map[string]interface{}
  13. }
  14. func NewGeoCentroidAggregation() *GeoCentroidAggregation {
  15. return &GeoCentroidAggregation{
  16. subAggregations: make(map[string]Aggregation),
  17. }
  18. }
  19. func (a *GeoCentroidAggregation) Field(field string) *GeoCentroidAggregation {
  20. a.field = field
  21. return a
  22. }
  23. func (a *GeoCentroidAggregation) Script(script *Script) *GeoCentroidAggregation {
  24. a.script = script
  25. return a
  26. }
  27. func (a *GeoCentroidAggregation) SubAggregation(name string, subAggregation Aggregation) *GeoCentroidAggregation {
  28. a.subAggregations[name] = subAggregation
  29. return a
  30. }
  31. // Meta sets the meta data to be included in the aggregation response.
  32. func (a *GeoCentroidAggregation) Meta(metaData map[string]interface{}) *GeoCentroidAggregation {
  33. a.meta = metaData
  34. return a
  35. }
  36. func (a *GeoCentroidAggregation) Source() (interface{}, error) {
  37. // Example:
  38. // {
  39. // "query" : {
  40. // "match" : { "business_type" : "shop" }
  41. // },
  42. // "aggs" : {
  43. // "centroid" : {
  44. // "geo_centroid" : {
  45. // "field" : "location"
  46. // }
  47. // }
  48. // }
  49. // }
  50. //
  51. // This method returns only the { "geo_centroid" : { ... } } part.
  52. source := make(map[string]interface{})
  53. opts := make(map[string]interface{})
  54. source["geo_centroid"] = opts
  55. if a.field != "" {
  56. opts["field"] = a.field
  57. }
  58. if a.script != nil {
  59. src, err := a.script.Source()
  60. if err != nil {
  61. return nil, err
  62. }
  63. opts["script"] = src
  64. }
  65. // AggregationBuilder (SubAggregations)
  66. if len(a.subAggregations) > 0 {
  67. aggsMap := make(map[string]interface{})
  68. source["aggregations"] = aggsMap
  69. for name, aggregate := range a.subAggregations {
  70. src, err := aggregate.Source()
  71. if err != nil {
  72. return nil, err
  73. }
  74. aggsMap[name] = src
  75. }
  76. }
  77. // Add Meta data if available
  78. if len(a.meta) > 0 {
  79. source["meta"] = a.meta
  80. }
  81. return source, nil
  82. }