Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,12 @@ public Iterator<Tuple2<Integer, Geometry>> placeObject(Geometry geometry) {
List<Tuple2<Integer, Geometry>> result = new ArrayList<>();
Envelope objectEnvelope = geometry.getEnvelopeInternal();

// Query the spatial index for intersecting envelopes
List<Integer> intersectingIds = spatialExpandedBoundaryIndex.query(objectEnvelope);
// Query the spatial index for intersecting envelopes. The index has an entry for each cell
// of a partition's expanded boundary, so an object that meets several cells of a partition
// is found several times. Place it in the partition once: a second copy would be returned
// as a second neighbor.
Set<Integer> intersectingIds =
new LinkedHashSet<Integer>(spatialExpandedBoundaryIndex.query(objectEnvelope));

for (Integer partitionId : intersectingIds) {
result.add(new Tuple2<>(partitionId, geometry));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* 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.core.spatialPartitioning.quadtree;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.junit.Test;
import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;

public class ExtendedQuadTreeTest {

private final GeometryFactory factory = new GeometryFactory();

/**
* The expanded boundary of a partition is a list of cells. An object that reaches across several
* of these cells still belongs to the partition once: a second copy would be returned as a second
* neighbor by a KNN join.
*/
@Test
public void testPlacesAnObjectOnceInAPartition() throws Exception {
ExtendedQuadTree<Integer> tree = new ExtendedQuadTree<>(new Envelope(0, 20, 0, 20), 4);
for (int x = 0; x <= 20; x++) {
for (int y = 0; y <= 20; y++) {
tree.insert(new Envelope(x, x, y, y));
}
}
tree.build(3);

// The square lies across the middle of the boundary, where the cells meet
Geometry square = factory.toGeometry(new Envelope(9.5, 10.5, 9.5, 10.5));
List<Integer> partitions = new ArrayList<>();
tree.placeObject(square).forEachRemaining(placed -> partitions.add(placed._1));

assertTrue(partitions.size() > 1);
assertEquals(new HashSet<>(partitions).size(), partitions.size());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,62 @@ class KnnJoinSuite extends TestBaseScala with TableDrivenPropertyChecks {
}
}

it("KNN Join returns a neighbor once when objects lie across partition cells") {
withConf(
Map(
"spark.sql.adaptive.enabled" -> "false",
"spark.sql.autoBroadcastJoinThreshold" -> "-1",
"spark.sedona.join.autoBroadcastJoinThreshold" -> "-1")) {
try {
// Squares around the points of a grid, in four partitions. The join splits the
// objects into cells, and the squares in the middle of the grid lie across them.
val side = 21
val x = s"CAST(id % $side AS DOUBLE)"
val y = s"CAST(FLOOR(id / $side) AS DOUBLE)"
sparkSession
.sql(
s"SELECT CAST(id AS INT) AS id, ST_Point($x, $y) AS g FROM range(${side * side})")
.repartition(4)
.createOrReplaceTempView("knn_cell_queries")
sparkSession
.sql(
s"SELECT CAST(id AS INT) AS id, ST_PolygonFromEnvelope($x - 0.25D, $y - 0.25D, " +
s"$x + 0.25D, $y + 0.25D) AS g FROM range(${side * side})")
.repartition(4)
.createOrReplaceTempView("knn_cell_objects")
// Every object that is as near as the third nearest one, from a ranking of all pairs
val ranked = sparkSession
.sql("""SELECT qid, oid FROM (
| SELECT q.id AS qid, o.id AS oid,
| RANK() OVER (PARTITION BY q.id ORDER BY ST_Distance(q.g, o.g)) AS position
| FROM knn_cell_queries q CROSS JOIN knn_cell_objects o)
|WHERE position <= 3""".stripMargin)
.collect()
.map(row => (row.getInt(0), row.getInt(1)))
.sorted
.toSeq
def pairs(includeTieBreakers: Boolean): Seq[(Int, Int)] =
withConf(
Map("spark.sedona.join.knn.includeTieBreakers" -> includeTieBreakers.toString)) {
val joined = sparkSession.sql(
"SELECT q.id, o.id FROM knn_cell_queries q JOIN knn_cell_objects o " +
"ON ST_KNN(q.g, o.g, 3, false)")
val plan = joined.queryExecution.executedPlan
assert(plan.find(_.getClass == classOf[KNNJoinExec]).isDefined, plan.toString)
joined.collect().map(row => (row.getInt(0), row.getInt(1))).sorted.toSeq
}
pairs(includeTieBreakers = true) should be(ranked)
val withoutTies = pairs(includeTieBreakers = false)
withoutTies.size should be(side * side * 3)
// A pair that the join returns twice is left over here
withoutTies.diff(ranked) should be(Seq.empty)
} finally {
sparkSession.catalog.dropTempView("knn_cell_queries")
sparkSession.catalog.dropTempView("knn_cell_objects")
}
}
}

it("KNN Join with exact algorithms should not fail with null geometries") {
val queries = sparkSession
.createDataFrame(sc.parallelize(Seq(Tuple1("POINT (0.0 0.0)"), Tuple1(null: String))))
Expand Down
Loading