Reputation: 11
Does anyone have a code sample using geojson shape in ElasticSearch 7.x shape query?
It works when I build the shape using ES builders, however I need to use geojson passed in (see below), which likely needs parsing of geojson into ES shape:
{"type":"Polygon","coordinates":[[[-82.30957031249999,26.657277674217585],[-81.7767333984375,25.84686509678058],[-80.90057373046875,24.986058021167594],[-80.25238037109375,25.16517336866393],[-79.97222900390625,26.08885491679362],[-79.771728515625,26.76277822801415],[-80.2606201171875,27.25707120788274],[-80.83740234375,27.332735136859146],[-81.529541015625,27.166695222253114],[-82.30957031249999,26.657277674217585]]]}
Upvotes: 1
Views: 1058
Reputation: 11
My query shapes are simple polygons, so I ended up converting it to an array of points and creating a polygon out of these:
if (null != shape) {
JSONObject jsonShape = new JSONObject(shape);
JSONArray coords = jsonShape.getJSONArray("coordinates");
CoordinatesBuilder cb = new CoordinatesBuilder();
for (Object coord: coords.getJSONArray(0)) {
JSONArray c = new JSONArray(coord.toString());
cb.coordinate((Double)c.get(0), (Double)c.get(1));
}
PolygonBuilder pb = new PolygonBuilder(cb);
gsqb = QueryBuilders.geoShapeQuery("FOOTPRINT", pb.buildGeometry());
}
Upvotes: 0
Reputation: 1111
I've been struggling with this as well though I actually wanted to feed a JTS Geometry directly to a query. The solution I came up with was to use WrapperQueryBuilder
to write the query in JSON:
import org.elasticsearch.common.geo.ShapeRelation;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
...
String queryName = "...";
String geoJson = "...";
QueryBuilder geoShapeQuery = QueryBuilders.wrapperQuery(
String.format(
"{ \"geo_shape\": { \"%s\": { \"shape\": %s, \"relation\": \"%s\" } } }",
queryName,
geoJson,
ShapeRelation.INTERSECTS.getRelationName()));
Upvotes: 1