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
1 change: 1 addition & 0 deletions .github/workflows/java.yml
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ jobs:
SKIP_TESTS: ${{ matrix.skipTests }}
SEDONA_SKIP_LIBPOSTAL_TESTS: ${{ matrix.skipLibPostalTests }}
FLINK_VERSION: ${{ matrix.flinkVersion }}
PYTHONPATH: ${{ github.workspace }}/python
run: |
SPARK_COMPAT_VERSION="${SPARK_VERSION:0:3}"

Expand Down
2 changes: 2 additions & 0 deletions docs/setup/install-scala.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,5 @@ A self-contained project allows you to create multiple Scala / Java files and wr

!!!note
The detailed explanation of spark-submit is available on [Spark website](https://spark.apache.org/docs/latest/submitting-applications.html).

See [Spark SQL geometry serialization](sql-geometry-serialization.md) before upgrading data stored with the legacy geometry UDT payload.
81 changes: 81 additions & 0 deletions docs/setup/sql-geometry-serialization.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<!--
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.
-->

# Spark SQL spatial serialization

Starting in v2.0.0, Spark SQL geometry values use a signed four-byte little-endian SRID followed by ISO WKB internally. The JVM uses the public JTS IO implementation and Python uses Shapely WKB. The WKB type codes use ISO offsets (1000 for Z, 2000 for M, 3000 for ZM), and the writer emits little-endian WKB. Readers accept either WKB byte order; the SRID prefix is always little-endian. The prefix supplies the SRID for the whole geometry, including collection members. The SQL transport preserves SRID and supported XY, XYZ, XYM and XYZM layouts, including dimensional empties. Python M support depends on the installed Shapely/GEOS version.

The UDT payload is not a standalone WKB/EWKB value: use `ST_AsBinary` or `ST_AsEWKB` for explicit interchange columns. This changes the internal payload of `GeometryUDT`; it does not change its SQL type name or the Python Shapely geometry API. The JVM writer retains its existing layout validation: explicitly different layouts within a polygon or multipart geometry are rejected, while general geometry collection members can retain independent layouts. Python follows Shapely's public WKB representation, which can preserve mixed member layouts instead of applying the compact SQL serializer's single-layout promotion. When Shapely/GEOS retains the declared dimensions, an XY/XYZ `MultiPoint` remains distinct from an all-XYZ `MultiPoint` whose first Z is NaN in `geom_equals_identical`. GEOS versions before 3.12 can treat a NaN-Z member as XY before Sedona receives the value. The public JVM WKB writer canonicalizes NaN payload bits and represents a point whose X and Y are both NaN as `POINT EMPTY`. SRIDs use the full signed 32-bit prefix instead of the compact format's 24-bit field. Finite coordinates and supported coordinate dimensions are preserved.

## Geography SQL values

`GeographyUDT` uses the same four-byte little-endian SRID prefix and ISO WKB contract. Geography retains its non-negative SRID requirement. The SQL payload uses ISO WKB without embedded SRIDs. The JVM preserves the WKB byte order and coordinate bytes of lazy geography values while normalizing their headers to ISO types; computed S2 values use the public S2 WKB writer. Python uses public Shapely WKB. This changes SQL transport only: S2 spherical computation, lazy/eager shape-index behavior and the Python `Geography` wrapper are preserved.

Geometry and geography UDT payloads have the same framing, but their type metadata and computation remain distinct. They are also distinct from Spark 4.2 native spatial values, which use Spark's default serializer and native CRS validation.

## Migrating persisted UDT values

An ordinary Parquet file written with the old `GeometryUDT` can contain Sedona's compact serialization bytes under UDT metadata. These bytes are not the new SRID-prefixed ISO WKB payload and are not automatically converted by the new reader. The reader does not guess the stored encoding. Export such data with the old Sedona version before upgrading. For example:

```python
# Run with the Sedona version that wrote the original UDT data.
old_df = sedona.read.parquet("old-udt-data")
old_df.selectExpr("id", "ST_AsEWKB(geom) AS geom_wkb").write.parquet(
"portable-wkb-data"
)
```

Then load the portable binary column with the new version:

```python
portable_df = sedona.read.parquet("portable-wkb-data")
new_df = portable_df.selectExpr("id", "ST_GeomFromWKB(geom_wkb) AS geom")
```

Include the remaining non-geometry columns in the projection as appropriate. Check row counts, nulls, SRIDs and coordinate dimensions after migrating. Standard GeoParquet and explicit WKB/EWKB columns already use portable geometry encodings and do not need this compact-UDT conversion.

### Geography UDT files

Earlier `GeographyUDT` files contain a **big-endian** SRID prefix followed by WKB. The new SQL reader expects a **little-endian** prefix. Export these files with the version that wrote them before upgrading, even though their WKB coordinate payload may already be valid ISO WKB. There is no automatic format detection: SRID 0 looks identical, SRID 4326 becomes negative when byte-swapped, and SRID 1 can silently become 16777216.

Export explicit EWKB and SRID columns with the old version. Convert to geometry only for this transport operation; the restored column remains geography:

```python
old_df = sedona.read.parquet("old-geography-udt-data")
old_df.selectExpr(
"id",
"ST_AsEWKB(ST_GeogToGeometry(geog)) AS geog_wkb",
"ST_SRID(ST_GeogToGeometry(geog)) AS geog_srid",
).write.parquet("portable-geography-data")
```

On Spark 3.5–4.1, reconstruct geography with the new version and the explicit SRID column:

```python
portable_df = sedona.read.parquet("portable-geography-data")
new_df = portable_df.selectExpr("id", "ST_GeogFromWKB(geog_wkb, geog_srid) AS geog")
```

Include other columns as needed and verify row counts, nulls, SRIDs, coordinate dimensions and representative spherical operations. Spark 4.2 native geography additionally requires a supported native CRS; changing the UDT framing does not relax that validation. Its built-in `ST_GeogFromWKB` takes one argument, so the two-argument reconstruction above is specific to older runtimes. Keep the separate SRID column when planning a native migration: EWKB writers can omit SRID 0, and a native constructor treats an absent CRS as 4326. Use an explicit Sedona UDT schema when retaining values outside the native contract rather than silently assigning a different CRS. Never relabel old geography bytes as new UDT data or infer their prefix byte order from the SRID's value.

## Scope

The RDD/Kryo geometry and geography serializers, spatial-index serializers, Python RDD framing and Flink serialization retain their existing formats. In particular, the common geography serializer used by these paths keeps its big-endian SRID prefix. Only Spark SQL geography callers use the new SQL serializer. Standard GeoParquet and explicit WKB/EWKB columns are unaffected by this UDT framing migration.

Application code should pass Shapely objects through `GeometryType` or use SQL WKB functions at external boundaries. The legacy `geometry_serde` utilities remain available for their existing compact-format contract; their bytes are no longer the SQL geometry payload.
21 changes: 10 additions & 11 deletions python/sedona/spark/sql/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@
import pandas as pd

from sedona.spark.sql.types import GeometryType
from sedona.spark.utils import geometry_serde
from sedona.spark.utils.geometry_sql_serde import (
deserialize_geometry,
serialize_geometry,
)
from pyspark.sql.udf import UserDefinedFunction
from pyspark.sql.types import DataType
from shapely.geometry.base import BaseGeometry
Expand Down Expand Up @@ -93,15 +96,13 @@ def _apply_shapely_series_udf(
def apply(series: pd.Series) -> pd.Series:
applied = series.apply(
lambda x: (
fn(geometry_serde.deserialize(x)[0])
fn(deserialize_geometry(x))
if deserialize_geom and x is not None
else fn(x)
)
)

return applied.apply(
lambda x: geometry_serde.serialize(x) if serialize_geom else x
)
return applied.apply(lambda x: serialize_geometry(x) if serialize_geom else x)

udf = UserDefinedFunction(
apply, return_type, "SedonaPandasArrowUDF", evalType=SEDONA_SCALAR_EVAL_TYPE
Expand All @@ -120,9 +121,7 @@ def apply(series: pd.Series) -> pd.Series:
if deserialize_geom:
series_data = gpd.GeoSeries(
series.apply(
lambda x: (
geometry_serde.deserialize(x)[0] if x is not None else None
)
lambda x: (deserialize_geometry(x) if x is not None else None)
)
)

Expand All @@ -131,7 +130,7 @@ def apply(series: pd.Series) -> pd.Series:
# GeoSeries.apply retains geometry dtype for empty or all-null
# results, which Arrow cannot convert to the binary storage type.
return pd.Series(
[geometry_serde.serialize(geom) for geom in result],
[serialize_geometry(geom) for geom in result],
index=result.index,
dtype=object,
)
Expand All @@ -144,13 +143,13 @@ def apply(series: pd.Series) -> pd.Series:

def deserialize_geometry_if_geom(data):
if isinstance(data, BaseGeometry):
return geometry_serde.deserialize(data)[0]
return deserialize_geometry(data)

return data


def serialize_to_geometry_if_geom(data, return_type: DataType):
if isinstance(return_type, GeometryType):
return geometry_serde.serialize(data)
return serialize_geometry(data)

return data
10 changes: 6 additions & 4 deletions python/sedona/spark/sql/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,10 @@
raster_serde = None
SedonaRaster = None

from sedona.spark.utils import geometry_serde
from sedona.spark.utils.geometry_sql_serde import (
deserialize_geometry,
serialize_geometry,
)
from sedona.spark.core.geom.geography import Geography
from sedona.spark.core.geom.box2d import Box2D
from sedona.spark.core.geom.box3d import Box3D
Expand Down Expand Up @@ -70,11 +73,10 @@ def sqlType(cls):
return BinaryType()

def serialize(self, obj):
return geometry_serde.serialize(obj)
return serialize_geometry(obj)

def deserialize(self, datum):
geom, offset = geometry_serde.deserialize(datum)
return geom
return deserialize_geometry(datum)

@classmethod
def module(cls):
Expand Down
39 changes: 9 additions & 30 deletions python/sedona/spark/utils/geography_sql_serde.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,52 +15,31 @@
# specific language governing permissions and limitations
# under the License.

"""Python transport for the existing JVM geography UDT: big-endian SRID and WKB."""
"""SQL geography transport: little-endian signed SRID followed by ISO WKB."""

import struct

from sedona.spark.core.geom.geography import Geography
from sedona.spark.utils import geometry_wkb

_SRID_FLAG = 0x20000000
from sedona.spark.utils import geometry_sql_serde


def serialize_geography(geography):
"""Encode a geography without changing the JVM geography or RDD formats."""
"""Encode SQL geography while preserving its non-negative SRID requirement."""
if geography is None:
return None
payload = geometry_wkb.dumps(geography.geometry)
geometry_type = struct.unpack_from("<I", payload, 1)[0]
srid = 0
if geometry_type & _SRID_FLAG:
srid = struct.unpack_from("<i", payload, 5)[0]
payload = struct.pack("<BI", 1, geometry_type & ~_SRID_FLAG) + payload[9:]
if srid < 0:
payload = geometry_sql_serde.serialize_geometry(geography.geometry)
if struct.unpack_from("<i", payload)[0] < 0:
raise ValueError("Geography SRID must be non-negative")
return struct.pack(">i", srid) + payload
return payload


def deserialize_geography(value):
"""Decode the JVM's SRID prefix using Shapely's public EWKB reader."""
"""Decode SQL geography with the outer SRID as the authoritative value."""
if value is None:
return None
value = bytes(value)
if len(value) < 9:
raise ValueError("Geography payload must contain a four-byte SRID and WKB")
srid = struct.unpack_from(">i", value)[0]
if srid < 0:
if struct.unpack_from("<i", value)[0] < 0:
raise ValueError("Geography SRID must be non-negative")
payload = value[4:]
if payload[0] not in (0, 1):
raise ValueError("Invalid geography WKB byte order")
endian = "<" if payload[0] == 1 else ">"
geometry_type = struct.unpack_from(endian + "I", payload, 1)[0]
offset = 9 if geometry_type & _SRID_FLAG else 5
# The outer SRID is authoritative. Embedding it in EWKB lets both Shapely
# 1.x and 2.x retain it without direct access to GEOS pointers.
ewkb = (
payload[:1]
+ struct.pack(endian + "Ii", geometry_type | _SRID_FLAG, srid)
+ payload[offset:]
)
return Geography(geometry_wkb.loads(ewkb))
return Geography(geometry_sql_serde.deserialize_geometry(value))
123 changes: 123 additions & 0 deletions python/sedona/spark/utils/geometry_sql_serde.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
# 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.

"""SQL geometry transport: little-endian signed SRID followed by ISO WKB."""

import struct

import shapely

from sedona.spark.utils import geometry_wkb


def serialize_geometry(geometry):
"""Encode a SQL geometry, retaining its SRID and supported coordinate dimensions."""
if geometry is None:
return None
srid = geometry_wkb._get_srid(geometry)
if hasattr(shapely, "to_wkb") and geometry_wkb.geos_version >= (3, 10, 0):
payload = shapely.to_wkb(
geometry,
byte_order=1,
include_srid=False,
flavor="iso",
output_dimension=(
4
if hasattr(shapely, "has_m") and shapely.geos_version >= (3, 12, 0)
else 3
),
)
else:
# Keep the shared writer's older-GEOS empty and Shapely 1.x type fixes.
# Only WKB headers are adapted; ordinates remain the public writer's bytes.
payload = _iso_headers(geometry_wkb.dumps(geometry))
return struct.pack("<i", srid) + payload


def deserialize_geometry(value):
"""Decode the SRID-prefixed WKB without retaining a mutable input buffer."""
if value is None:
return None
value = bytes(value)
if len(value) < 9:
raise ValueError("Geometry payload must contain a four-byte SRID and WKB")
srid = struct.unpack_from("<i", value)[0]
payload = value[4:]
if payload[0] not in (0, 1):
raise ValueError("Invalid geometry WKB byte order")
endian = "<" if payload[0] == 1 else ">"
geometry_type = struct.unpack_from(endian + "I", payload, 1)[0]
# The public EWKB reader restores SRID on Shapely 1.x as well as 2.x.
# Convert the root ISO type offset to EWKB flags before adding its SRID.
plain = geometry_type & 0x1FFFFFFF
layout, base = divmod(plain, 1000)
if layout > 3 or not 1 <= base <= 7:
raise ValueError("Invalid geometry WKB type")
flags = geometry_type & 0xC0000000
if layout in (1, 3):
flags |= 0x80000000
if layout in (2, 3):
flags |= 0x40000000
offset = 9 if geometry_type & 0x20000000 else 5
ewkb = (
payload[:1]
+ struct.pack(endian + "Ii", base | flags | 0x20000000, srid)
+ payload[offset:]
)
return geometry_wkb.loads(ewkb)


def _iso_headers(source):
"""Adapt the legacy public writer's little-endian EWKB headers to ISO WKB."""
result = bytearray()
position = 0
pending = 1

def copy(size):
nonlocal position
end = position + size
if end > len(source):
raise ValueError("Invalid geometry WKB framing")
result.extend(source[position:end])
position = end

def count():
value = struct.unpack_from("<I", source, position)[0]
copy(4)
return value

while pending:
pending -= 1
geometry_type = struct.unpack_from("<I", source, position + 1)[0]
base = geometry_type & 0x1FFFFFFF
has_z = bool(geometry_type & 0x80000000)
has_m = bool(geometry_type & 0x40000000)
dimensions = 2 + has_z + has_m
position += 9 if geometry_type & 0x20000000 else 5
result.extend(struct.pack("<BI", 1, base + 1000 * has_z + 2000 * has_m))
if base == 1:
copy(dimensions * 8)
elif base == 2:
copy(count() * dimensions * 8)
elif base == 3:
for _ in range(count()):
copy(count() * dimensions * 8)
elif 4 <= base <= 7:
pending += count()
else:
raise ValueError("Invalid geometry WKB type")
return bytes(result)
8 changes: 7 additions & 1 deletion python/tests/geopandas/test_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import pyspark.pandas as ps
import pytest
from geopandas.testing import assert_geoseries_equal
from shapely import wkt

import sedona.spark.geopandas as sgpd
from sedona.spark.geopandas import GeoSeries
Expand Down Expand Up @@ -172,8 +173,13 @@ def test_points_from_xy_null_is_nan_coordinate_not_missing_geometry(self):
gpd.points_from_xy([None, 3.0, None], [2.0, None, None]),
index=pd.Index([0, 1, 2], name="id"),
)
# Standard WKB represents a point with two NaN coordinates as empty.
# A single NaN coordinate remains a nonempty geometry, not a missing value.
expected.iloc[2] = wkt.loads("POINT EMPTY")
actual = result.to_geopandas()
assert actual.is_empty.tolist() == [False, False, True]
_assert_geoseries_equal_with_nan_xy(
result.to_geopandas(),
actual,
expected,
np.ones(len(expected), dtype=bool),
)
Expand Down
Loading
Loading