Skip to content
4 changes: 3 additions & 1 deletion docs/tutorial/files/geoparquet-sedona-spark.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ Sedona writes the Z dimension with the type codes of ISO WKB, which the GeoParqu

Each member of a geometry collection keeps its own coordinate layout. A collection with both XY and XYZ members is stored with the type codes of both, for example 1007 for the collection, 2 for an XY `LineString` member and 1001 for a `Point Z` member. ISO WKB requires every member of a collection with a Z coordinate to have one as well, so a reader may reject such a geometry. Spark's native geometry type does: on Spark 4.2 and later, Sedona fails to read it into a native geometry column with `WKB_PARSE_ERROR`.

[GeoParquet 1.1](https://geoparquet.org/releases/v1.1.0/#wkb) does not support M coordinates. Sedona discards M when writing GeoParquet: XYM becomes XY, and XYZM becomes XYZ. If you need the M values, store them separately before writing.
[GeoParquet 1.1](https://geoparquet.org/releases/v1.1.0/#wkb) does not support M coordinates. Sedona discards M when writing GeoParquet 1.1: XYM becomes XY, and XYZM becomes XYZ. If you need the M values, store them separately before writing, or write GeoParquet 2.0, which keeps them. See the section on writing GeoParquet 2.0 below.

## Read GeoParquet files into Sedona DataFrame with Spark

Expand Down Expand Up @@ -295,6 +295,8 @@ A GeoParquet 2.0 file differs from a GeoParquet 1.1 file in these ways:

* The geometry column carries the `GEOMETRY` logical type, and the CRS is a property of that type. The GeoParquet metadata repeats the CRS as PROJJSON.
* Each row group has geospatial statistics, a bounding box and the geometry types, which the Parquet library writes. Sedona therefore adds no covering column by default. `geoparquet.covering` and `geoparquet.covering.<column_name>` still declare a covering column that you provide.
* M coordinates are kept: XYM and XYZM geometries are stored as they are. The `geometry_types` of the GeoParquet metadata name the layout, for example `Point M` or `LineString ZM`.
* The `bbox` of the GeoParquet metadata also states the bounds of the Z and M coordinates. A column with Z coordinates has six values, `[xmin, ymin, zmin, xmax, ymax, zmax]`, and a column with Z and M coordinates has eight, `[xmin, ymin, zmin, mmin, xmax, ymax, zmax, mmax]`. A column with M and without Z coordinates has the X and Y bounds only, because GeoParquet has no `bbox` with M bounds and without Z bounds. A Z or M coordinate that is NaN is skipped, and a dimension whose coordinates are all NaN counts as absent, so the array can be shorter than the coordinates of the geometries suggest. Sedona writes no `bbox` for a column when one of the bounds it would list is infinite or NaN, because JSON has no number for such a value. A GeoParquet 1.1 file keeps the four values of the X and Y bounds.

Sedona writes the `crs` property of the column in the shortest form that identifies the CRS:

Expand Down
4 changes: 3 additions & 1 deletion docs/tutorial/files/geoparquet-sedona-spark.zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ Sedona 按 GeoParquet 规范的要求,用 ISO WKB 的类型代码写出 Z 维

几何集合的每个成员保留各自的坐标布局。同时包含 XY 和 XYZ 成员的集合会按两种类型代码存储,例如集合为 1007,XY 的 `LineString` 成员为 2,`Point Z` 成员为 1001。ISO WKB 要求带 Z 坐标的集合中每个成员也带 Z 坐标,因此读取方可能拒绝这样的几何对象。Spark 原生几何类型就是如此:在 Spark 4.2 及更高版本上,Sedona 将其读入原生几何列时会失败并报 `WKB_PARSE_ERROR`。

[GeoParquet 1.1](https://geoparquet.org/releases/v1.1.0/#wkb) 不支持 M 坐标。Sedona 在写出 GeoParquet 时会丢弃 M:XYM 转换为 XY,XYZM 转换为 XYZ。如果需要保留 M 值,请在写出前将其单独存储。
[GeoParquet 1.1](https://geoparquet.org/releases/v1.1.0/#wkb) 不支持 M 坐标。Sedona 在写出 GeoParquet 1.1 时会丢弃 M:XYM 转换为 XY,XYZM 转换为 XYZ。如果需要保留 M 值,请在写出前将其单独存储,或者写出 GeoParquet 2.0,它会保留 M 坐标。详见下文写出 GeoParquet 2.0 一节。

## 使用 Spark 将 GeoParquet 读入 Sedona DataFrame

Expand Down Expand Up @@ -290,6 +290,8 @@ GeoParquet 2.0 文件与 GeoParquet 1.1 文件有以下区别:

* 几何列带有 `GEOMETRY` 逻辑类型,CRS 是该类型的一个属性。GeoParquet 元数据会以 PROJJSON 重复给出 CRS。
* 每个行组都带有地理空间统计信息,即边界框和几何类型,由 Parquet 库写出。因此 Sedona 默认不再添加 covering 列。`geoparquet.covering` 和 `geoparquet.covering.<column_name>` 仍可声明由你提供的 covering 列。
* M 坐标会被保留:XYM 和 XYZM 几何对象按原样存储。GeoParquet 元数据中的 `geometry_types` 会标明坐标布局,例如 `Point M` 或 `LineString ZM`。
* GeoParquet 元数据中的 `bbox` 还会给出 Z 和 M 坐标的范围。含 Z 坐标的列有六个值 `[xmin, ymin, zmin, xmax, ymax, zmax]`,同时含 Z 和 M 坐标的列有八个值 `[xmin, ymin, zmin, mmin, xmax, ymax, zmax, mmax]`。只含 M 而不含 Z 坐标的列只给出 X 和 Y 的范围,因为 GeoParquet 的 `bbox` 无法在没有 Z 范围时表示 M 范围。为 NaN 的 Z 或 M 坐标不计入范围;如果某一维的坐标全部为 NaN,则视为该列没有这一维,因此数组可能比几何的坐标维度所对应的更短。如果要写出的某个范围值为无穷大或 NaN,Sedona 不会为该列写出 `bbox`,因为 JSON 无法用数字表示这样的值。GeoParquet 1.1 文件仍只写出 X 和 Y 范围的四个值。

Sedona 会用能够标识 CRS 的最短形式写出列的 `crs` 属性:

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,43 @@ object SpatialTypeSupport {
}
def readGeometry(row: SpecializedGetters, ordinal: Int, dataType: DataType): Geometry =
if (row.isNullAt(ordinal)) null else deserializeGeometry(row.get(ordinal, dataType), dataType)

/**
* The geometry that [[readGeometry]] returns and, for a native geometry value, the ISO WKB that
* the value holds, None for a value of Sedona's own geometry type. The geometry is read from
* that WKB, so a native value is converted to WKB once. A native value keeps the Z and M
* dimensions that an empty multi-geometry or collection declares. A JTS geometry has no
* coordinates to keep them in, so they are lost when such a value is written from the geometry.
*/
def readGeometryWithWkb(
row: SpecializedGetters,
ordinal: Int,
dataType: DataType,
order: ByteOrder): (Geometry, Option[Array[Byte]]) = dataType match {
case nativeType: GeometryType if !row.isNullAt(ordinal) =>
val native = NativeGeometry.fromValue(row.get(ordinal, dataType).asInstanceOf[BinaryView])
val wkb = native.toWkb(order)
val result = WKBReader.forDeclaredDimensions(native.srid()).read(wkb)
nativeType.assertSridAllowedForType(result.getSRID)
(result, Some(wkb))
case _ => (readGeometry(row, ordinal, dataType), None)
}

/**
* A native geometry value that holds `wkb` as it is. None when `dataType` is Sedona's own
* geometry type, and when Spark does not take the WKB as it is: a line of one point or a ring
* that is not closed, for example, which the WKB reader completes. The caller then builds the
* value from a JTS geometry. The value keeps what a JTS geometry would lose, as
* [[readGeometryWithWkb]] describes.
*/
def nativeGeometryFromWkb(wkb: Array[Byte], srid: Int, dataType: DataType): Option[Any] =
dataType match {
case native: GeometryType =>
native.assertSridAllowedForType(srid)
try Some(NativeGeometry.fromWkb(PublicWkbHeaderAdapter.toIsoWkb(wkb), srid).getValue)
catch { case _: IllegalArgumentException => None }
case _ => None
}
def externalGeometry(value: Geometry): Any = externalGeometry(value, geometryType)
def externalGeometry(value: Geometry, dataType: DataType): Any = dataType match {
case _: GeometryUDT => value
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
*/
package org.apache.spark.sql.sedona_sql.types

import java.nio.ByteOrder

import org.apache.sedona.common.S2Geography.Geography
import org.apache.sedona.common.geography.Constructors
import org.apache.spark.sql.catalyst.analysis.FunctionRegistry.FunctionBuilder
Expand Down Expand Up @@ -51,6 +53,20 @@ object SpatialTypeSupport {
if (value == null) null else GeographyUDT.deserialize(value)
def readGeometry(row: SpecializedGetters, ordinal: Int, dataType: DataType): Geometry =
if (row.isNullAt(ordinal)) null else deserializeGeometry(row.get(ordinal, dataType), dataType)

/**
* The geometry that [[readGeometry]] returns and the WKB of a native Spark geometry value.
* Sedona uses no native values before Spark 4.2, so there is no WKB.
*/
def readGeometryWithWkb(
row: SpecializedGetters,
ordinal: Int,
dataType: DataType,
order: ByteOrder): (Geometry, Option[Array[Byte]]) =
(readGeometry(row, ordinal, dataType), None)

/** A native Spark geometry value that holds `wkb`. Sedona uses none before Spark 4.2. */
def nativeGeometryFromWkb(wkb: Array[Byte], srid: Int, dataType: DataType): Option[Any] = None
def externalGeometry(value: Geometry): Any = value
def externalGeometry(value: Geometry, dataType: DataType): Any = value
def fromExternalGeometry(value: Any): Geometry = value.asInstanceOf[Geometry]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -226,9 +226,18 @@ private[geoparquet] class GeoParquetRowConverter(
if (parquetType.isPrimitive) {
new ParquetPrimitiveConverter(updater) {
override def addBinary(value: Binary): Unit = {
val geom = WKBReader.forDeclaredDimensions().read(value.getBytes)
geom.setSRID(srid)
this.updater.set(SpatialTypeSupport.serializeGeometry(geom, catalystType))
val wkb = value.getBytes
// A native geometry value takes the stored WKB as it is. A JTS geometry in
// between would lose the Z and M dimensions that an empty multi-geometry or
// collection declares. Spark does not take all WKB as it is: a line of one
// point, for example, is read into a JTS geometry, which completes it.
val geometry =
SpatialTypeSupport.nativeGeometryFromWkb(wkb, srid, catalystType).getOrElse {
val geom = WKBReader.forDeclaredDimensions().read(wkb)
geom.setSRID(srid)
SpatialTypeSupport.serializeGeometry(geom, catalystType)
}
this.updater.set(geometry)
}
}
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
import org.apache.spark.sql.types._
import org.json4s.JValue
import org.json4s.jackson.JsonMethods.parse
import org.locationtech.jts.geom.Geometry
import org.locationtech.jts.geom.{CoordinateSequence, Geometry, LineString, Point, Polygon}
import org.locationtech.jts.io.ByteOrderValues
import org.datasyslab.jts.io.WKBWriter

Expand All @@ -48,7 +48,7 @@
import scala.collection.JavaConverters._
import scala.collection.mutable

/**

Check warning on line 51 in spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeoParquetWriteSupport.scala

View workflow job for this annotation

GitHub Actions / build

Could not find any member to link for "InternalRow".

Check warning on line 51 in spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeoParquetWriteSupport.scala

View workflow job for this annotation

GitHub Actions / build

Could not find any member to link for "WriteSupport".
* A Parquet [[WriteSupport]] implementation that writes Catalyst [[InternalRow]]s as Parquet
* messages. This class can write Parquet data in two modes:
*
Expand Down Expand Up @@ -277,14 +277,11 @@
val geometryTypes = columnInfo.seenGeometryTypes.toSeq
// Empty geometries still contribute geometry_types but have no spatial extent.
// Omit bbox when the file contains only empty/null geometries or no rows.
val bbox = if (!columnInfo.bbox.isEmpty) {
Some(
Seq(
columnInfo.bbox.minX,
columnInfo.bbox.minY,
columnInfo.bbox.maxX,
columnInfo.bbox.maxY))
} else None
// Omit it too when a bound is infinite or NaN. JSON has no number for such a bound, and
// a bbox states the range of every dimension that it covers.
val bbox =
if (columnInfo.bbox.isEmpty) None
else Some(columnInfo.bbox.bounds).filter(_.forall(b => !b.isNaN && !b.isInfinity))
lazy val legacyCrs = geoParquetColumnCrsMap.getOrElse(
columnName, {
if (!userExplicitlySetDefaultCrs) {
Expand Down Expand Up @@ -540,28 +537,48 @@
val byteOrder = if (ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN) {
ByteOrderValues.BIG_ENDIAN
} else ByteOrderValues.LITTLE_ENDIAN
// Preserve declared Z even for empty geometries, but keep GeoParquet output limited
// to XY/XYZ: the configured XYZ ordinates continue to exclude M.
val wkbWriter = new WKBWriter(3, byteOrder, false)
// Preserve declared dimensions even for empty geometries. GeoParquet 1.1 has no M
// coordinate, so a 1.x file keeps X, Y and Z. GeoParquet 2.0 has all four.
val geospatialTypes = writesGeospatialTypes
val wkbWriter = new WKBWriter(if (geospatialTypes) 4 else 3, byteOrder, false)
wkbWriter.setPreserveCoordinateDimensions(true)
(row: SpecializedGetters, ordinal: Int) => {
val geom = SpatialTypeSupport.readGeometry(row, ordinal, dataType)
// A native geometry value of a 2.x file is stored as it is. It is ISO WKB of any of
// the four coordinate layouts, and it keeps the layout that an empty multi-geometry
// or collection declares, which geom cannot hold. geom is read from the same WKB, so
// the value is converted once. A 1.x file has no M coordinate, so its geometries are
// written again from geom.
val (geom, heldWkb) =
if (geospatialTypes) {
SpatialTypeSupport.readGeometryWithWkb(
row,
ordinal,
dataType,
ByteOrder.nativeOrder())
} else (SpatialTypeSupport.readGeometry(row, ordinal, dataType), None)
SpatialTypeSupport.geometrySrid(dataType).foreach { expectedSrid =>
GeoParquetNativeCrs.requireSrid(
rootOrdinal.map(schema(_).name).getOrElse("<nested geometry>"),
expectedSrid,
geom.getSRID)
}
val nativeWkb = heldWkb.map(PublicWkbHeaderAdapter.toIsoWkb)
// The writer marks a Z coordinate with the EWKB flag bit. GeoParquet asks for the WKB
// of the OGC and ISO standards, which uses the type codes 1001 to 1007 instead. The
// writer returns a new array without an SRID, so the type words change in that array.
val wkb = PublicWkbHeaderAdapter.toIsoWkbInPlace(wkbWriter.write(geom))
val wkb =
nativeWkb.getOrElse(PublicWkbHeaderAdapter.toIsoWkbInPlace(wkbWriter.write(geom)))
recordConsumer.addBinary(Binary.fromReusedByteArray(wkb))
if (geometryColumnInfo != null) {
// The writer resolves each geometry's actual layout, including collection members.
// Derive metadata from its WKB type code rather than the first coordinate.
// ISO WKB adds 1000 to the type code for Z, 2000 for M and 3000 for both.
val typeCode = ByteBuffer.wrap(wkb, 1, 4).order(ByteOrder.nativeOrder()).getInt
geometryColumnInfo.update(geom, typeCode / 1000 == 1)
val layout = typeCode / 1000
geometryColumnInfo.update(geom, hasZ = layout % 2 == 1, hasM = layout >= 2)
// The bbox of a 2.x file states the Z and M bounds too. A 1.x file keeps the X and
// Y bounds that Sedona has always written for it.
if (geospatialTypes) geometryColumnInfo.bbox.updateZAndM(geom)
}
}

Expand Down Expand Up @@ -866,10 +883,12 @@
else Some(_srid)
}

def update(geom: Geometry, hasZ: Boolean): Unit = {
def update(geom: Geometry, hasZ: Boolean, hasM: Boolean): Unit = {
bbox.update(geom)
// Match the dimensionality encoded in WKB, including typed empty geometries.
val geometryType = if (!hasZ) geom.getGeometryType else geom.getGeometryType + " Z"
val layout = (if (hasZ) "Z" else "") + (if (hasM) "M" else "")
val geometryType =
if (layout.isEmpty) geom.getGeometryType else geom.getGeometryType + " " + layout
seenGeometryTypes.add(geometryType)

// Track SRID consistency across all geometries in this column
Expand All @@ -889,6 +908,11 @@
var minY: Double = Double.PositiveInfinity,
var maxX: Double = Double.NegativeInfinity,
var maxY: Double = Double.NegativeInfinity) {
private var minZ = Double.PositiveInfinity
private var maxZ = Double.NegativeInfinity
private var minM = Double.PositiveInfinity
private var maxM = Double.NegativeInfinity

def isEmpty: Boolean = minX > maxX || minY > maxY

def update(geom: Geometry): Unit = {
Expand All @@ -900,6 +924,67 @@
maxY = math.max(maxY, env.getMaxY)
}
}

/**
* Takes the Z and M coordinates of `geom` into the bounds. A coordinate that is NaN is not a
* bound, as in the bounding box of the Parquet statistics.
*/
def updateZAndM(geom: Geometry): Unit = geom match {
case point: Point => updateZAndM(point.getCoordinateSequence)
case line: LineString => updateZAndM(line.getCoordinateSequence)
case polygon: Polygon =>
updateZAndM(polygon.getExteriorRing.getCoordinateSequence)
var i = 0
while (i < polygon.getNumInteriorRing) {
updateZAndM(polygon.getInteriorRingN(i).getCoordinateSequence)
i += 1
}
case _ =>
var i = 0
while (i < geom.getNumGeometries) {
updateZAndM(geom.getGeometryN(i))
i += 1
}
}

private def updateZAndM(coordinates: CoordinateSequence): Unit = {
val hasZ = coordinates.hasZ
val hasM = coordinates.hasM
if (hasZ || hasM) {
var i = 0
while (i < coordinates.size) {
if (hasZ) {
val z = coordinates.getZ(i)
if (!z.isNaN) {
minZ = math.min(minZ, z)
maxZ = math.max(maxZ, z)
}
}
if (hasM) {
val m = coordinates.getM(i)
if (!m.isNaN) {
minM = math.min(minM, m)
maxM = math.max(maxM, m)
}
}
i += 1
}
}
}

/**
* The bbox of the column metadata: the lower bound of every dimension and then the upper
* bound of every dimension. X and Y come first, then Z, then M. A dimension without a
* coordinate that is a number has no bounds and is left out. GeoParquet has no bbox with M
* bounds and without Z bounds, so the M bounds are stated only next to the Z bounds.
*/
def bounds: Seq[Double] = {
val hasZ = minZ <= maxZ
val hasM = minM <= maxM
if (hasZ && hasM) Seq(minX, minY, minZ, minM, maxX, maxY, maxZ, maxM)
else if (hasZ) Seq(minX, minY, minZ, maxX, maxY, maxZ)
else Seq(minX, minY, maxX, maxY)
}
}

/**
Expand Down
Loading
Loading