ST_KNN
Introduction: join operation to find the k-nearest neighbors of a point or region in a spatial dataset. Format:ST_KNN(R: Table, S: Table, k: Integer, use_sphere: Boolean, search_radius: Double)
Rrepresents the queries side table.Srepresents the objects side table.Kdenotes the number of nearest neighbors to retrieve.use_sphereselects the distance model.falseuses planar (Euclidean) distance in the geometries’ coordinate units.trueuses great-circle (haversine) distance on a sphere, in meters.search_radiusis an optional parameter that defines the maximum distance within which neighbors will be searched. It is expressed in the same units as the selected distance model: coordinate units (degrees for EPSG:4326 data) whenuse_sphereisfalse, meters whenuse_sphereistrue.
use_sphere = false(planar): distances are the true minimum distance between the two geometries (boundary to boundary). A parcel polygon touching a river has distance0. This is the mode to use for exact nearest-feature searches.use_sphere = true(sphere): each non-point geometry is reduced to its centroid before the distance is computed, so results are approximate for large or elongated geometries.
use_sphere = true, an empty query geometry has no neighbors, and an empty object geometry is never returned as a neighbor.
In case there are ties in the distance, the result will include all the tied geometries only when the following sedona config is set to true:
ST_KNN join does an inner join for the query side table (Table R). It returns only pairs where there is at least one matching neighbor within the k nearest neighbors. If a query point has no valid neighbor (e.g., because k is too large), it is excluded from the result.
Known limitations
ST_KNN join is a new syntax we introduced to Spatial SQL and therefore it has a few known limitations. But we are actively working on solving them.- Filter Pushdown Considerations
- Handling SQL-Defined Tables in ST_KNN Joins
ST_KNN joins, WherobotsDB may attempt to optimize the query in a way that bypasses the intended kNN join logic. Specifically, if you create DataFrames with hard-coded SQL, such as:
SQL Example
Suppose we have two tablesQUERIES and OBJECTS with the following data:
QUERIES table:
FALSE indicates that the sphere distance model is not being used. Instead a planar distance model is being applied, and distances are in the geometries’ coordinate units (degrees for EPSG:4326 data).
Since the search_radius parameter is not provided, there are no constraints on the maximum distance between the query and the objects.
Output:
search_radius Parameter
search_radius = 3.0. With this parameter, only neighbors within 3.0 units of each query geometry are considered.
The search_radius acts as a filter, removing any object geometries that are farther than the specified radius.
When search_radius is applied, the query may return fewer than K neighbors if there aren’t enough points within the radius.
Output:
QUERY_ID = 2), fewer than 4 neighbors are returned since not enough points are within the specified radius.
The search_radius ensures more focused results by excluding distant neighbors, which can be useful for scenarios requiring spatial proximity.
Example 3: Exact Nearest Neighbors With Distances in Meters
To attach the true nearest feature (with an exact distance in meters) to every geometry in a table, transform both sides to a projected, meter-based coordinate reference system, then run ST_KNN with use_sphere = false and k = 1. Planar distance on projected coordinates is the exact minimum distance between the two geometries, boundary to boundary.
EPSG:3311, California Albers); see CRS Transformation. The optional search_radius (25000.0 meters here, written as a double literal) bounds the search and reduces the work the join has to do.
Example 4: Additional join conditions and query hints
The kNN join works with an additional inequality or equality condition, and with a broadcast query hint. These queries return the 16 nearest neighbors from the OBJECTS table based on great-circle distance on a sphere.
Performance considerations
Similar to range joins, kNN joins can be computationally expensive. To optimize performance, consider the following:- Partitioning: Increase the number of partitions with
df.repartition(n)to ensure better distribution of data across nodes. - Broadcasting: For smaller datasets, WherobotsDB will use a broadcast join to avoid shuffling large amounts of data.
Use ST_KNN with geography columns
The three-argument formST_KNN(query_geography, object_geography, k) also accepts geography columns. Both inputs must be geographies; convert geometry inputs with ST_GeomToGeography when needed.
Neighbors are ranked by the shortest spherical distance in meters between the full geographies, using the same distance as ST_Distance. Lines and polygons are not replaced by centroids. This supports searches across the antimeridian and around the poles. Geography calls do not accept a fourth distance-mode argument.
Geography KNN supports inner broadcast joins. One side must fit in memory; broadcast either side with a hint, or allow automatic broadcasting with sedona.join.autoBroadcastJoinThreshold. Planning fails if neither side can be broadcast.
NULL and empty inputs are skipped. Ties are included only when spark.sedona.join.knn.includeTieBreakers is true. For additional ON predicates that remain in the join after optimization, KNN selects neighbors first and the remaining predicates filter those neighbors. Rejected neighbors are not replaced. A predicate pushed into an input before the join changes its candidate set.
ST_AKNN
Introduction: join operation to find the k-nearest neighbors of a point or region in a spatial dataset. Format:ST_AKNN(R: Table, S: Table, k: Integer, use_sphere: Boolean, search_radius: Double)
The ST_AKNN function is similar to ST_KNN, but it uses approximate algorithms to find the k-nearest neighbors. This can be useful for large datasets where exact kNN search is computationally expensive. The trade-off is that approximate algorithms may not always return the exact k-nearest neighbors, but they provide a good approximation in a reasonable amount of time.
Known limitations
Similar to ST_KNN, ST_AKNN join is a new syntax we introduced to Spatial SQL.- Filter Pushdown Considerations
- Handling SQL-Defined Tables in ST_AKNN Joins

