Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions docs/api/sql/NearestNeighbourSearching.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,63 @@ In case there are ties in the distance, the result will include all the tied geo
spark.sedona.join.knn.includeTieBreakers=true
```

### ST_KNN on Geography

Format: `ST_KNN(R: Geography, S: Geography, k: Integer)`

Since: `v2.0.0`

`ST_KNN` also accepts [Geography](geography/Geography-Functions.md) columns. R is the queries side and S is the object side, as above. Each query row is joined with its `k` nearest object rows.

Neighbors are ranked by the distance that [ST_Distance](geography/Geography-Functions/ST_Distance.md) returns for two geographies: the shortest distance on the sphere between them, in meters. This has three consequences:

- There is no `use_spheroid` argument. Geographies are always measured on the sphere, so only the three-argument form accepts them.
- Lines and polygons are not replaced by their centroids. The distance to a polygon is the distance to its nearest point, and it is zero when the query lies inside the polygon.
- Neighbors are found correctly across the antimeridian and around the poles.

Both arguments must be geographies. To join a geography with a geometry, convert the geometry first with [ST_GeomToGeography](geography/Geography-Constructors/ST_GeomToGeography.md).

A geography `ST_KNN` join runs as a broadcast join, so one side must fit in memory. Either side can be broadcast. Add a broadcast hint to the smaller side, or set `sedona.join.autoBroadcastJoinThreshold` high enough for Sedona to broadcast it automatically. If neither side is broadcast, query planning fails with an error. Only inner joins are supported.

The other rules on this page apply to geographies as well: NULL and empty geographies are skipped, ties are returned only when `spark.sedona.join.knn.includeTieBreakers` is `true`, and additional `ON` predicates are evaluated on the neighbors that `ST_KNN` selected.

SQL Example:

```sql
SELECT /*+ BROADCAST(a) */
s.name AS station,
a.name AS airport,
ROUND(ST_Distance(s.geog, a.geog) / 1000) AS km
FROM stations AS s
JOIN airports AS a
ON ST_KNN(s.geog, a.geog, 1)
ORDER BY station
```

With these two tables:

```
stations airports
name geog name geog
Suva POINT (178.44 -18.14) Apia POINT (-171.76 -13.83)
Longyearbyen POINT (15.63 78.22) Noumea POINT (166.46 -22.27)
Alert POINT (-62.35 82.50)
Tromso POINT (18.96 69.65)
```

Output:

```
+------------+-------+------+
|station |airport|km |
+------------+-------+------+
|Longyearbyen|Tromso |958.0 |
|Suva |Apia |1152.0|
+------------+-------+------+
```

Apia is on the other side of the antimeridian from Suva. In longitude and latitude degrees it looks much farther away than Noumea, but on the sphere it is the nearer of the two.

### Filter Pushdown Considerations:

When using ST_KNN with filters applied to the resulting DataFrame, some of these filters may be pushed down to the object side of the kNN join. This means the filters will be applied to the object side reader before the kNN join is executed. If you want the filters to be applied after the kNN join, ensure that you first materialize the kNN join results and then apply the filters.
Expand Down
57 changes: 57 additions & 0 deletions docs/api/sql/NearestNeighbourSearching.zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,63 @@ Sedona 通过提供地理空间 k 近邻(kNN)连接方法来支持对地理
spark.sedona.join.knn.includeTieBreakers=true
```

### Geography 上的 ST_KNN

格式:`ST_KNN(R: Geography, S: Geography, k: Integer)`

起始版本:`v2.0.0`

`ST_KNN` 也接受 [Geography](geography/Geography-Functions.md) 列。与上文相同,R 是查询侧,S 是对象侧。每一条查询行会与距离它最近的 `k` 条对象行连接。

邻居按 [ST_Distance](geography/Geography-Functions/ST_Distance.md) 对两个 geography 返回的距离排序,即两者在球面上的最短距离,单位为米。由此带来三点不同:

- 没有 `use_spheroid` 参数。Geography 始终在球面上度量,因此只有三参数形式接受 geography。
- 线和面不会被替换为质心。到一个面的距离是到该面上最近点的距离;当查询对象位于面内时,距离为零。
- 跨越反子午线(±180° 经线)以及极点附近的邻居都能被正确找到。

