diff --git a/docs/tutorial/files/geoparquet-sedona-spark.md b/docs/tutorial/files/geoparquet-sedona-spark.md index 2f25dc7e53f..52a568ca380 100644 --- a/docs/tutorial/files/geoparquet-sedona-spark.md +++ b/docs/tutorial/files/geoparquet-sedona-spark.md @@ -69,6 +69,10 @@ Sedona writes many Parquet files in parallel because that's much faster than wri GeoParquet writes preserve the declared XY or XYZ coordinate layout of empty `Point`, `LineString`, and `Polygon` geometries. XYZ geometries also retain their Z dimension when Z ordinates are `NaN`. +Sedona writes the Z dimension with the type codes of ISO WKB, which the GeoParquet specification asks for: a geometry with a Z coordinate has a type code from 1001 to 1007, for example 1001 for `Point Z`. Before Sedona 2.0.0 the writer marked Z with the EWKB flag bit instead (`0x80000001` for `Point Z`). Sedona reads both forms. + +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. ## Read GeoParquet files into Sedona DataFrame with Spark diff --git a/docs/tutorial/files/geoparquet-sedona-spark.zh.md b/docs/tutorial/files/geoparquet-sedona-spark.zh.md index 209d4d4f504..42fbb825bfb 100644 --- a/docs/tutorial/files/geoparquet-sedona-spark.zh.md +++ b/docs/tutorial/files/geoparquet-sedona-spark.zh.md @@ -69,6 +69,10 @@ Sedona 会并行写出多个 Parquet 文件,比写单一文件快得多。 写出 GeoParquet 时,Sedona 会保留空 `Point`、`LineString` 和 `Polygon` 几何对象声明的 XY 或 XYZ 坐标布局。即使 Z 坐标值为 `NaN`,XYZ 几何对象也会保留 Z 维度。 +Sedona 按 GeoParquet 规范的要求,用 ISO WKB 的类型代码写出 Z 维度:带 Z 坐标的几何对象使用 1001 到 1007 的类型代码,例如 `Point Z` 为 1001。Sedona 2.0.0 之前的写出方式是用 EWKB 标志位标记 Z(`Point Z` 为 `0x80000001`)。两种形式 Sedona 都能读取。 + +几何集合的每个成员保留各自的坐标布局。同时包含 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 值,请在写出前将其单独存储。 ## 使用 Spark 将 GeoParquet 读入 Sedona DataFrame diff --git a/spark/common/src/main/java/org/apache/spark/sql/sedona_sql/types/PublicWkbHeaderAdapter.java b/spark/common/src/main/java/org/apache/spark/sql/sedona_sql/types/PublicWkbHeaderAdapter.java index f68bb7aa936..b602b2e98f0 100644 --- a/spark/common/src/main/java/org/apache/spark/sql/sedona_sql/types/PublicWkbHeaderAdapter.java +++ b/spark/common/src/main/java/org/apache/spark/sql/sedona_sql/types/PublicWkbHeaderAdapter.java @@ -25,22 +25,43 @@ /** Converts public WKB headers to ISO types without changing coordinate bytes. */ public final class PublicWkbHeaderAdapter { public static byte[] toIsoWkb(byte[] source) { - Cursor sizing = new Cursor(source, null); + return convert(source, false); + } + + /** + * Like {@link #toIsoWkb}, for a caller that owns {@code source} and no longer needs its original + * bytes: the ISO type words are written into {@code source} itself, so a geometry with a Z or M + * coordinate needs no second array. WKB with an embedded SRID is shorter in ISO form; it is left + * as it is and the result is a new array. + */ + public static byte[] toIsoWkbInPlace(byte[] source) { + return convert(source, true); + } + + private static byte[] convert(byte[] source, boolean reuseSource) { + Cursor sizing = new Cursor(source, null, false); int length = sizing.walk(); if (!sizing.changed) return source; + if (reuseSource && length == source.length) { + new Cursor(source, null, true).walk(); + return source; + } byte[] result = new byte[length]; - new Cursor(source, result).walk(); + new Cursor(source, result, false).walk(); return result; } private static final class Cursor { final byte[] source; final ByteBuffer input, output; + // Whether the ISO type words are written into the source, which then has no embedded SRID + final boolean patchSource; int outputSize; boolean changed; - Cursor(byte[] source, byte[] target) { + Cursor(byte[] source, byte[] target, boolean patchSource) { this.source = source; + this.patchSource = patchSource; input = ByteBuffer.wrap(source); output = target == null ? null : ByteBuffer.wrap(target); } @@ -82,6 +103,7 @@ int walk() { int dimensions = 2 + (z ? 1 : 0) + (m ? 1 : 0); if ((code & 0x20000000) != 0) input.getInt(); // Caller supplies the SRID separately. changed |= code != iso; + if (patchSource && code != iso) input.putInt(input.position() - Integer.BYTES, iso); if (output != null) output.order(order).put(endian).putInt(iso); outputSize += 5; switch (base) { diff --git a/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeoParquetWriteSupport.scala b/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeoParquetWriteSupport.scala index 95a54049143..c46cbc172a9 100644 --- a/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeoParquetWriteSupport.scala +++ b/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeoParquetWriteSupport.scala @@ -32,7 +32,7 @@ import org.apache.spark.sql.catalyst.util.DateTimeUtils import org.apache.spark.sql.execution.datasources.geoparquet.GeoParquetMetaData.{GEOPARQUET_COVERING_KEY, GEOPARQUET_COVERING_MODE_AUTO, GEOPARQUET_COVERING_MODE_KEY, GEOPARQUET_COVERING_MODE_LEGACY, GEOPARQUET_CRS_KEY, GEOPARQUET_VERSION_KEY, VERSION, createCoveringColumnMetadata} import org.apache.spark.sql.execution.datasources.geoparquet.GeoParquetWriteSupport.GeometryColumnInfo import org.apache.spark.sql.execution.datasources.geoparquet.internal.{DataSourceUtils, LegacyBehaviorPolicy, PortableSQLConf} -import org.apache.spark.sql.sedona_sql.types.SpatialTypeSupport +import org.apache.spark.sql.sedona_sql.types.{PublicWkbHeaderAdapter, SpatialTypeSupport} import org.apache.spark.sql.types._ import org.json4s.JValue import org.json4s.jackson.JsonMethods.parse @@ -510,13 +510,16 @@ class GeoParquetWriteSupport extends WriteSupport[InternalRow] with Logging { expectedSrid, geom.getSRID) } - val wkb = wkbWriter.write(geom) + // 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)) recordConsumer.addBinary(Binary.fromReusedByteArray(wkb)) if (geometryColumnInfo != null) { // The writer resolves each geometry's actual layout, including collection members. - // Derive metadata from its EWKB type header rather than the first coordinate. + // Derive metadata from its WKB type code rather than the first coordinate. val typeCode = ByteBuffer.wrap(wkb, 1, 4).order(ByteOrder.nativeOrder()).getInt - geometryColumnInfo.update(geom, (typeCode & 0x80000000) != 0) + geometryColumnInfo.update(geom, typeCode / 1000 == 1) } } diff --git a/spark/common/src/test/scala/org/apache/sedona/sql/GeoParquetDimensionsSuite.scala b/spark/common/src/test/scala/org/apache/sedona/sql/GeoParquetDimensionsSuite.scala index edc00e39363..d1172849ead 100644 --- a/spark/common/src/test/scala/org/apache/sedona/sql/GeoParquetDimensionsSuite.scala +++ b/spark/common/src/test/scala/org/apache/sedona/sql/GeoParquetDimensionsSuite.scala @@ -29,15 +29,15 @@ import org.apache.commons.io.FileUtils import org.apache.hadoop.conf.Configuration import org.apache.hadoop.fs.Path import org.apache.parquet.example.data.simple.SimpleGroupFactory -import org.apache.parquet.hadoop.ParquetFileReader +import org.apache.parquet.hadoop.{ParquetFileReader, ParquetReader} import org.apache.parquet.hadoop.util.HadoopInputFile import org.apache.parquet.column.Encoding -import org.apache.parquet.hadoop.example.ExampleParquetWriter +import org.apache.parquet.hadoop.example.{ExampleParquetWriter, GroupReadSupport} import org.apache.parquet.io.api.Binary import org.apache.parquet.schema.MessageTypeParser import org.apache.sedona.common.utils.GeometryEquality import org.apache.spark.sql.{DataFrame, Row} -import org.apache.spark.sql.types.{BinaryType, IntegerType, StructField, StructType} +import org.apache.spark.sql.types.{ArrayType, BinaryType, IntegerType, StructField, StructType} import org.json4s.{DefaultFormats, JNothing, JValue} import org.json4s.jackson.parseJson import org.apache.spark.sql.sedona_sql.UDT.GeometryUDT @@ -235,6 +235,13 @@ class GeoParquetDimensionsSuite extends TestBaseScala { (kind & 0x80000000) != 0 || ((kind & 0x0fffffff) / 1000) % 2 == 1 } + private def typeCode(wkb: Array[Byte]): Int = { + val order = if (wkb(0) == 0) ByteOrder.BIG_ENDIAN else ByteOrder.LITTLE_ENDIAN + ByteBuffer.wrap(wkb).order(order).getInt(1) + } + + private def hex(wkb: Array[Byte]): String = org.locationtech.jts.io.WKBWriter.toHex(wkb) + private def columnMetadata(file: File): JValue = { val reader = ParquetFileReader.open(HadoopInputFile.fromPath(new Path(file.toURI), new Configuration())) @@ -257,6 +264,7 @@ class GeoParquetDimensionsSuite extends TestBaseScala { else { val bytes = row.getAs[Array[Byte]](1) assert(hasZ(bytes) == hasZ(sample.wkb), "top-level WKB Z header changed") + assert(typeCode(bytes) == typeCode(sample.wkb), "top-level type code is not ISO WKB") assert( GeometryEquality.equalsIdentical( WKBReader.forDeclaredDimensions().read(bytes), @@ -398,5 +406,118 @@ class GeoParquetDimensionsSuite extends TestBaseScala { withDirectory(directory => writeAndRoundTrip(directory, allEmpty, legacyUdt)) } } + + // GeoParquet asks for the WKB of the OGC and ISO standards, where a geometry with Z has a + // type code from 1001 to 1007. EWKB sets a flag bit in the type code instead. + val order = ByteOrder.nativeOrder() + val pointZ = isoWkb(1, true, Seq(1, 2, 3), order = order) + val lineStringZ = isoWkb(2, true, Seq(1, 2, 3, 4, 5, 6), order = order) + val isoSamples = Seq( + Sample("point", isoWkb(1, false, Seq(1, 2), order = order)), + Sample("point-z", pointZ), + Sample("line-z", lineStringZ), + Sample("multipoint-z", isoWkb(4, true, children = Seq(pointZ), order = order)), + Sample("collection-z", isoWkb(7, true, children = Seq(pointZ, lineStringZ), order = order))) + + it("stores geometries as ISO WKB") { + withDirectory { directory => + val path = new File(directory, "iso").getPath + val rows = isoSamples.zipWithIndex.map { case (sample, index) => Row(index, sample.wkb) } + val schema = StructType( + Seq( + StructField("id", IntegerType, nullable = false), + StructField("wkb", BinaryType, nullable = false))) + sparkSession + .createDataFrame(rows.asJava, schema) + .selectExpr("id", "ST_GeomFromWKB(wkb) AS geometry") + .coalesce(1) + .write + .format("geoparquet") + .save(path) + val stored = sparkSession.read.parquet(path).collect().sortBy(_.getInt(0)) + assert(stored.length == isoSamples.size) + stored.zip(isoSamples).foreach { case (row, sample) => + withClue(s"${sample.name}: ") { + assert(hex(row.getAs[Array[Byte]](1)) == hex(sample.wkb)) + } + } + } + } + + it("stores geometries nested in another column as ISO WKB") { + withDirectory { directory => + val path = new File(directory, "nested").getPath + // Spark's native geometry type is only written at the root of the schema, so the nested + // columns hold GeometryUDT values on every Spark version. + val geometry = WKBReader.forDeclaredDimensions().read(pointZ) + val holder = StructType(Seq(StructField("g", GeometryUDT()))) + val schema = StructType( + Seq( + StructField("geometry", GeometryUDT()), + StructField("members", ArrayType(GeometryUDT())), + StructField("holder", holder))) + sparkSession + .createDataFrame(Seq(Row(geometry, Seq(geometry), Row(geometry))).asJava, schema) + .coalesce(1) + .write + .format("geoparquet") + .save(path) + // Read the stored bytes with the Parquet library: Spark's own reader takes the nested + // values for serialized geometries. + val file = new File(path).listFiles().filter(_.getName.endsWith(".parquet")).head + val reader = ParquetReader.builder(new GroupReadSupport(), new Path(file.toURI)).build() + val record = + try reader.read() + finally reader.close() + val member = record.getGroup("members", 0).getGroup("list", 0).getBinary("element", 0) + assert(hex(record.getBinary("geometry", 0).getBytes) == hex(pointZ)) + assert(hex(member.getBytes) == hex(pointZ)) + assert(hex(record.getGroup("holder", 0).getBinary("g", 0).getBytes) == hex(pointZ)) + } + } + + it("keeps the coordinate layout of each member of a geometry collection") { + withDirectory { directory => + // The OGC grammar asks for Z members throughout a collection with a Z coordinate. A + // geometry can hold members of both layouts, and the writer stores each one as it is. + val order = ByteOrder.nativeOrder() + val mixedSamples = Seq( + Sample( + "members", + isoWkb( + 7, + true, + children = Seq( + isoWkb(2, false, Seq(0, 0, 1, 1), order = order), + isoWkb(1, true, Seq(1, 2, 3), order = order)), + order = order)), + Sample( + "empty-members", + isoWkb( + 7, + true, + children = Seq(isoWkb(2, false, order = order), isoWkb(3, true, order = order)), + order = order))) + val schema = StructType(Seq(StructField("geometry", GeometryUDT()))) + mixedSamples.foreach { sample => + val path = new File(directory, sample.name).getPath + val geometry = WKBReader.forDeclaredDimensions().read(sample.wkb) + sparkSession + .createDataFrame(Seq(Row(geometry)).asJava, schema) + .coalesce(1) + .write + .format("geoparquet") + .save(path) + val file = new File(path).listFiles().filter(_.getName.endsWith(".parquet")).head + val reader = ParquetReader.builder(new GroupReadSupport(), new Path(file.toURI)).build() + val record = + try reader.read() + finally reader.close() + withClue(s"${sample.name}: ") { + assert(hex(record.getBinary("geometry", 0).getBytes) == hex(sample.wkb)) + } + } + } + } } } diff --git a/spark/common/src/test/scala/org/apache/spark/sql/sedona_sql/types/PublicWkbHeaderAdapterSuite.scala b/spark/common/src/test/scala/org/apache/spark/sql/sedona_sql/types/PublicWkbHeaderAdapterSuite.scala new file mode 100644 index 00000000000..c60720a150e --- /dev/null +++ b/spark/common/src/test/scala/org/apache/spark/sql/sedona_sql/types/PublicWkbHeaderAdapterSuite.scala @@ -0,0 +1,125 @@ +/* + * 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.spark.sql.sedona_sql.types + +import java.nio.{ByteBuffer, ByteOrder} +import java.nio.ByteOrder.{BIG_ENDIAN, LITTLE_ENDIAN} + +import org.scalatest.FunSuite + +class PublicWkbHeaderAdapterSuite extends FunSuite { + private val ewkbZ = 0x80000000 + private val ewkbM = 0x40000000 + private val ewkbSrid = 0x20000000 + + private def wkb(order: ByteOrder, size: Int)(fill: ByteBuffer => Unit): Array[Byte] = { + val buffer = ByteBuffer.allocate(5 + size).order(order) + buffer.put(if (order == LITTLE_ENDIAN) 1.toByte else 0.toByte) + fill(buffer) + buffer.array() + } + + private def point(order: ByteOrder, code: Int, ordinates: Double*): Array[Byte] = + wkb(order, ordinates.size * 8) { buffer => + buffer.putInt(code) + ordinates.foreach(buffer.putDouble) + } + + private def line(order: ByteOrder, code: Int, points: Int, ordinates: Double*): Array[Byte] = + wkb(order, 4 + ordinates.size * 8) { buffer => + buffer.putInt(code).putInt(points) + ordinates.foreach(buffer.putDouble) + } + + private def collection(order: ByteOrder, code: Int, members: Array[Byte]*): Array[Byte] = + wkb(order, 4 + members.map(_.length).sum) { buffer => + buffer.putInt(code).putInt(members.size) + members.foreach(buffer.put) + } + + private def typeCode(wkb: Array[Byte], offset: Int = 0): Int = + ByteBuffer + .wrap(wkb) + .order(if (wkb(offset) == 1) LITTLE_ENDIAN else BIG_ENDIAN) + .getInt(offset + 1) + + test("toIsoWkbInPlace writes the ISO type word into the array it was given") { + val source = line(LITTLE_ENDIAN, ewkbZ | 2, 2, 1, 2, 3, 4, 5, 6) + val expected = PublicWkbHeaderAdapter.toIsoWkb(source.clone()) + val result = PublicWkbHeaderAdapter.toIsoWkbInPlace(source) + assert(result eq source) + assert(typeCode(result) == 1002) + assert(result.toSeq == expected.toSeq) + } + + test("toIsoWkbInPlace rewrites the members of a collection in both byte orders") { + val nested = collection( + BIG_ENDIAN, + ewkbZ | 7, + point(LITTLE_ENDIAN, ewkbZ | 1, 1, 2, 3), + line(BIG_ENDIAN, ewkbZ | ewkbM | 2, 1, 1, 2, 3, 4)) + val source = collection( + LITTLE_ENDIAN, + ewkbZ | 7, + point(BIG_ENDIAN, ewkbZ | 1, 1, 2, 3), + nested, + point(LITTLE_ENDIAN, ewkbM | 1, 1, 2, 3)) + val expected = PublicWkbHeaderAdapter.toIsoWkb(source.clone()) + val result = PublicWkbHeaderAdapter.toIsoWkbInPlace(source) + assert(result eq source) + assert(typeCode(result) == 1007) + // The first member starts after the byte order, type and member count of the collection + assert(typeCode(result, 9) == 1001) + assert(result.toSeq == expected.toSeq) + } + + test("toIsoWkbInPlace leaves WKB without a Z or M coordinate, and ISO WKB, as it is") { + Seq( + point(LITTLE_ENDIAN, 1, 1, 2), + point(BIG_ENDIAN, 1001, 1, 2, 3), + collection(LITTLE_ENDIAN, 1007, line(BIG_ENDIAN, 1002, 1, 1, 2, 3))).foreach { source => + val before = source.clone() + assert(PublicWkbHeaderAdapter.toIsoWkbInPlace(source) eq source) + assert(source.toSeq == before.toSeq) + } + } + + test("toIsoWkbInPlace returns a new array for WKB with an embedded SRID") { + // ISO WKB has no place for the SRID, so the result is four bytes shorter than the source + val source = wkb(LITTLE_ENDIAN, 4 + 24) { buffer => + buffer.putInt(ewkbZ | ewkbSrid | 1).putInt(4326).putDouble(1).putDouble(2).putDouble(3) + } + val before = source.clone() + val result = PublicWkbHeaderAdapter.toIsoWkbInPlace(source) + assert(result.toSeq == point(LITTLE_ENDIAN, 1001, 1, 2, 3).toSeq) + assert(source.toSeq == before.toSeq) + } + + test("toIsoWkbInPlace rejects invalid WKB without changing it") { + // A valid Point Z in front of a member with a type that does not exist + val source = collection( + LITTLE_ENDIAN, + ewkbZ | 7, + point(LITTLE_ENDIAN, ewkbZ | 1, 1, 2, 3), + point(LITTLE_ENDIAN, 9, 1, 2)) + val before = source.clone() + intercept[IllegalArgumentException](PublicWkbHeaderAdapter.toIsoWkbInPlace(source)) + assert(source.toSeq == before.toSeq) + } +}