Skip to content

[GH-3556] Add an include_tie_breakers argument to ST_KNN - #3630

Open
jiayuasu wants to merge 3 commits into
apache:masterfrom
jiayuasu:feature/knn-include-tie-breakers
Open

jiayuasu wants to merge 3 commits into
apache:masterfrom
jiayuasu:feature/knn-include-tie-breakers

Conversation

@jiayuasu

@jiayuasu jiayuasu commented Dec 4, 2026 •

Copy link
Copy Markdown
Member

Did you read the Contributor Guide?

Is this PR related to a ticket?

What changes were proposed in this PR?

ST_KNN takes an optional include_tie_breakers argument. It says whether a KNN join also returns the objects that are as near as the k-th nearest one (true), or at most k objects (false):

SELECT *
FROM queries JOIN objects
ON ST_KNN(queries.geom, objects.geom, 3, false, true)

Until now only the spark.sedona.join.knn.includeTieBreakers setting decided this. The join reads the setting when it runs, so the rows of a query or a view depended on the session that executed it, and two KNN joins in one query could not differ. With the argument, the choice is part of the query. SedonaDB has the same argument (apache/sedona-db#1577).

  • Geometry: ST_KNN(a, b, k, use_spheroid, include_tie_breakers), the same form as in SedonaDB.
  • Geography: ST_KNN(a, b, k, include_tie_breakers). The geography forms take no use_spheroid, as with ST_Buffer on geography, so the argument comes right after k. The five-argument form does not accept geographies and fails at analysis time.
  • The argument must be a constant true or false. A column reference or a NULL fails at planning time with a message that names the argument.
  • Without the argument the setting decides, as before. Existing queries do not change.

The value is kept as an Option[Boolean] on JoinQueryDetection and on the four KNN join nodes (KNNJoinExec, BroadcastQuerySideKNNJoinExec, BroadcastObjectSideKNNJoinExec, BroadcastGeographyKNNJoinExec). None means that the setting decides. The Scala DataFrame API has two new ST_KNN overloads for the five-argument form.

A fourth argument on geographies was rejected before this PR, and geography ST_KNN is not in a release yet. LocalOutlierFactor and the GeoPandas sjoin_nearest still use the setting and are not changed here.

Which objects are tie breakers

The geometry join had two defects in the rows that it returns with tie breakers. They are fixed here, because the argument makes these rows part of a query's result:

  • The join compared the distance in the units of the coordinates, also when use_spheroid is true and the neighbors are ranked by a distance in meters. For a query at POINT(0 80), the object at POINT(0 81) was returned as a tie of the object at POINT(1 80), which is about six times nearer.
  • A tied row was left out when its geometry was equal to the geometry of a row that was already a neighbor.

InMemoryKNNJoinIterator now finds the ties in two steps, as before, but with the metric of the join in both:

  1. The search of the index for k neighbors gives a distance that the k-th nearest object is within.
  2. The join reads every object within this distance from the index, measures each with the item distance that ranks the neighbors, and keeps the ones that are as near as the k-th. Each row is a neighbor of its own, also when another row has the same geometry.

With use_spheroid the distance is in meters and the index is in degrees. The range of latitudes and longitudes for the distance comes from Haversine.expandEnvelope, which distance joins already use. The query is moved to the meridian of 0 degrees for it, so that the range is not folded at 180 degrees, and the range is searched in each full turn of longitude that the index reaches. A tie is found at longitudes above 180, such as the output of ST_ShiftLongitude, on the other side of the antimeridian, and in a table with the other longitude convention.

The search of the index (STRtree.nearestNeighbour) prunes a branch by its distance in degrees and compares that with distances in meters. With use_spheroid it can leave out an object that is as near as the ones it returns, or nearer, when the object is a full turn of longitude away in degrees. With tie breakers the result no longer depends on this, because the objects within the distance are ranked again. Without tie breakers the join returns what that search returns, as before this PR. That is #3634.

The cost is the cost before this PR: one search for k neighbors and one range query. In a benchmark of the iterator with k = 1 and tie breakers on 10,000 objects, 5,000 places with two records a few meters apart, a query takes 296 µs on the sphere and 3.7 µs in the plane, against 284 µs and 4.2 µs before. With a query polygon that has 1,000 points inside, in the plane, a query takes 120 µs, against 113 µs before.

On the partitioned plan a line or a polygon can still be returned more than once for a query, with and without tie breakers. That is #3632 and is not changed here.

How was this patch tested?

KnnJoinSuite:

  • For each of the three geometry join strategies (partitioned, broadcast on the query side, broadcast on the object side), every combination of the setting (false, true) and the argument (omitted, false, true). The argument decides where it is given, and the setting decides where it is not.
  • In the five-argument form the fourth argument is still use_spheroid. The test uses objects at 80 degrees north whose nearest neighbor is different in degrees and on the spheroid.
  • A column reference and a NULL as include_tie_breakers are rejected.
  • The two new DataFrame API overloads.
  • For each strategy, two rows at one point are both returned, for use_spheroid false and true, also when they tie with an object on the other side of the query, and when k is above the number of objects.
  • For each strategy, objects that are one degree away to the east and to the north are a tie with use_spheroid false and not with use_spheroid true. On a grid of one degree cells joined with itself, the ties are the neighbors in four directions in degrees and the neighbors to the east and west on the sphere.
  • For each strategy, points at 90 degrees west and the same points after ST_ShiftLongitude, at 270 degrees, have the same two tied neighbors, for use_spheroid false and true.
  • For each strategy, twenty objects on two meridians that are 360 degrees apart in degrees and one meridian on the sphere, at 180 and -180 degrees and at 270 and -90 degrees. The nearest pair is returned for k = 1, and the pair that ties for the third place for k = 3.

InMemoryKNNJoinIteratorTest (new). The first three cases use an index of three levels:

  • ties a full turn of longitude away, in both directions, with the sphere and the spheroid metric,
  • a nearer object in the other longitude convention, which the search of the index leaves out,
  • ties on the far side of a pole,
  • a neighbor with eleven ties, and k above the number of objects, up to Integer.MAX_VALUE.

KnnJoinGeographySuite:

  • For each of the four broadcast layouts, ST_KNN(geog, geog, k, true) with the setting off and ST_KNN(geog, geog, k, false) with the setting on, and the four-argument form through the DataFrame API.
  • The test that expected a fourth argument on geographies to be rejected now expects the five-argument form to be rejected.

The tests of the argument, of the two defects and of the ties a full turn of longitude away fail without the change. The test with ST_ShiftLongitude passes without it too: it keeps the ties that the join already found there. The KNN suites pass on Spark 3.5 with Scala 2.12 and on Spark 4.0 with Scala 2.13. The whole spark/common module on Spark 3.5 passes locally except for 12 tests that need the libpostal data directory or Docker.

Did this PR include necessary documentation updates?

  • Yes, I have updated the documentation: the formats, a new "Ties" section and the geography section of docs/api/sql/NearestNeighbourSearching.md, the row of spark.sedona.join.knn.includeTieBreakers on docs/api/sql/Parameter.md, and the .zh.md version of both pages. The argument is marked as available since v2.0.0. The GeoPandas pages and the sjoin_nearest docstring no longer say that rows with identical geometries can be left out of the ties.

ST_KNN takes an optional constant argument that says whether the join
also returns the objects as near as the k-th nearest one. It comes
after use_spheroid for geometries,
ST_KNN(a, b, k, use_spheroid, include_tie_breakers), and after k for
geographies, ST_KNN(a, b, k, include_tie_breakers), which take no
use_spheroid. Without the argument the
spark.sedona.join.knn.includeTieBreakers setting decides, as before.
…ith equal geometries

With tie breakers, the join took an object as a tie when it was as far
from the query as the k-th neighbor in the units of the coordinates, also
when use_spheroid ranks the neighbors by a distance in meters. An object
at one degree of latitude was a tie of an object at one degree of
longitude. The search for ties now measures with the item distance that
ranked the neighbors, and looks for candidates in the range of longitudes
and latitudes that covers this distance.

The join also left out a tied row when its geometry was equal to the
geometry of a row that was already a neighbor. The neighbors are now told
apart by the indexed object, so each row of a repeated point is returned.
…f the k-th neighbor

The search for ties looked for candidates in an envelope around the query.
With use_spheroid this envelope was folded into the longitudes from -180
to 180, while the index keeps the coordinates as they are. A tie at 269 or
271 degrees, which ST_ShiftLongitude produces, was not found.

The join now takes the distance of the farthest of the k neighbors that
the index returns, reads every object within this distance from the index
and ranks them again. The range of longitudes for the distance comes from
Haversine.expandEnvelope with the query moved to the meridian of 0 degrees.
It is searched in each full turn of longitude that the index reaches, so a
tie on the other side of the antimeridian or in the other longitude
convention is found as well.

The search of the index prunes a branch by its distance in degrees, which
can leave out an object that is as near in meters, or nearer. With tie
breakers the result no longer depends on what that search left out.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

KNN Join including tie config needs to be a function call param like SedonaDB

1 participant