-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathtest_sjoin.py
More file actions
493 lines (438 loc) · 18 KB
/
test_sjoin.py
File metadata and controls
493 lines (438 loc) · 18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
# 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.
import json
import re
import warnings
import geopandas as gpd
import numpy as np
import pandas as pd
import pytest
import sedonadb
from sedonadb.testing import PostGIS, SedonaDB, random_geometry
from shapely.geometry import Point
@pytest.mark.parametrize(
"join_type", ["INNER JOIN", "LEFT OUTER JOIN", "RIGHT OUTER JOIN"]
)
@pytest.mark.parametrize(
"on",
[
"ST_Intersects(sjoin_point.geometry, sjoin_polygon.geometry)",
"ST_Within(sjoin_point.geometry, sjoin_polygon.geometry)",
"ST_Contains(sjoin_polygon.geometry, sjoin_point.geometry)",
"ST_DWithin(sjoin_point.geometry, sjoin_polygon.geometry, 1.0)",
"ST_DWithin(sjoin_point.geometry, sjoin_polygon.geometry, sjoin_point.dist / 100)",
"ST_DWithin(sjoin_point.geometry, sjoin_polygon.geometry, sjoin_polygon.dist / 100)",
],
)
def test_spatial_join(join_type, on):
with (
SedonaDB.create_or_skip() as eng_sedonadb,
PostGIS.create_or_skip() as eng_postgis,
):
df_point = random_geometry("Point", 100, seed=42)
df_polygon = random_geometry(
"Polygon", 100, hole_rate=0.5, num_vertices=(2, 10), seed=43
)
eng_sedonadb.create_table_arrow("sjoin_point", df_point)
eng_sedonadb.create_table_arrow("sjoin_polygon", df_polygon)
eng_postgis.create_table_arrow("sjoin_point", df_point)
eng_postgis.create_table_arrow("sjoin_polygon", df_polygon)
sql = f"""
SELECT sjoin_point.id id0, sjoin_polygon.id id1
FROM sjoin_point {join_type} sjoin_polygon
ON {on}
ORDER BY id0, id1
"""
sedonadb_results = eng_sedonadb.execute_and_collect(sql).to_pandas()
assert len(sedonadb_results) > 0
eng_postgis.assert_query_result(sql, sedonadb_results)
def _plan_text(df):
query_plan = df.to_pandas()
return "\n".join(query_plan.iloc[:, 1].astype(str).tolist())
def _spatial_join_side_file_names(plan_text):
"""Extract the left/right parquet file names used by `SpatialJoinExec`.
Example input:
SpatialJoinExec: join_type=Inner, on=ST_intersects(geo_right@0, geo_left@0)
ProjectionExec: expr=[geometry@0 as geo_right]
DataSourceExec: file_groups={1 group: [[.../natural-earth_countries_geo.parquet]]}, projection=[geometry], file_type=parquet
ProbeShuffleExec: partitioning=RoundRobinBatch(1)
ProjectionExec: expr=[geometry@0 as geo_left]
DataSourceExec: file_groups={1 group: [[.../natural-earth_cities_geo.parquet]]}, projection=[geometry], file_type=parquet
Example output:
["natural-earth_countries_geo", "natural-earth_cities_geo"]
"""
spatial_join_idx = plan_text.find("SpatialJoinExec:")
assert spatial_join_idx != -1, plan_text
file_names = re.findall(
r"DataSourceExec:.*?/([^/\]]+)\.parquet", plan_text[spatial_join_idx:]
)
assert len(file_names) >= 2, plan_text
return file_names[:2]
def test_spatial_join_reordering_can_be_disabled_e2e(geoarrow_data):
path_left = (
geoarrow_data / "natural-earth" / "files" / "natural-earth_cities_geo.parquet"
)
path_right = (
geoarrow_data
/ "natural-earth"
/ "files"
/ "natural-earth_countries_geo.parquet"
)
assert path_left.exists(), f"Missing test asset: {path_left}"
assert path_right.exists(), f"Missing test asset: {path_right}"
with SedonaDB.create_or_skip() as eng_sedonadb:
sql = f"""
SELECT t1.name
FROM '{path_left}' AS t1
JOIN '{path_right}' AS t2
ON ST_Intersects(t1.geometry, t2.geometry)
"""
# Test 1: regular run swaps the join order
plan_text = _plan_text(eng_sedonadb.con.sql(f"EXPLAIN {sql}"))
print(f"Plan with reordering enabled:\n{plan_text}")
assert _spatial_join_side_file_names(plan_text) == [
"natural-earth_countries_geo",
"natural-earth_cities_geo",
], plan_text
result_with_reordering = (
eng_sedonadb.execute_and_collect(sql)
.to_pandas()
.sort_values("name")
.reset_index(drop=True)
)
assert len(result_with_reordering) > 0
# Test 2: with config disabled, join won't reorder
eng_sedonadb.con.sql(
"SET sedona.spatial_join.spatial_join_reordering TO false"
).execute()
plan_text = _plan_text(eng_sedonadb.con.sql(f"EXPLAIN {sql}"))
print(f"Plan with reordering disabled:\n{plan_text}")
assert _spatial_join_side_file_names(plan_text) == [
"natural-earth_cities_geo",
"natural-earth_countries_geo",
], plan_text
result_without_reordering = (
eng_sedonadb.execute_and_collect(sql)
.to_pandas()
.sort_values("name")
.reset_index(drop=True)
)
pd.testing.assert_frame_equal(
result_without_reordering,
result_with_reordering,
)
@pytest.mark.parametrize(
"join_type",
[
"LEFT SEMI JOIN",
"LEFT ANTI JOIN",
"RIGHT SEMI JOIN",
"RIGHT ANTI JOIN",
],
)
@pytest.mark.parametrize(
"on",
[
"ST_Intersects(sjoin_point.geometry, sjoin_polygon.geometry)",
"ST_Within(sjoin_point.geometry, sjoin_polygon.geometry)",
"ST_Contains(sjoin_polygon.geometry, sjoin_point.geometry)",
"ST_DWithin(sjoin_point.geometry, sjoin_polygon.geometry, 1.0)",
"ST_DWithin(sjoin_point.geometry, sjoin_polygon.geometry, sjoin_point.dist / 100)",
"ST_DWithin(sjoin_point.geometry, sjoin_polygon.geometry, sjoin_polygon.dist / 100)",
],
)
def test_spatial_join_semi_anti(join_type, on):
with (
SedonaDB.create_or_skip() as eng_sedonadb,
PostGIS.create_or_skip() as eng_postgis,
):
options = json.dumps(
{
"geom_type": "Point",
"polygon_hole_rate": 0.5,
"num_parts_range": [2, 10],
"vertices_per_linestring_range": [2, 10],
"seed": 42,
}
)
df_point = eng_sedonadb.execute_and_collect(
f"SELECT * FROM sd_random_geometry('{options}') LIMIT 100"
)
options = json.dumps(
{
"geom_type": "Polygon",
"polygon_hole_rate": 0.5,
"num_parts_range": [2, 10],
"vertices_per_linestring_range": [2, 10],
"seed": 43,
}
)
df_polygon = eng_sedonadb.execute_and_collect(
f"SELECT * FROM sd_random_geometry('{options}') LIMIT 100"
)
eng_sedonadb.create_table_arrow("sjoin_point", df_point)
eng_sedonadb.create_table_arrow("sjoin_polygon", df_polygon)
eng_postgis.create_table_arrow("sjoin_point", df_point)
eng_postgis.create_table_arrow("sjoin_polygon", df_polygon)
is_left = join_type.startswith("LEFT")
is_semi = "SEMI" in join_type
if is_left:
sedona_sql = f"""
SELECT sjoin_point.id id0
FROM sjoin_point {join_type} sjoin_polygon
ON {on}
ORDER BY id0
"""
exists = f"EXISTS (SELECT 1 FROM sjoin_polygon WHERE {on})"
where = exists if is_semi else f"NOT {exists}"
postgis_sql = f"""
SELECT sjoin_point.id id0
FROM sjoin_point
WHERE {where}
ORDER BY id0
"""
else:
sedona_sql = f"""
SELECT sjoin_polygon.id id1
FROM sjoin_point {join_type} sjoin_polygon
ON {on}
ORDER BY id1
"""
exists = f"EXISTS (SELECT 1 FROM sjoin_point WHERE {on})"
where = exists if is_semi else f"NOT {exists}"
postgis_sql = f"""
SELECT sjoin_polygon.id id1
FROM sjoin_polygon
WHERE {where}
ORDER BY id1
"""
sedonadb_results = eng_sedonadb.execute_and_collect(sedona_sql).to_pandas()
assert len(sedonadb_results) > 0
eng_postgis.assert_query_result(postgis_sql, sedonadb_results)
@pytest.mark.parametrize(
"outer",
["point", "polygon"],
)
@pytest.mark.parametrize(
"on",
[
"ST_Intersects(sjoin_point.geometry, sjoin_polygon.geometry)",
"ST_Within(sjoin_point.geometry, sjoin_polygon.geometry)",
"ST_DWithin(sjoin_point.geometry, sjoin_polygon.geometry, 1.0)",
],
)
def test_spatial_mark_join_via_correlated_exists(outer, on):
with (
SedonaDB.create_or_skip() as eng_sedonadb,
PostGIS.create_or_skip() as eng_postgis,
):
options = json.dumps(
{
"geom_type": "Point",
"polygon_hole_rate": 0.5,
"num_parts_range": [2, 10],
"vertices_per_linestring_range": [2, 10],
"seed": 42,
}
)
df_point = eng_sedonadb.execute_and_collect(
f"SELECT * FROM sd_random_geometry('{options}') LIMIT 100"
)
options = json.dumps(
{
"geom_type": "Polygon",
"polygon_hole_rate": 0.5,
"num_parts_range": [2, 10],
"vertices_per_linestring_range": [2, 10],
"seed": 43,
}
)
df_polygon = eng_sedonadb.execute_and_collect(
f"SELECT * FROM sd_random_geometry('{options}') LIMIT 100"
)
eng_sedonadb.create_table_arrow("sjoin_point", df_point)
eng_sedonadb.create_table_arrow("sjoin_polygon", df_polygon)
eng_postgis.create_table_arrow("sjoin_point", df_point)
eng_postgis.create_table_arrow("sjoin_polygon", df_polygon)
if outer == "point":
sql = f"""
SELECT sjoin_point.id id0
FROM sjoin_point
WHERE sjoin_point.id = 1 OR EXISTS (SELECT 1 FROM sjoin_polygon WHERE {on})
ORDER BY id0
"""
else:
sql = f"""
SELECT sjoin_polygon.id id1, ST_AsBinary(sjoin_polygon.geometry) geom
FROM sjoin_polygon
WHERE sjoin_polygon.id = 1 OR EXISTS (SELECT 1 FROM sjoin_point WHERE {on})
ORDER BY id1
"""
# Verify the physical query plan contains a Mark join
query_plan = eng_sedonadb.execute_and_collect(f"EXPLAIN {sql}").to_pandas()
plan_text = "\n".join(query_plan.iloc[:, 1].astype(str).tolist())
assert any(
"SpatialJoinExec" in line and ("LeftMark" in line or "RightMark" in line)
for line in plan_text.splitlines()
), plan_text
sedonadb_results = eng_sedonadb.execute_and_collect(sql).to_pandas()
assert len(sedonadb_results) > 0
eng_postgis.assert_query_result(sql, sedonadb_results)
@pytest.mark.parametrize(
"join_type", ["INNER JOIN", "LEFT OUTER JOIN", "RIGHT OUTER JOIN"]
)
@pytest.mark.parametrize(
"on",
[
"ST_Intersects(sjoin_geog1.geog, sjoin_geog2.geog)",
"ST_Distance(sjoin_geog1.geog, sjoin_geog2.geog) < 100000",
],
)
def test_spatial_join_geography(join_type, on):
if "s2geography" not in sedonadb.__features__:
pytest.skip("Python package built without s2geography")
with (
SedonaDB.create_or_skip() as eng_sedonadb,
PostGIS.create_or_skip() as eng_postgis,
):
# Select two sets of bounding boxes that cross the antimeridian,
# which would be disjoint on a Euclidean plane. A geography join will produce non-empty results,
# whereas a geometry join would not.
west_most_bound = [-190, -10, -170, 10]
east_most_bound = [170, -10, 190, 10]
options = json.dumps(
{
"geom_type": "Point",
"num_parts": [2, 10],
"num_vertices": [2, 10],
"bounds": west_most_bound,
"size": [0.1, 5],
"seed": 542,
}
)
df_point = eng_sedonadb.execute_and_collect(
f"SELECT id, ST_SetSRID(ST_GeogFromWKB(ST_AsBinary(geometry)), 4326) geog, dist FROM sd_random_geometry('{options}') LIMIT 100"
)
options = json.dumps(
{
"geom_type": "Polygon",
"hole_rate": 0.5,
"num_parts": [2, 10],
"num_vertices": [2, 10],
"bounds": east_most_bound,
"size": [0.1, 5],
"seed": 44,
}
)
df_polygon = eng_sedonadb.execute_and_collect(
f"SELECT id, ST_SetSRID(ST_GeogFromWKB(ST_AsBinary(geometry)), 4326) geog, dist FROM sd_random_geometry('{options}') LIMIT 100"
)
eng_sedonadb.create_table_arrow("sjoin_geog1", df_point)
eng_sedonadb.create_table_arrow("sjoin_geog2", df_polygon)
eng_postgis.create_table_arrow("sjoin_geog1", df_point)
eng_postgis.create_table_arrow("sjoin_geog2", df_polygon)
sql = f"""
SELECT sjoin_geog1.id id0, sjoin_geog2.id id1
FROM sjoin_geog1 {join_type} sjoin_geog2
ON {on}
ORDER BY id0, id1
"""
sedonadb_results = eng_sedonadb.execute_and_collect(sql).to_pandas()
eng_postgis.assert_query_result(sql, sedonadb_results)
def test_query_window_in_subquery():
with (
SedonaDB.create_or_skip() as eng_sedonadb,
PostGIS.create_or_skip() as eng_postgis,
):
df_point = random_geometry("Point", 100, seed=100)
df_polygon = random_geometry(
"Polygon", 100, hole_rate=0.5, num_vertices=(2, 10), size=(50, 60), seed=999
)
eng_sedonadb.create_table_arrow("sjoin_point", df_point)
eng_sedonadb.create_table_arrow("sjoin_polygon", df_polygon)
eng_postgis.create_table_arrow("sjoin_point", df_point)
eng_postgis.create_table_arrow("sjoin_polygon", df_polygon)
# This should be optimized to a spatial join
sql = """
SELECT id FROM sjoin_point AS L
WHERE ST_Intersects(L.geometry, (SELECT R.geometry FROM sjoin_polygon AS R WHERE R.id = 1))
ORDER BY id
"""
# Verify that the physical query plan should contain a SpatialJoinExec
query_plan = eng_sedonadb.execute_and_collect(f"EXPLAIN {sql}").to_pandas()
assert "SpatialJoinExec" in query_plan.iloc[1, 1]
sedonadb_results = eng_sedonadb.execute_and_collect(sql).to_pandas()
assert len(sedonadb_results) > 0
eng_postgis.assert_query_result(sql, sedonadb_results)
def test_non_optimizable_subquery():
with (
SedonaDB.create_or_skip() as eng_sedonadb,
PostGIS.create_or_skip() as eng_postgis,
):
df_main = random_geometry("Point", 100, seed=42)
df_subquery = random_geometry("Point", 100, seed=43)
eng_sedonadb.create_table_arrow("sjoin_main", df_main)
eng_sedonadb.create_table_arrow("sjoin_subquery", df_subquery)
eng_postgis.create_table_arrow("sjoin_main", df_main)
eng_postgis.create_table_arrow("sjoin_subquery", df_subquery)
# This cannot be optimized to a spatial join, but the query result should still be correct
sql = """
SELECT id FROM sjoin_main AS L
WHERE ST_DWithin(L.geometry, ST_Point(10, 10), (SELECT R.dist FROM sjoin_subquery AS R WHERE R.id = 1))
ORDER BY id
"""
sedonadb_results = eng_sedonadb.execute_and_collect(sql).to_pandas()
assert len(sedonadb_results) > 0
eng_postgis.assert_query_result(sql, sedonadb_results)
def test_spatial_join_with_pandas_metadata(con):
# Previous versions of SedonaDB failed to execute this because of a mismatched
# schema. Attempts to simplify this reproducer weren't able to recreate the
# initial error (PhysicalOptimizer rule 'join_selection' failed).
# https://github.com/apache/sedona-db/issues/477
# 1. Generate Data
n_points = 1000
n_polys = 10
# Points
rng = np.random.Generator(np.random.MT19937(49791))
lons = rng.uniform(-6, 2, n_points)
lats = rng.uniform(50, 59, n_points)
pts_df = pd.DataFrame(
{"idx": range(n_points), "geometry": [Point(x, y) for x, y in zip(lons, lats)]}
)
pts_gdf = gpd.GeoDataFrame(pts_df, crs="EPSG:4326")
# Polygons (Centers buffered)
plons = rng.uniform(-6, 2, n_polys)
plats = rng.uniform(50, 59, n_polys)
poly_centers = gpd.GeoDataFrame(
{"geometry": [Point(x, y) for x, y in zip(plons, plats)]}, crs="EPSG:4326"
)
# Simple buffer in degrees (test data so we don't need the GeoPandas warning here)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
polys_gdf = poly_centers.buffer(0.1).to_frame(name="geometry")
# 2. Load
con.create_data_frame(pts_gdf).to_view("points", overwrite=True)
con.create_data_frame(polys_gdf).to_view("polygons", overwrite=True)
# 3. Intersection
query = """
SELECT p.idx
FROM points AS p, polygons AS poly
WHERE ST_Intersects(p.geometry, poly.geometry)
ORDER BY p.idx
"""
res = con.sql(query).to_pandas()
pd.testing.assert_frame_equal(res, pd.DataFrame({"idx": [304, 342, 490, 705]}))