两个参数都必须是 geography。如果要把 geography 与 geometry 连接,请先用 [ST_GeomToGeography](geography/Geography-Constructors/ST_GeomToGeography.md) 转换 geometry。

Geography 上的 `ST_KNN` 连接以广播连接的方式执行,因此其中一侧必须能放入内存。两侧都可以被广播。请给较小的一侧加上广播提示,或者把 `sedona.join.autoBroadcastJoinThreshold` 设置得足够大,让 Sedona 自动广播它。如果两侧都没有被广播,查询规划会报错。仅支持内连接。

本页的其他规则同样适用于 geography:NULL 和空的 geography 会被跳过;只有当 `spark.sedona.join.knn.includeTieBreakers` 为 `true` 时才返回并列的结果;`ON` 中的其他谓词作用于 `ST_KNN` 已选出的邻居。

SQL 示例:

```sql
SELECT /*+ BROADCAST(a) */
s.name AS station,
a.name AS airport,
ROUND(ST_Distance(s.geog, a.geog) / 1000) AS km
FROM stations AS s
JOIN airports AS a
ON ST_KNN(s.geog, a.geog, 1)
ORDER BY station
```

使用下面两张表:

```
stations airports
name geog name geog
Suva POINT (178.44 -18.14) Apia POINT (-171.76 -13.83)
Longyearbyen POINT (15.63 78.22) Noumea POINT (166.46 -22.27)
Alert POINT (-62.35 82.50)
Tromso POINT (18.96 69.65)
```

输出:

```
+------------+-------+------+
|station |airport|km |
+------------+-------+------+
|Longyearbyen|Tromso |958.0 |
|Suva |Apia |1152.0|
+------------+-------+------+
```

Apia 与 Suva 分别位于反子午线的两侧。按经纬度的度数看,它比 Noumea 远得多;但在球面上,它才是两者中较近的一个。

### 谓词下推注意事项:

