You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

search_queries_geo_polygon.go 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. // GeoPolygonQuery allows to include hits that only fall within a polygon of points.
  6. //
  7. // For more details, see:
  8. // https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-geo-polygon-query.html
  9. type GeoPolygonQuery struct {
  10. name string
  11. points []*GeoPoint
  12. queryName string
  13. }
  14. // NewGeoPolygonQuery creates and initializes a new GeoPolygonQuery.
  15. func NewGeoPolygonQuery(name string) *GeoPolygonQuery {
  16. return &GeoPolygonQuery{
  17. name: name,
  18. points: make([]*GeoPoint, 0),
  19. }
  20. }
  21. // AddPoint adds a point from latitude and longitude.
  22. func (q *GeoPolygonQuery) AddPoint(lat, lon float64) *GeoPolygonQuery {
  23. q.points = append(q.points, GeoPointFromLatLon(lat, lon))
  24. return q
  25. }
  26. // AddGeoPoint adds a GeoPoint.
  27. func (q *GeoPolygonQuery) AddGeoPoint(point *GeoPoint) *GeoPolygonQuery {
  28. q.points = append(q.points, point)
  29. return q
  30. }
  31. func (q *GeoPolygonQuery) QueryName(queryName string) *GeoPolygonQuery {
  32. q.queryName = queryName
  33. return q
  34. }
  35. // Source returns JSON for the function score query.
  36. func (q *GeoPolygonQuery) Source() (interface{}, error) {
  37. // "geo_polygon" : {
  38. // "person.location" : {
  39. // "points" : [
  40. // {"lat" : 40, "lon" : -70},
  41. // {"lat" : 30, "lon" : -80},
  42. // {"lat" : 20, "lon" : -90}
  43. // ]
  44. // }
  45. // }
  46. source := make(map[string]interface{})
  47. params := make(map[string]interface{})
  48. source["geo_polygon"] = params
  49. polygon := make(map[string]interface{})
  50. params[q.name] = polygon
  51. var points []interface{}
  52. for _, point := range q.points {
  53. points = append(points, point.Source())
  54. }
  55. polygon["points"] = points
  56. if q.queryName != "" {
  57. params["_name"] = q.queryName
  58. }
  59. return source, nil
  60. }