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