Reputation: 2087
I have a project using Spring Boot 1.5.7 and Spring Data Mongodb 1.10.7. In my entity (POJO annotated with @Document), I want to perform a geospatial query against one of the fields using spring data repos "findByXxxWithin" scheme and passing in a Box containing the bounding box of the search area.
The field I want to query against is a polygon, not a simple point. I have found that a double[] point definition is easy to query and some examples show that you can also use a GeoJsonPoint. For polygons, it doesn't seem that easy. If my entity declares a GeoJsonPoint, the within search using the Box always comes back empty. The GeoJson definition of a polygon is actually a 3 dimensional array of values, in my case, doubles. Defining the data in this manner also results in an empty result. Any attempt to use a of POJO that contains the polygon definition fails. The only success I've had is using a double[][].
I would like to have a more accurate GeoJson representation of the data in my objects that spring data is capable of querying against. Is this possible? Also, there are several other geospatial query operations available to Mongodb, such as $geoIntersects. Are these available through spring data? Or perhaps a lower level api I can use to directly formulate these queries against mongo if spring data does not support them?
Upvotes: 0
Views: 1949
Reputation: 73
Let me try to recite one of my work with MongoDB and Spring data, which resembles your problem statement quite a bit.
I have a document which has georeference (Latitude and Longitude). I have used org.geojson.LngLatAlt object to store longitudes and latitudes. You can also have multiple LngLatAlt objects, as I use a Set (java.util.Set) of them. So, this will solve your problem of representation in your document.
Now, when you have data is present in MongoDB, you can make geospatial queries using Spring data. At first, it may look like Spring data is quite in-efficient in geospatial queries, you may be tempted to use native MongoDB queries, which is definitely good and efficient. But the thing to learn here is, Spring also provides a way to make such queries; although not very direct but equally efficient. With Spring Data, you can make spatial queries using org.springframework.data.geo.Box or org.springframework.data.geo.Circle objects. Box is used for BBOX queries and circle is used for sphere queries. Now that you have your org.springframework.data.geo.Shape objects, you can make Criteria objects to Query.
Code snippet -
@Autowired
private MongoTemplate mongoTemplate;
Box bbox = ShapeUtils.getBBox(coordinates);
Query q = new Query(Criteria.where("lngLatAlt").within(bbox));
List<Lead> leads = mongoTemplate.find(q, Lead.class);
Please let me know if my solution is clear and relevant. Or if you need some more clarifications.
Regards
Upvotes: 1