Querying: Spatial
To perform a spatial search, you can use the spatial()
method which contains a full spectrum of spatial capabilities. You can check the detailed Client API reference for this method here.
Radius Search
The most basic usage and probably most common one is to search for all points or shapes within provided distance from the given center point. To perform this search use the withinRadius()
method.
const results = await session
.query(Event)
.spatial(new PointField("latitude", "longitude"),
criteria => criteria.withinRadius(500, 30, 30))
.all();
from Events
where spatial.within(spatial.point(latitude, longitude), spatial.circle(500, 30, 30))
Advanced Search
The most advanced (and low-level) method available is relatesToShape()
const results = await session
.query(Event)
.spatial(new PointField("latitude", "longitude"),
criteria => criteria.relatesToShape(
"Circle(30 30 d=500.0000)",
"Within"
))
.all();
from Events
where spatial.within(spatial.point(latitude, longitude), spatial.wkt('Circle(30 30 d=500.0000)'))
Where the shape is in WKT format and the relation is one of within
, contains
, disjoint
, intersects
. The above example will yield the same results as the example from the Radius Search
section.
Polygons
When using spatial.wkt()
to define a polygon, the vertices (points that form the corners of the polygon) must be listed
in a counter-clockwise order:
Static Indexes
All of the above examples are using the dynamic querying capabilities of RavenDB and will create automatic indexes to retrieve their results. However, spatial queries can also be performed against static indexes, and this is done in a very similar way.
const results = await session
.query({ indexName: "Events/ByCoordinates" })
.spatial("coordinates",
criteria => criteria.withinRadius(500, 30, 30))
.all();
class Events_ByCoordinates extends AbstractIndexCreationTask {
constructor() {
super();
this.map = `docs.Events.Select(e => new {
Coordinates = this.CreateSpatialField(((double?) e.latitude), ((double?) e.longitude))
})`;
}
}
from index 'Events/ByCoordinates'
where spatial.within(coordinates, spatial.circle(500, 30, 30))
Information
If you want to know how to setup and customize a spatial field in static index please refer to this article.
Ordering
In order to sort the results by distance, please use the orderByDistance()
or orderByDistanceDescending()
methods. You can read more about them here.
Remarks
Information
Distance in RavenDB by default is measured in kilometers.