You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@sedona.apache.org by "zhangfengcdt (via GitHub)" <gi...@apache.org> on 2026/04/27 16:01:34 UTC

[PR] [GH-2830] Add broadcast spatial-join support for the Geography type with ST_Contains [sedona]

zhangfengcdt opened a new pull request, #2864:
URL: https://github.com/apache/sedona/pull/2864

   ## Did you read the Contributor Guide?
   
   - Yes, I have read the [Contributor Rules](https://sedona.apache.org/latest/community/rule/) and [Contributor Development Guide](https://sedona.apache.org/latest/community/develop/)
   
   ## Is this PR related to a ticket?
   
   - Yes, and the PR name follows the format `[GH-XXX] my subject`. Closes #<issue_number>
   
   ## What changes were proposed in this PR?
   
   Adds broadcast spatial-join support for the Geography type with ST_Contains. JoinQueryDetector now plans BroadcastIndexJoinExec for ST_Contains(geog, geog) with a broadcast() hint (previously fell back to a row-by-row BroadcastNestedLoopJoin). The build side is indexed by each Geography's lat/lng bounding rect (full-longitude fallback at the antimeridian) and refined with the existing S2 Functions.contains. Non-broadcast Geography joins still fall through to row-by-row.
   
   Also fixes a Geography ST_Contains correctness bug uncovered during testing.
   
   Out of scope: range/partition joins, distance/KNN joins, and true split-at-±180 indexing for antimeridian polygons.
   
   EXPLAIN on SELECT … JOIN /*+ BROADCAST(b) */ b ON ST_Contains(a.geog, b.geog) now shows BroadcastIndexJoinExec.
   
   
   ## How was this patch tested?
   
   New tests:
     - common/.../WkbContainsRoundtripTest — 4/4
     - spark/common/.../BroadcastIndexJoinGeographySuite — 5/5 (both broadcast sides, antimeridian polygon, plan-choice + correctness)
   
   Regression (Spark 3.4 / Scala 2.12), 363/363 total:
     - S2Geography.*Test 83/83, Geography.*Test 33/33
     - BroadcastIndexJoinSuite 65/65, SpatialJoinSuite 160/160, GeographyFunctionTest 17/17
   
   
   ## Did this PR include necessary documentation updates?
   
   - No, this PR does not affect any public API so no need to change the documentation.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [GH-2830] Add broadcast spatial-join support for the Geography type with ST_Contains [sedona]

Posted by "jiayuasu (via GitHub)" <gi...@apache.org>.
jiayuasu commented on PR #2864:
URL: https://github.com/apache/sedona/pull/2864#issuecomment-4339568001

   @zhangfengcdt Please fix these simple comments otherwise this PR is read to be merged


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [GH-2830] Add broadcast spatial-join support for the Geography type with ST_Contains [sedona]

Posted by "zhangfengcdt (via GitHub)" <gi...@apache.org>.
zhangfengcdt commented on code in PR #2864:
URL: https://github.com/apache/sedona/pull/2864#discussion_r3157768364


##########
spark/common/src/test/scala/org/apache/sedona/sql/geography/BroadcastIndexJoinGeographySuite.scala:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.sedona.sql.geography
+
+import org.apache.sedona.sql.TestBaseScala
+import org.apache.spark.sql.functions.{broadcast, expr}
+import org.apache.spark.sql.sedona_sql.strategy.join.BroadcastIndexJoinExec
+
+class BroadcastIndexJoinGeographySuite extends TestBaseScala {
+
+  // Three unit-square polygons centred at integer offsets.
+  private lazy val polygonGeogDf = {
+    val rows = (0 until 3).map { i =>
+      (i, s"POLYGON((${i} ${i}, ${i + 1} ${i}, ${i + 1} ${i + 1}, ${i} ${i + 1}, ${i} ${i}))")
+    }
+    import sparkSession.implicits._
+    rows
+      .toDF("poly_id", "wkt")
+      .selectExpr("poly_id", "ST_GeogFromWKT(wkt, 4326) AS poly_geog")
+  }
+
+  // One point inside each of the three polygons (3 hits) plus three points outside.
+  private lazy val pointGeogDf = {
+    val rows = Seq(
+      (0, "POINT(0.5 0.5)"), // in polygon 0
+      (1, "POINT(1.5 1.5)"), // in polygon 1
+      (2, "POINT(2.5 2.5)"), // in polygon 2
+      (3, "POINT(10 10)"), // outside
+      (4, "POINT(20 20)"), // outside
+      (5, "POINT(30 30)") // outside
+    )
+    import sparkSession.implicits._
+    rows
+      .toDF("pt_id", "wkt")
+      .selectExpr("pt_id", "ST_GeogFromWKT(wkt, 4326) AS pt_geog")
+  }
+
+  private def planUsesBroadcastIndexJoin(df: org.apache.spark.sql.DataFrame): Boolean =

Review Comment:
   Yes — both LEFT OUTER and RIGHT OUTER broadcast variants are supported. The planner only matches them when the build side aligns with the join type:
   
   LEFT OUTER ⇒ broadcast right
   RIGHT OUTER ⇒ broadcast left
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [GH-2830] Add broadcast spatial-join support for the Geography type with ST_Contains [sedona]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #2864:
URL: https://github.com/apache/sedona/pull/2864#discussion_r3157573406


##########
spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/strategy/join/BroadcastIndexJoinExec.scala:
##########
@@ -169,14 +177,8 @@ case class BroadcastIndexJoinExec(
         .iterator
         .asScala
         .asInstanceOf[Iterator[Geometry]]
-        .filter(candidate =>
-          evaluator.eval(
-            preparedGeometries.getOrElseUpdate(
-              candidate, {
-                factory.create(candidate)
-              }),
-            geom))
-        .map(candidate => joinedRow.withRight(candidate.getUserData.asInstanceOf[UnsafeRow]))
+        .filter(candidate => refiner.matches(candidate, geom))
+        .map(candidate => joinedRow.withRight(refiner.unpackRow(candidate)))
         .exists(boundCondition)
 

Review Comment:
   `semiJoin` also assumes `geom` is non-null and calls `geom.getEnvelopeInternal`. Since `createStreamShapes` can return null shapes when the join key is null, this can throw an NPE. Align behavior with `antiJoin`/`outerJoin` by treating null stream shapes as having zero candidates (thus producing no output for LeftSemi).



##########
spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/strategy/join/TraitJoinQueryBase.scala:
##########
@@ -57,6 +58,30 @@ trait TraitJoinQueryBase {
     spatialRdd
   }
 
+  /**
+   * Builds a SpatialRDD from a column of GeographyUDT bytes. Each row becomes a JTS geometry
+   * whose envelope is the Geography's lat/lng bounding rectangle (full-longitude when the
+   * rectangle wraps the antimeridian). The Geography object is carried alongside the original row
+   * in `userData` via [[GeographyJoinShape]] so the join executor can perform S2-based predicate
+   * refinement and emit the row.
+   */
+  def toGeographySpatialRDD(
+      rdd: RDD[UnsafeRow],
+      shapeExpression: Expression): SpatialRDD[Geometry] = {
+    val spatialRdd = new SpatialRDD[Geometry]
+    spatialRdd.setRawSpatialRDD(
+      rdd
+        .map { x =>
+          val geog =
+            GeographyWKBSerializer.deserialize(shapeExpression.eval(x).asInstanceOf[Array[Byte]])
+          val shape = JoinedGeometry.geographyToEnvelopeGeometry(geog)
+          shape.setUserData(GeographyJoinShape(geog, x.copy))
+          shape

Review Comment:
   `toGeographySpatialRDD` deserializes `shapeExpression.eval(x)` unconditionally. If the Geography join key column is nullable, a null value will cause `GeographyWKBSerializer.deserialize(null)` to throw and fail the broadcast-index build. Consider adding a null check (skip the row or create a null/empty envelope entry consistent with how nulls are handled on the stream side).
   ```suggestion
           .flatMap { x =>
             val geogBytes = shapeExpression.eval(x).asInstanceOf[Array[Byte]]
             if (geogBytes == null) {
               None
             } else {
               val geog = GeographyWKBSerializer.deserialize(geogBytes)
               val shape = JoinedGeometry.geographyToEnvelopeGeometry(geog)
               shape.setUserData(GeographyJoinShape(geog, x.copy))
               Some(shape)
             }
   ```



##########
common/src/main/java/org/apache/sedona/common/S2Geography/WkbS2Shape.java:
##########
@@ -229,6 +243,18 @@ private int findChain(int edgeId) {
     return 0;
   }
 
+  /**
+   * Returns true when the ring's first and last vertex coordinates are byte-identical (i.e. the
+   * ring is closed in the standard WKB sense). Sedona's own WKBWriter produces open rings, so a
+   * cheap byte-level comparison lets us distinguish the two cases without running through the
+   * S2Point conversion.
+   */
+  private static boolean firstAndLastEqual(ByteBuffer buf, int byteOffset, int numCoords) {
+    int lastOffset = byteOffset + (numCoords - 1) * 16;
+    return buf.getDouble(byteOffset) == buf.getDouble(lastOffset)
+        && buf.getDouble(byteOffset + 8) == buf.getDouble(lastOffset + 8);
+  }

Review Comment:
   The comment for `firstAndLastEqual` says it checks whether coordinates are "byte-identical" and does a "byte-level comparison", but the implementation compares doubles using `==` (numeric equality). Either update the comment to match the behavior, or implement an actual byte-wise comparison if that distinction matters for correctness.



##########
spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/strategy/join/BroadcastIndexJoinExec.scala:
##########
@@ -146,20 +158,16 @@ case class BroadcastIndexJoinExec(
         .iterator
         .asScala
         .asInstanceOf[Iterator[Geometry]]
-        .filter(candidate =>
-          evaluator.eval(
-            preparedGeometries.getOrElseUpdate(candidate, { factory.create(candidate) }),
-            geom))
-        .map(candidate => joinedRow.withRight(candidate.getUserData.asInstanceOf[UnsafeRow]))
+        .filter(candidate => refiner.matches(candidate, geom))
+        .map(candidate => joinedRow.withRight(refiner.unpackRow(candidate)))
         .filter(boundCondition)
     }
   }

Review Comment:
   `innerJoin` calls `geom.getEnvelopeInternal` without guarding for `geom == null`, but `createStreamShapes` can emit `(null, row)` when the join key evaluates to null. This will throw a NullPointerException instead of treating null join keys as non-matching rows. Consider short-circuiting null stream shapes (e.g., return `Iterator.empty` for inner joins) before querying the index.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [GH-2830] Add broadcast spatial-join support for the Geography type with ST_Contains [sedona]

Posted by "jiayuasu (via GitHub)" <gi...@apache.org>.
jiayuasu commented on code in PR #2864:
URL: https://github.com/apache/sedona/pull/2864#discussion_r3157623418


##########
spark/common/src/test/scala/org/apache/sedona/sql/geography/BroadcastIndexJoinGeographySuite.scala:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.sedona.sql.geography
+
+import org.apache.sedona.sql.TestBaseScala
+import org.apache.spark.sql.functions.{broadcast, expr}
+import org.apache.spark.sql.sedona_sql.strategy.join.BroadcastIndexJoinExec
+
+class BroadcastIndexJoinGeographySuite extends TestBaseScala {
+
+  // Three unit-square polygons centred at integer offsets.
+  private lazy val polygonGeogDf = {
+    val rows = (0 until 3).map { i =>
+      (i, s"POLYGON((${i} ${i}, ${i + 1} ${i}, ${i + 1} ${i + 1}, ${i} ${i + 1}, ${i} ${i}))")
+    }
+    import sparkSession.implicits._
+    rows
+      .toDF("poly_id", "wkt")
+      .selectExpr("poly_id", "ST_GeogFromWKT(wkt, 4326) AS poly_geog")
+  }
+
+  // One point inside each of the three polygons (3 hits) plus three points outside.
+  private lazy val pointGeogDf = {
+    val rows = Seq(
+      (0, "POINT(0.5 0.5)"), // in polygon 0
+      (1, "POINT(1.5 1.5)"), // in polygon 1
+      (2, "POINT(2.5 2.5)"), // in polygon 2
+      (3, "POINT(10 10)"), // outside
+      (4, "POINT(20 20)"), // outside
+      (5, "POINT(30 30)") // outside
+    )
+    import sparkSession.implicits._
+    rows
+      .toDF("pt_id", "wkt")
+      .selectExpr("pt_id", "ST_GeogFromWKT(wkt, 4326) AS pt_geog")
+  }
+
+  private def planUsesBroadcastIndexJoin(df: org.apache.spark.sql.DataFrame): Boolean =

Review Comment:
   I assume left join / right join (broadcast version) will work as well?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [GH-2830] Add broadcast spatial-join support for the Geography type with ST_Contains [sedona]

Posted by "zhangfengcdt (via GitHub)" <gi...@apache.org>.
zhangfengcdt merged PR #2864:
URL: https://github.com/apache/sedona/pull/2864


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org