在 ST_KNN 之后对结果 DataFrame 施加的过滤条件,部分可能会被下推到 kNN 连接的对象侧。这意味着这些过滤会在 kNN 连接执行之前应用到对象侧的读取阶段。如果你希望过滤在 kNN 连接之后再生效,请先将 kNN 连接的结果物化,然后再应用过滤条件。
Expand Down
1 change: 1 addition & 0 deletions docs/api/sql/geography/Geography-Functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ These functions operate on geography type objects.
| [ST_Contains](Geography-Functions/ST_Contains.md) | Boolean | Test whether geography A fully contains geography B. | v1.9.0 |
| [ST_Intersects](Geography-Functions/ST_Intersects.md) | Boolean | Test whether two geographies intersect. | v1.9.1 |
| [ST_DWithin](Geography-Functions/ST_DWithin.md) | Boolean | Test whether two geographies are within a given geodesic distance (in meters) of each other. | v1.9.1 |
| [ST_KNN](../NearestNeighbourSearching.md#st_knn-on-geography) | Boolean | Join condition that matches each geography with its `k` nearest geographies, ranked by geodesic distance. | v2.0.0 |
| [ST_Within](Geography-Functions/ST_Within.md) | Boolean | Test whether geography A is fully within geography B. | v1.9.1 |
| [ST_Equals](Geography-Functions/ST_Equals.md) | Boolean | Test whether two geographies are spatially equal. | v1.9.1 |
| [ST_X](Geography-Functions/ST_X.md) | Double | Return the longitude (X coordinate) of a point geography. | v1.9.1 |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
package org.apache.spark.sql.sedona_sql.expressions

import org.apache.sedona.common.Predicates
import org.apache.sedona.common.S2Geography.Geography
import org.apache.sedona.sql.utils.GeometrySerializer
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions.codegen.CodegenFallback
Expand Down Expand Up @@ -402,14 +403,27 @@ private[apache] case class ST_3DDWithin(inputExpressions: Seq[Expression])
* Test if leftGeometry is one of the k nearest neighbors (KNN) of rightGeometry based on
* approximate distance metric.
*
* The geography overload takes no use_spheroid flag: geographies are always ranked by their
* distance on the sphere.
*
* @param inputExpressions
*/
private[apache] case class ST_KNN(inputExpressions: Seq[Expression])
extends InferredExpression(
inferrableFunction3(Predicates.knn),
inferrableFunction4(Predicates.knn)) {
inferrableFunction4(Predicates.knn),
inferrableFunction3(GeographyKnnPredicate.knn)) {

protected def withNewChildrenInternal(newChildren: IndexedSeq[Expression]) = {
copy(inputExpressions = newChildren)
}
}

/**
* ST_KNN over geographies is only meaningful as a join condition, where the join strategy
* implements it. Like the geometry overloads, it cannot be evaluated one pair at a time.
*/
private object GeographyKnnPredicate {
def knn(query: Geography, neighbor: Geography, k: Int): Boolean =
throw new UnsupportedOperationException("KNN predicate is not supported")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.spark.sql.sedona_sql.strategy.join

import org.apache.sedona.common.geography.GeographyKnnIndex
import org.apache.sedona.core.utils.SedonaConf
import org.apache.spark.internal.Logging
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeRowJoiner
import org.apache.spark.sql.catalyst.expressions.{Attribute, BindReferences, Expression, Predicate, UnsafeRow}
import org.apache.spark.sql.execution.SparkPlan
import org.apache.spark.sql.sedona_sql.execution.SedonaBinaryExecNode

import scala.collection.JavaConverters._

/**
* The objects of a geography KNN join as they are broadcast to the executors. The index over them
* is built once per JVM, on first use.
*/
private[join] final class BroadcastGeographyKnnIndex(objects: Array[GeographyKnnInput])
extends Serializable {
@transient lazy val index: GeographyKnnIndex[UnsafeRow] = {
val index = new GeographyKnnIndex[UnsafeRow]()
objects.foreach(input => index.add(input.geography, input.row))
index
}
}

/**
* Inner join on `ST_KNN(queryShape, objectShape, k)` over geography inputs, with one side
* broadcast. Each query row is joined with its k nearest object rows, ranked by the distance that
* `ST_Distance(geography, geography)` returns.
*
* - When the object side is broadcast, the objects are collected and indexed once, and every
* query row searches that index.
* - When the query side is broadcast, every partition of objects is indexed and searched by
* every query, and the per-partition neighbours of a query are merged into its k nearest.
*
* @param queryShape
* the first argument of ST_KNN, a geography from the query side
* @param objectShape
* the second argument of ST_KNN, a geography from the object side
* @param broadcastSide
* the side of the join that is broadcast
* @param querySide
* the side of the join that `queryShape` comes from
* @param k
* the number of neighbours per query row
* @param extraCondition
* the rest of the join condition, applied to the k nearest neighbours that were found
*/
case class BroadcastGeographyKNNJoinExec(
left: SparkPlan,
right: SparkPlan,
queryShape: Expression,
objectShape: Expression,
broadcastSide: JoinSide,
querySide: JoinSide,
k: Expression,
extraCondition: Option[Expression] = None)
extends SedonaBinaryExecNode
with Logging {

override def output: Seq[Attribute] = left.output ++ right.output

override protected def doExecute(): RDD[InternalRow] = {
val kValue = k.eval().asInstanceOf[Int]
val includeTies = SedonaConf.fromActiveSession.isIncludeTieBreakersInKNNJoins
val (queryPlan, objectPlan) = if (querySide == LeftSide) (left, right) else (right, left)
val boundQueryShape = BindReferences.bindReference(queryShape, queryPlan.output)
val boundObjectShape = BindReferences.bindReference(objectShape, objectPlan.output)
val queryRows = queryPlan.execute().asInstanceOf[RDD[UnsafeRow]]
val objectRows = objectPlan.execute().asInstanceOf[RDD[UnsafeRow]]

if (broadcastSide == querySide) {
logInfo("Geography KNN join: broadcasting the query side")
joinWithBroadcastQueries(
collectInputs(queryRows, boundQueryShape),
objectRows,
boundObjectShape,
kValue,
includeTies)
} else {
logInfo("Geography KNN join: broadcasting the object side")
joinWithBroadcastObjects(
queryRows,
boundQueryShape,
collectInputs(objectRows, boundObjectShape),
kValue,
includeTies)
}
}

/** Collects the rows of the broadcast side that have a non-empty geography. */
private def collectInputs(
rows: RDD[UnsafeRow],
boundShape: Expression): Array[GeographyKnnInput] =
rows
.mapPartitions(_.flatMap { row =>
GeographyKnnInput.from(TraitJoinQueryBase.shapeToGeography(boundShape, row), row.copy())
})
.collect()

private def joinWithBroadcastObjects(
queryRows: RDD[UnsafeRow],
boundQueryShape: Expression,
objects: Array[GeographyKnnInput],
kValue: Int,
includeTies: Boolean): RDD[InternalRow] = {
if (objects.isEmpty) {
return sparkContext.emptyRDD[InternalRow]
}
val broadcastObjects = sparkContext.broadcast(new BroadcastGeographyKnnIndex(objects))
val toOutput = outputRows
queryRows.mapPartitions { rows =>
val index = broadcastObjects.value.index
toOutput(rows.flatMap { queryRow =>
val query = TraitJoinQueryBase.shapeToGeography(boundQueryShape, queryRow)
// The query row stays valid while its neighbours are consumed: the outer iterator only
// advances once this inner iterator is exhausted.
index
.nearest(query, kValue, includeTies)
.iterator
.asScala
.map(neighbor => (queryRow, neighbor.getItem))
})
}
}

private def joinWithBroadcastQueries(
queries: Array[GeographyKnnInput],
objectRows: RDD[UnsafeRow],
boundObjectShape: Expression,
kValue: Int,
includeTies: Boolean): RDD[InternalRow] = {
if (queries.isEmpty) {
return sparkContext.emptyRDD[InternalRow]
}
val broadcastQueries = sparkContext.broadcast(queries)
// The nearest neighbours of every query within each partition of objects, keyed by the
// position of the query in the broadcast array.
val partitionNeighbors = objectRows.mapPartitions { rows =>
val index = new GeographyKnnIndex[UnsafeRow]()
rows.foreach { row =>
index.add(TraitJoinQueryBase.shapeToGeography(boundObjectShape, row), row.copy())
}
if (index.isEmpty) {
Iterator.empty
} else {
broadcastQueries.value.iterator.zipWithIndex.flatMap { case (query, queryId) =>
val neighbors = index.nearest(query.geography, kValue, includeTies)
if (neighbors.isEmpty) None else Some((queryId, neighbors))
}
}
}
val toOutput = outputRows
partitionNeighbors
.reduceByKey((a, b) => GeographyKnnIndex.merge(a, b, kValue, includeTies))
.mapPartitions { neighborsByQuery =>
toOutput(neighborsByQuery.flatMap { case (queryId, neighbors) =>
val queryRow = broadcastQueries.value(queryId).row
neighbors.iterator.asScala.map(neighbor => (queryRow, neighbor.getItem))
})
}
}

/**
* Returns a function, safe to ship to executors, that turns (query row, object row) pairs into
* the output rows of this join: the two rows concatenated in left / right order, filtered by
* the rest of the join condition.
*/
private def outputRows: Iterator[(UnsafeRow, UnsafeRow)] => Iterator[InternalRow] = {
val leftSchema = left.schema
val rightSchema = right.schema
val queriesOnLeft = querySide == LeftSide
val joinOutput = output
val residual = extraCondition
matches => {
val joiner = GenerateUnsafeRowJoiner.create(leftSchema, rightSchema)
val joined = matches.map { case (queryRow, objectRow) =>
if (queriesOnLeft) joiner.join(queryRow, objectRow) else joiner.join(objectRow, queryRow)
}
residual match {
case Some(condition) =>
val boundCondition = Predicate.create(condition, joinOutput)
joined.filter(row => boundCondition.eval(row))
case None => joined
}
}
}

protected def withNewChildrenInternal(newLeft: SparkPlan, newRight: SparkPlan): SparkPlan = {
copy(left = newLeft, right = newRight)
}
}
Loading
Loading