diff --git a/docs/api/sql/Parameter.md b/docs/api/sql/Parameter.md index 72e57fb4252..0b7a7c0b8c7 100644 --- a/docs/api/sql/Parameter.md +++ b/docs/api/sql/Parameter.md @@ -82,3 +82,28 @@ If you set the same parameter through both `sedona` and `spark.sedona` prefixes, | `spark.sedona.crs.url.base` | Base URL of a CRS definition server for resolving authority codes (e.g., EPSG) via HTTP. When set, ST_Transform will consult this URL provider before the built-in definitions. | _(empty — disabled)_ | e.g. `https://crs.example.com` | v1.9.0 | | `spark.sedona.crs.url.pathTemplate` | URL path template appended to `spark.sedona.crs.url.base`. Placeholders `{authority}` and `{code}` are replaced at runtime. | `/{authority}/{code}.json` | e.g. `/epsg/{code}.json` | v1.9.0 | | `spark.sedona.crs.url.format` | The CRS definition format returned by the URL provider | `projjson` | `projjson`, `proj`, `wkt1` (OGC WKT1), `wkt2` (ISO 19162 WKT2) | v1.9.0 | + +## GeoParquet Write Options + +These are options of a `geoparquet` write, not parameters of the session. Set them on the writer: + +```scala +df.write.format("geoparquet") + .option("geoparquet.version", "2.0.0") + .option("geoparquet.crs.geometry", projjson) + .save("/path/to/saved_geoparquet.parquet") +``` + +| Option | Description | Default | Possible Values | Since | +| :--- | :--- | :--- | :--- | :--- | +| `geoparquet.version` | GeoParquet version of the files. Version `2.0.0` stores the geometry columns in the Parquet `GEOMETRY` logical type and needs Spark 4.1 or later. | `1.1.0` | `1.0.0`, `1.1.0`, `2.0.0` | v1.5.1 (`2.0.0` since v2.0.0) | +| `geoparquet.crs` | CRS of all geometry columns | Derived from the SRID of the geometries | A PROJJSON string, `""` (OGC:CRS84) or `"null"` (unknown CRS) | v1.5.1 | +| `geoparquet.crs.` | CRS of one geometry column. It comes before `geoparquet.crs`. | Derived from the SRID of the geometries | A PROJJSON string, `""` (OGC:CRS84) or `"null"` (unknown CRS) | v1.5.1 | +| `geoparquet.covering` | Bounding box column of the geometry column, for a DataFrame with one geometry column | See `geoparquet.covering.mode` | Name of a top-level struct column with `xmin`, `ymin`, `xmax` and `ymax` | v1.6.1 | +| `geoparquet.covering.` | Bounding box column of one geometry column | See `geoparquet.covering.mode` | Name of a top-level struct column with `xmin`, `ymin`, `xmax` and `ymax` | v1.6.1 | +| `geoparquet.covering.mode` | What a GeoParquet `1.1.0` write does for a geometry column without a covering option | `auto` | `auto` (use `_bbox` as the bounding box column, and generate it if the DataFrame has none), `legacy` (write no covering) | v1.9.0 | +| `geoparquet.srid.lookahead.bytes` | A GeoParquet `2.0.0` write on Spark 4.1 takes the CRS of a geometry column without a CRS option from the first geometry of each file. This is the size of the rows that it holds in memory per file until every such column has shown a geometry. | `16777216` (16 MB) | A number of bytes | v2.0.0 | + +Since v2.0.0, the keys are read without regard to case, as Spark reads the keys of write options. In a key that ends in a column name, the name is first compared with the geometry columns as it is written: `geoparquet.covering.MODE` is the bounding box column of a geometry column `MODE`. If no geometry column has the name in that case, the name is compared without regard to case. The write fails if it then fits several geometry columns, which a DataFrame can have with `spark.sql.caseSensitive=true`. + +See [Apache Sedona GeoParquet with Spark](../../tutorial/files/geoparquet-sedona-spark.md) for examples. diff --git a/docs/api/sql/Parameter.zh.md b/docs/api/sql/Parameter.zh.md index 2d71f8f9b8a..8bea0560cce 100644 --- a/docs/api/sql/Parameter.zh.md +++ b/docs/api/sql/Parameter.zh.md @@ -82,3 +82,28 @@ sparkSession.conf.set("spark.sedona.global.index","false") | `spark.sedona.crs.url.base` | CRS 定义服务器的基础 URL,用于通过 HTTP 解析权威机构代码(如 EPSG)。设置后,ST_Transform 会先查询该 URL 提供者,再回退到内置定义。 | _(空 —— 禁用)_ | 例如 `https://crs.example.com` | v1.9.0 | | `spark.sedona.crs.url.pathTemplate` | 附加在 `spark.sedona.crs.url.base` 之后的 URL 路径模板。占位符 `{authority}` 和 `{code}` 会在运行时被替换。 | `/{authority}/{code}.json` | 例如 `/epsg/{code}.json` | v1.9.0 | | `spark.sedona.crs.url.format` | URL 提供者返回的 CRS 定义格式 | `projjson` | `projjson`、`proj`、`wkt1`(OGC WKT1)、`wkt2`(ISO 19162 WKT2) | v1.9.0 | + +## GeoParquet 写出选项 + +以下是 `geoparquet` 写出操作的选项,而不是会话参数,需要在 writer 上设置: + +```scala +df.write.format("geoparquet") + .option("geoparquet.version", "2.0.0") + .option("geoparquet.crs.geometry", projjson) + .save("/path/to/saved_geoparquet.parquet") +``` + +| 选项 | 说明 | 默认值 | 可选值 | 起始版本 | +| :--- | :--- | :--- | :--- | :--- | +| `geoparquet.version` | 文件的 GeoParquet 版本。`2.0.0` 版本把几何列存为 Parquet 的 `GEOMETRY` 逻辑类型,需要 Spark 4.1 及以上版本。 | `1.1.0` | `1.0.0`、`1.1.0`、`2.0.0` | v1.5.1(`2.0.0` 自 v2.0.0 起) | +| `geoparquet.crs` | 所有几何列的 CRS | 由几何对象的 SRID 推导 | PROJJSON 字符串、`""`(OGC:CRS84)或 `"null"`(未知 CRS) | v1.5.1 | +| `geoparquet.crs.` | 单个几何列的 CRS,优先于 `geoparquet.crs`。 | 由几何对象的 SRID 推导 | PROJJSON 字符串、`""`(OGC:CRS84)或 `"null"`(未知 CRS) | v1.5.1 | +| `geoparquet.covering` | 几何列的边界框列,适用于只有一个几何列的 DataFrame | 见 `geoparquet.covering.mode` | 包含 `xmin`、`ymin`、`xmax`、`ymax` 的顶层 struct 列的名称 | v1.6.1 | +| `geoparquet.covering.` | 单个几何列的边界框列 | 见 `geoparquet.covering.mode` | 包含 `xmin`、`ymin`、`xmax`、`ymax` 的顶层 struct 列的名称 | v1.6.1 | +| `geoparquet.covering.mode` | 写出 GeoParquet `1.1.0` 时,如何处理没有 covering 选项的几何列 | `auto` | `auto`(以 `_bbox` 作为边界框列,DataFrame 中没有该列时自动生成)、`legacy`(不写出 covering) | v1.9.0 | +| `geoparquet.srid.lookahead.bytes` | 在 Spark 4.1 上写出 GeoParquet `2.0.0` 时,没有 CRS 选项的几何列的 CRS 取自每个文件中该列的第一个几何对象。本选项是在所有这类列都出现几何对象之前,每个文件暂存在内存中的行的大小上限。 | `16777216`(16 MB) | 字节数 | v2.0.0 | + +自 v2.0.0 起,选项的键不区分大小写,与 Spark 处理写出选项的键的方式一致。对于以列名结尾的键,先按键中的写法与几何列的名称比较:`geoparquet.covering.MODE` 是几何列 `MODE` 的边界框列。如果没有几何列的名称与该写法完全一致,再忽略大小写进行比较。此时如果有多个几何列匹配,写出会失败;在 `spark.sql.caseSensitive=true` 时 DataFrame 可能包含这样的列。 + +示例请参见 [在 Spark 上使用 Apache Sedona 处理 GeoParquet](../../tutorial/files/geoparquet-sedona-spark.md)。 diff --git a/docs/tutorial/files/geoparquet-sedona-spark.md b/docs/tutorial/files/geoparquet-sedona-spark.md index 39f81c0667e..61ee4e5d2f0 100644 --- a/docs/tutorial/files/geoparquet-sedona-spark.md +++ b/docs/tutorial/files/geoparquet-sedona-spark.md @@ -252,6 +252,8 @@ The value of `geoparquet.crs` and `geoparquet.crs.` can be one of t * `""` (empty string): Omit the `crs` field. This implies that the CRS is [OGC:CRS84](https://www.opengis.net/def/crs/OGC/1.3/CRS84) for CRS-aware implementations. * `"{...}"` (PROJJSON string): The `crs` field will be set as the PROJJSON object representing the Coordinate Reference System (CRS) of the geometry. You can find the PROJJSON string of a specific CRS from here: https://epsg.io/ (click the JSON option at the bottom of the page). You can also customize your PROJJSON string as needed. +All options of a GeoParquet write are listed in [Parameter](../../api/sql/Parameter.md). + ### Automatic CRS from SRID When no `geoparquet.crs` option is explicitly provided, Sedona will automatically derive the CRS PROJJSON from the SRID of the geometry column. For example, if all geometries in a column have SRID 32632 (set via [`ST_SetSRID`](../../api/sql/Spatial-Reference-System/ST_SetSRID.md)), the writer will automatically produce the PROJJSON for EPSG:32632 in the GeoParquet metadata. For SRID 4326, the CRS field is omitted since this is the GeoParquet default (OGC:CRS84). @@ -283,14 +285,6 @@ df.write.format("geoparquet").option("geoparquet.version", "2.0.0").save( ) ``` -On Spark 4.1 the write also needs the CRS of the geometry columns, for the reason given below. An empty `geoparquet.crs` stands for OGC:CRS84: - -```python -df.write.format("geoparquet").option("geoparquet.version", "2.0.0").option( - "geoparquet.crs", "" -).save("/tmp/somewhere") -``` - 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. @@ -312,7 +306,11 @@ On Spark 4.2 and later the CRS comes from the SRID of the column type. Sedona's `geoparquet` reader returns a geometry column for a GeoParquet 2.0 file. The exception is a column whose CRS gives no SRID, such as PROJJSON without an identifier, on Spark 4.2 and later. Sedona cannot infer a native geometry type for it, so the read fails unless you give a schema with Sedona's own geometry type, as the section on reading GeoParquet 2.0 files shows. What Spark's own Parquet reader, `spark.read.parquet`, returns on Spark 4.2 depends on the column the file was written from. For a native geometry column it returns a native geometry column. For a `GeometryUDT` column, which is every geometry column written on Spark 4.1, it returns the WKB as a binary column, as it does for a GeoParquet 1.1 file. -On Spark 4.1 the SRID belongs to each geometry and not to the column, so a GeoParquet 2.0 write needs the CRS of every geometry column in `geoparquet.crs` or `geoparquet.crs.`. +On Spark 4.1 the SRID belongs to each geometry and not to the column, while a GeoParquet 2.0 column has a single CRS. Sedona takes it from the first geometry of the column in each file, and the write fails if another geometry in that file has a different SRID. A column with SRID 0, or without any geometry in the file, is written with an unknown CRS. + +Sedona has to know the CRS before it writes the first row, so it holds the rows before the first geometry in memory, up to 16 MB per file. `geoparquet.srid.lookahead.bytes` changes that limit. A column that has shown no geometry by then is written with an unknown CRS, and a later geometry with an SRID fails the write. + +Set `geoparquet.crs` or `geoparquet.crs.` to state the CRS yourself. Sedona then writes it as given and does not compare it with the SRIDs of the geometries. Spark 3.5 and 4.0 ship a Parquet library that predates the `GEOMETRY` logical type. Sedona writes GeoParquet 1.1 on these versions and rejects `geoparquet.version` `2.0.0`. diff --git a/docs/tutorial/files/geoparquet-sedona-spark.zh.md b/docs/tutorial/files/geoparquet-sedona-spark.zh.md index b3acf85edc9..37a85bee115 100644 --- a/docs/tutorial/files/geoparquet-sedona-spark.zh.md +++ b/docs/tutorial/files/geoparquet-sedona-spark.zh.md @@ -249,6 +249,8 @@ df.write.format("geoparquet") * `""`(空字符串):省略 `crs` 字段。对于支持 CRS 的实现而言,意味着使用 [OGC:CRS84](https://www.opengis.net/def/crs/OGC/1.3/CRS84)。 * `"{...}"`(PROJJSON 字符串):`crs` 字段会被设为表示该几何坐标参考系的 PROJJSON 对象。可在 https://epsg.io/ (页面底部点击 JSON 选项)查找特定 CRS 的 PROJJSON,也可以根据需要自定义 PROJJSON。 +GeoParquet 写出操作的全部选项见[参数](../../api/sql/Parameter.md)。 + ### 通过 SRID 自动推断 CRS 未显式提供 `geoparquet.crs` 选项时,Sedona 会根据几何列的 SRID 自动推导出 CRS PROJJSON。例如,如果某列所有几何对象的 SRID 都是 32632(通过 [`ST_SetSRID`](../../api/sql/Spatial-Reference-System/ST_SetSRID.md) 设置),写入器会自动在 GeoParquet 元数据中生成 EPSG:32632 对应的 PROJJSON。当 SRID 为 4326 时,由于这就是 GeoParquet 的默认 CRS(OGC:CRS84),`crs` 字段会被省略。 @@ -278,14 +280,6 @@ df.write.format("geoparquet").option("geoparquet.version", "2.0.0").save( ) ``` -在 Spark 4.1 上,写出时还需要给出几何列的 CRS,原因见下文。空的 `geoparquet.crs` 表示 OGC:CRS84: - -```python -df.write.format("geoparquet").option("geoparquet.version", "2.0.0").option( - "geoparquet.crs", "" -).save("/tmp/somewhere") -``` - GeoParquet 2.0 文件与 GeoParquet 1.1 文件有以下区别: * 几何列带有 `GEOMETRY` 逻辑类型,CRS 是该类型的一个属性。GeoParquet 元数据会以 PROJJSON 重复给出 CRS。 @@ -307,7 +301,11 @@ Sedona 会用能够标识 CRS 的最短形式写出列的 `crs` 属性: Sedona 的 `geoparquet` 读取器会把 GeoParquet 2.0 文件的几何列读取为几何列。例外是在 Spark 4.2 及更高版本上,CRS 无法给出 SRID 的列,例如没有标识符的 PROJJSON。Sedona 无法为它推断出原生几何类型,因此读取会失败,除非你提供一个使用 Sedona 自己的几何类型的 schema,做法见读取 GeoParquet 2.0 文件一节。Spark 自带的 Parquet 读取器 `spark.read.parquet` 在 Spark 4.2 上返回什么,取决于写出文件时的列类型。对于原生几何列,它返回原生几何列。对于 `GeometryUDT` 列(在 Spark 4.1 上写出的几何列都是这种类型),它以二进制列返回 WKB,与读取 GeoParquet 1.1 文件时相同。 -在 Spark 4.1 上,SRID 属于每个几何对象而不属于列,因此写出 GeoParquet 2.0 时需要通过 `geoparquet.crs` 或 `geoparquet.crs.` 给出每个几何列的 CRS。 +在 Spark 4.1 上,SRID 属于每个几何对象而不属于列,而 GeoParquet 2.0 的一列只有一个 CRS。Sedona 取每个文件中该列第一个几何对象的 SRID 作为列的 CRS;如果同一文件中另一个几何对象的 SRID 不同,写出会失败。SRID 为 0 的列,或在文件中没有任何几何对象的列,会以未知 CRS 写出。 + +Sedona 必须在写出第一行之前知道 CRS,因此会把第一个几何对象之前的行暂存在内存中,每个文件最多 16 MB。`geoparquet.srid.lookahead.bytes` 可以修改这一上限。到达上限时仍未出现几何对象的列会以未知 CRS 写出,之后如果出现带 SRID 的几何对象,写出会失败。 + +设置 `geoparquet.crs` 或 `geoparquet.crs.` 可以自行指定 CRS。此时 Sedona 按给定值写出,不再与几何对象的 SRID 比较。 Spark 3.5 和 4.0 自带的 Parquet 库早于 `GEOMETRY` 逻辑类型。Sedona 在这些版本上写出 GeoParquet 1.1,并拒绝把 `geoparquet.version` 设为 `2.0.0`。 diff --git a/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/FirstGeometryOutputWriter.scala b/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/FirstGeometryOutputWriter.scala new file mode 100644 index 00000000000..3323c472a56 --- /dev/null +++ b/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/FirstGeometryOutputWriter.scala @@ -0,0 +1,143 @@ +/* + * 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.execution.datasources.geoparquet + +import scala.collection.mutable + +import org.apache.hadoop.conf.Configuration +import org.apache.hadoop.fs.Path +import org.apache.hadoop.mapreduce.{RecordWriter, TaskAttemptContext} +import org.apache.parquet.hadoop.ParquetOutputFormat +import org.apache.parquet.hadoop.codec.CodecConfig +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.expressions.{UnsafeProjection, UnsafeRow} +import org.apache.spark.sql.execution.datasources.OutputWriter +import org.apache.spark.sql.sedona_sql.types.SpatialTypeSupport +import org.apache.spark.sql.types.StructType + +/** + * Writes a GeoParquet 2 file that has GeometryUDT columns without a CRS option. + * + * GeoParquet 2 states the CRS of a geometry column in the Parquet schema, which the Parquet + * writer needs before the first row. A GeometryUDT column has an SRID on each geometry only. This + * writer therefore holds rows back until every such column has shown a geometry, then opens the + * file with those SRIDs. [[GeoParquetWriteSupport]] turns them into the CRS of the columns and + * rejects a later geometry that has another SRID. + * + * The rows held back are limited to [[GeoParquetWriteSupport.GEOPARQUET_SRID_LOOKAHEAD_KEY]] + * bytes. A column that has shown no geometry by then is written with an unknown CRS. + * + * @param columns + * the ordinals of the columns to look up, see [[GeoParquetWriteSupport.columnsWithoutCrs]] + */ +class FirstGeometryOutputWriter( + val path: String, + context: TaskAttemptContext, + schema: StructType, + columns: Seq[Int]) + extends OutputWriter { + + private val configuration = context.getConfiguration + private val lookaheadBytes = configuration.getLong( + GeoParquetWriteSupport.GEOPARQUET_SRID_LOOKAHEAD_KEY, + GeoParquetWriteSupport.DEFAULT_CRS_LOOKAHEAD_BYTES) + + private val waiting = mutable.LinkedHashSet(columns: _*) + private val srids = mutable.Map.empty[Int, Int] + private val heldBack = mutable.ArrayBuffer.empty[UnsafeRow] + private var toUnsafe: UnsafeProjection = _ + private var heldBackBytes = 0L + private var recordWriter: RecordWriter[Void, InternalRow] = _ + private var closed = false + + override def write(row: InternalRow): Unit = { + if (recordWriter != null) { + recordWriter.write(null, row) + } else { + waiting.toSeq.foreach { ordinal => + if (!row.isNullAt(ordinal)) { + val geometry = SpatialTypeSupport.readGeometry(row, ordinal, schema(ordinal).dataType) + srids.put(ordinal, geometry.getSRID) + waiting.remove(ordinal) + } + } + // The row that ends the wait is written as it is: the one that shows the last geometry + // waited for, or the one that reaches the limit. Only the rows before it are kept, which + // keeps the rows held back under the limit however large this row is. + val kept = + if (waiting.isEmpty) None + else Some(asUnsafe(row)).filter(heldBackBytes + _.getSizeInBytes < lookaheadBytes) + kept match { + case Some(unsafe) => + heldBack += unsafe.copy() + heldBackBytes += unsafe.getSizeInBytes + case None => + open() + recordWriter.write(null, row) + } + } + } + + /** + * A row of another kind may share its values with the caller, and does not tell its size. As an + * UnsafeRow it tells its size, and a copy of that owns all its values. + */ + private def asUnsafe(row: InternalRow): UnsafeRow = row match { + case unsafe: UnsafeRow => unsafe + case other => + if (toUnsafe == null) toUnsafe = UnsafeProjection.create(schema) + toUnsafe(other) + } + + private def open(): Unit = { + // Other files of the same task may find other SRIDs, so each file gets its own configuration + val fileConfiguration = new Configuration(configuration) + columns.foreach { ordinal => + fileConfiguration.set( + GeoParquetWriteSupport.FIRST_GEOMETRY_SRID_KEY + ordinal, + srids.get(ordinal).map(_.toString).getOrElse(GeoParquetWriteSupport.NO_FIRST_GEOMETRY)) + } + recordWriter = new ParquetOutputFormat[InternalRow]() + .getRecordWriter(fileConfiguration, new Path(path), CodecConfig.from(context).getCodec) + try heldBack.foreach(recordWriter.write(null, _)) + catch { + case error: Throwable => + // A row held back can fail, with a second SRID for example. Spark does not close a + // writer again after its close() has failed, so the file is released here. + release(error) + throw error + } finally { + heldBack.clear() + // It keeps the last row that it converted + toUnsafe = null + } + } + + private def release(error: Throwable): Unit = { + closed = true + try recordWriter.close(context) + catch { case other: Throwable => error.addSuppressed(other) } + } + + override def close(): Unit = if (!closed) { + if (recordWriter == null) open() + closed = true + recordWriter.close(context) + } +} diff --git a/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeoParquetFileFormat.scala b/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeoParquetFileFormat.scala index df64872dc34..2c0f54a5da2 100644 --- a/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeoParquetFileFormat.scala +++ b/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeoParquetFileFormat.scala @@ -92,6 +92,7 @@ class GeoParquetFileFormat(val spatialFilter: Option[GeoParquetSpatialFilter]) val parquetOptions = new ParquetOptions(options, sqlConf) val conf = ContextUtil.getConfiguration(job) + GeoParquetWriteSupport.setWriteOptions(options, dataSchema, conf) GeoParquetWriteSupport.requireSupportedVersion(conf) val committerClass = @@ -168,7 +169,11 @@ class GeoParquetFileFormat(val spatialFilter: Option[GeoParquetSpatialFilter]) path: String, dataSchema: StructType, context: TaskAttemptContext): OutputWriter = { - new ParquetOutputWriter(path, context) + // A GeoParquet 2 file needs the CRS of its GeometryUDT columns before the first row + val columns = + GeoParquetWriteSupport.columnsWithoutCrs(dataSchema, context.getConfiguration) + if (columns.isEmpty) new ParquetOutputWriter(path, context) + else new FirstGeometryOutputWriter(path, context, dataSchema, columns) } override def getFileExtension(context: TaskAttemptContext): String = { 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 5a27ae2a0a1..385485ba3fe 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 @@ -30,7 +30,7 @@ import org.apache.spark.SPARK_VERSION_SHORT import org.apache.spark.internal.Logging import org.apache.spark.sql.catalyst.InternalRow import org.apache.spark.sql.catalyst.expressions.SpecializedGetters -import org.apache.spark.sql.catalyst.util.DateTimeUtils +import org.apache.spark.sql.catalyst.util.{CaseInsensitiveMap, 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} @@ -116,6 +116,9 @@ class GeoParquetWriteSupport extends WriteSupport[InternalRow] with Logging { // The CRS of the geometry columns for which it is known before the first row is written: the // columns of a native Spark type, and every geometry column of a GeoParquet 2 file. private var fixedColumnCrs: Map[Int, Option[JValue]] = Map.empty + // The SRID that FirstGeometryOutputWriter found for a GeometryUDT column of a GeoParquet 2 file, + // None when it found no geometry before it had to open the file. + private val firstGeometrySrids: mutable.Map[Int, Option[Int]] = mutable.Map.empty private val geoParquetColumnCoveringMap: mutable.Map[String, Covering] = mutable.Map.empty private val generatedCoveringColumnOrdinals: mutable.Map[Int, Int] = mutable.Map.empty private var geoParquetCoveringMode: String = GEOPARQUET_COVERING_MODE_AUTO @@ -177,12 +180,12 @@ class GeoParquetWriteSupport extends WriteSupport[InternalRow] with Logging { userExplicitlySetDefaultCrs = true Some(parse(crs)) } - geometryColumnInfoMap.keys.map(schema(_).name).foreach { name => - Option(configuration.get(GEOPARQUET_CRS_KEY + "." + name)).foreach { - case "" => geoParquetColumnCrsMap.put(name, None) - case crs: String => geoParquetColumnCrsMap.put(name, Some(parse(crs))) + GeoParquetWriteSupport + .columnCrsOptions(configuration, geometryColumnInfoMap.keys.map(schema(_).name).toSeq) + .foreach { + case (name, "") => geoParquetColumnCrsMap.put(name, None) + case (name, crs) => geoParquetColumnCrsMap.put(name, Some(parse(crs))) } - } fixedColumnCrs = geometryColumnInfoMap.keys.flatMap { ordinal => val field = schema(ordinal) val explicit = geoParquetColumnCrsMap.get(field.name).orElse { @@ -193,11 +196,22 @@ class GeoParquetWriteSupport extends WriteSupport[InternalRow] with Logging { Some(ordinal -> GeoParquetNativeCrs.writeCrs(field.name, srid, explicit)) case None if writesGeospatialTypes => // The GEOMETRY logical type states the CRS in the Parquet schema, and a GeometryUDT - // column only has an SRID on each geometry. - Some(ordinal -> explicit.getOrElse(throw new IllegalArgumentException( - s"GeoParquet ${geoParquetVersion.get} states the CRS of column '${field.name}' in " + - "the Parquet schema, which is fixed before the first row is written. Set " + - s"$GEOPARQUET_CRS_KEY or $GEOPARQUET_CRS_KEY.${field.name} to the CRS of the column."))) + // column only has an SRID on each geometry. FirstGeometryOutputWriter looks it up. + Some(ordinal -> explicit.getOrElse { + val found = + configuration.get(GeoParquetWriteSupport.FIRST_GEOMETRY_SRID_KEY + ordinal) + if (found == null) { + throw new IllegalArgumentException( + s"GeoParquet ${geoParquetVersion.get} states the CRS of column '${field.name}' " + + "in the Parquet schema, which is fixed before the first row is written. Set " + + s"$GEOPARQUET_CRS_KEY or $GEOPARQUET_CRS_KEY.${field.name} to the CRS of the " + + "column.") + } + val srid = + if (found == GeoParquetWriteSupport.NO_FIRST_GEOMETRY) None else Some(found.toInt) + firstGeometrySrids.put(ordinal, srid) + GeoParquetNativeCrs.writeCrs(field.name, srid.getOrElse(0), None) + }) case None => None } }.toMap @@ -542,6 +556,7 @@ class GeoParquetWriteSupport extends WriteSupport[InternalRow] with Logging { val geospatialTypes = writesGeospatialTypes val wkbWriter = new WKBWriter(if (geospatialTypes) 4 else 3, byteOrder, false) wkbWriter.setPreserveCoordinateDimensions(true) + val firstGeometrySrid = rootOrdinal.flatMap(firstGeometrySrids.get) (row: SpecializedGetters, ordinal: Int) => { // 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 @@ -562,6 +577,15 @@ class GeoParquetWriteSupport extends WriteSupport[InternalRow] with Logging { expectedSrid, geom.getSRID) } + firstGeometrySrid.foreach { expected => + if (geom.getSRID != expected.getOrElse(0)) { + throw GeoParquetWriteSupport.secondSrid( + geoParquetVersion.get, + schema(rootOrdinal.get).name, + expected, + 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 @@ -821,6 +845,137 @@ class GeoParquetWriteSupport extends WriteSupport[InternalRow] with Logging { object GeoParquetWriteSupport { + /** + * Prefix of the configuration keys under which [[FirstGeometryOutputWriter]] passes the SRID of + * the first geometry of a column, followed by the ordinal of the column. The value is + * [[NO_FIRST_GEOMETRY]] when it found none. + */ + private[geoparquet] val FIRST_GEOMETRY_SRID_KEY = + "org.apache.sedona.geoparquet.first-geometry-srid." + private[geoparquet] val NO_FIRST_GEOMETRY = "none" + + /** + * Configuration key for the bytes of rows that a GeoParquet 2 write holds back while it waits + * for the first geometry of a GeometryUDT column. It is not under geoparquet.crs, where every + * key that goes on names a column. + */ + val GEOPARQUET_SRID_LOOKAHEAD_KEY = "geoparquet.srid.lookahead.bytes" + val DEFAULT_CRS_LOOKAHEAD_BYTES: Long = 16L * 1024 * 1024 + + /** + * The ordinals of the geometry columns whose CRS a GeoParquet 2 write takes from the data: + * GeometryUDT columns that no CRS option covers. A native Spark geometry type names its SRID, + * and a GeoParquet 1 file states the CRS in metadata that is written after the last row. + */ + def columnsWithoutCrs(schema: StructType, configuration: Configuration): Seq[Int] = { + val version = Option(configuration.get(GEOPARQUET_VERSION_KEY)).getOrElse(VERSION) + if (!GeoParquetMetaData.usesGeospatialTypes(version) || + configuration.get(GEOPARQUET_CRS_KEY) != null) { + Seq.empty + } else { + val candidates = schema.fields.toSeq.zipWithIndex.filter { case (field, _) => + SpatialTypeSupport.isGeometry(field.dataType) && + SpatialTypeSupport.geometrySrid(field.dataType).isEmpty + } + val stated = columnCrsOptions(configuration, candidates.map(_._1.name)) + candidates.collect { case (field, ordinal) if !stated.contains(field.name) => ordinal } + } + } + + /** The CRS option of each of `columns` that has one, under the key [[setWriteOptions]] set. */ + private[geoparquet] def columnCrsOptions( + configuration: Configuration, + columns: Seq[String]): Map[String, String] = + columns.flatMap { column => + Option(configuration.get(GEOPARQUET_CRS_KEY + "." + column)).map(column -> _) + }.toMap + + /** The keys of the options of a GeoParquet write that are complete as they are. */ + private val WRITE_OPTION_KEYS = Seq( + GEOPARQUET_VERSION_KEY, + GEOPARQUET_CRS_KEY, + GEOPARQUET_COVERING_KEY, + GEOPARQUET_COVERING_MODE_KEY, + GEOPARQUET_SRID_LOOKAHEAD_KEY) + + /** The keys of the options of a GeoParquet write that go on with the name of a column. */ + private val COLUMN_WRITE_OPTION_KEYS = + Seq(GEOPARQUET_CRS_KEY + ".", GEOPARQUET_COVERING_KEY + ".") + + /** + * Sets the GeoParquet options of a write in `configuration` under the keys that the writer + * reads there. Spark takes the keys of the options of a write without regard to case, and + * copies them to the Hadoop configuration as they were written, where a key in another case is + * another key. An option of the write replaces a value that the configuration has from + * elsewhere. + * + * A key that goes on with the name of a geometry column, in the case of that column, is for + * that column. This comes before anything else that the key is in another case: + * `geoparquet.covering.MODE` is the covering of a column `MODE`, not the covering mode. When no + * geometry column has the name in that case and the key is no other option either, the key is + * for the column whose name differs from it in case only, and is rejected when there are + * several of those. + */ + def setWriteOptions( + options: Map[String, String], + schema: StructType, + configuration: Configuration): Unit = { + def lowerCase(text: String): String = text.toLowerCase(java.util.Locale.ROOT) + val geometryColumns = + schema.fields.toSeq + .filter(field => SpatialTypeSupport.isGeometry(field.dataType)) + .map(_.name) + // The map that Spark hands over lists its keys in lower case, which would take the case + // from the column names in them + val asWritten = options match { + case insensitive: CaseInsensitiveMap[String @unchecked] => insensitive.originalMap + case other => other + } + asWritten.foreach { case (key, value) => + // The name that the key goes on with, if it is the key of a column + val ofColumn = COLUMN_WRITE_OPTION_KEYS + .find(lowerCase(key).startsWith) + .map(prefix => prefix -> key.substring(prefix.length)) + ofColumn match { + case Some((prefix, name)) if geometryColumns.contains(name) => + configuration.set(prefix + name, value) + case _ => + WRITE_OPTION_KEYS.find(_ == lowerCase(key)) match { + case Some(complete) => configuration.set(complete, value) + case None => + ofColumn.foreach { case (prefix, name) => + val columns = geometryColumns.filter(lowerCase(_) == lowerCase(name)) + if (columns.size > 1) { + throw new IllegalArgumentException( + s"Option $key names the geometry columns " + + s"${columns.mkString("'", "', '", "'")}, which differ in case only. " + + "Write the name in the key in the case of the column that the option " + + "is for.") + } + columns.foreach(column => configuration.set(prefix + column, value)) + } + } + } + } + } + + private def secondSrid( + version: String, + column: String, + first: Option[Int], + second: Int): IllegalArgumentException = { + val found = first match { + case Some(srid) => s"The first geometry of column '$column' has SRID $srid" + case None => + s"Column '$column' had no geometry in the first rows of the file, so its CRS was " + + "written as unknown" + } + new IllegalArgumentException( + s"$found, but another geometry has SRID $second. A GeoParquet $version column has a " + + "single CRS: give all its geometries the same SRID, or set " + + s"$GEOPARQUET_CRS_KEY or $GEOPARQUET_CRS_KEY.$column to state the CRS.") + } + /** GeoParquet 2 needs the geospatial logical types of the Parquet library on the classpath. */ def requireSupportedVersion(configuration: Configuration): Unit = { Option(configuration.get(GEOPARQUET_VERSION_KEY)).foreach { version => diff --git a/spark/common/src/test/scala/org/apache/sedona/sql/GeoParquetNativeTypesSuite.scala b/spark/common/src/test/scala/org/apache/sedona/sql/GeoParquetNativeTypesSuite.scala index bb469905e3c..9cbb6ce4ff9 100644 --- a/spark/common/src/test/scala/org/apache/sedona/sql/GeoParquetNativeTypesSuite.scala +++ b/spark/common/src/test/scala/org/apache/sedona/sql/GeoParquetNativeTypesSuite.scala @@ -25,19 +25,26 @@ import java.nio.file.Files import org.apache.commons.io.FileUtils import org.apache.hadoop.conf.Configuration import org.apache.hadoop.fs.Path -import org.apache.parquet.hadoop.{ParquetFileReader, ParquetReader} +import org.apache.hadoop.mapreduce.{Job, TaskAttemptID, TaskType} +import org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl +import org.apache.parquet.hadoop.{ParquetFileReader, ParquetOutputFormat, ParquetReader} import org.apache.parquet.hadoop.example.GroupReadSupport import org.apache.parquet.hadoop.metadata.{ColumnChunkMetaData, ParquetMetadata} import org.apache.parquet.hadoop.util.HadoopInputFile -import org.apache.spark.sql.DataFrame -import org.apache.spark.sql.execution.datasources.geoparquet.{GeoParquetMetaData, ParquetGeospatialColumn, ParquetGeospatialTypes} +import org.apache.spark.sql.{DataFrame, Row} +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.expressions.{GenericInternalRow, UnsafeProjection} +import org.apache.spark.sql.execution.datasources.OutputWriter +import org.apache.spark.sql.execution.datasources.geoparquet.{GeoParquetFileFormat, GeoParquetMetaData, GeoParquetWriteSupport, ParquetGeospatialColumn, ParquetGeospatialTypes} import org.apache.spark.sql.sedona_sql.UDT.GeometryUDT import org.apache.spark.sql.sedona_sql.types.SpatialTypeSupport import org.apache.spark.sql.types.{BinaryType, StructField, StructType} -import org.locationtech.jts.geom.Geometry import org.json4s.{JArray, JDouble, JInt, JNothing, JNull, JString, JValue} import org.json4s.jackson.JsonMethods.{compact, parse, render} +import org.locationtech.jts.geom.{Coordinate, Geometry, GeometryFactory} + +import scala.collection.mutable import scala.util.Try /** @@ -98,6 +105,12 @@ class GeoParquetNativeTypesSuite extends TestBaseScala { ParquetGeospatialTypes.describe(schema.getType(schema.getFieldIndex("geometry"))) } + /** The CRS that the Parquet schema of the file in `path` states for `column`. */ + private def parquetCrs(path: String, column: String): Option[String] = { + val schema = footer(path).getFileMetaData.getSchema + ParquetGeospatialTypes.describe(schema.getType(schema.getFieldIndex(column))).flatMap(_.crs) + } + private def geoMetadata(footer: ParquetMetadata): JValue = parse(footer.getFileMetaData.getKeyValueMetaData.get("geo")) @@ -108,6 +121,73 @@ class GeoParquetNativeTypesSuite extends TestBaseScala { .sql(s"SELECT ST_SetSRID(ST_Point(1.0, 2.0), $srid) AS geometry") .coalesce(1) + private def pointWithSrid(srid: Int): Geometry = { + val point = new GeometryFactory().createPoint(new Coordinate(1, 2)) + point.setSRID(srid) + point + } + + /** One partition of GeometryUDT columns, where the SRID belongs to each geometry. */ + private def udtColumns(names: Seq[String], rows: Seq[Geometry]*): DataFrame = + sparkSession.createDataFrame( + sparkSession.sparkContext.parallelize(rows.map(Row.fromSeq(_)), 1), + StructType(names.map(StructField(_, GeometryUDT())))) + + private def udtColumn(geometries: Geometry*): DataFrame = + udtColumns(Seq("geometry"), geometries.map(Seq(_)): _*) + + private def writeVersion2(df: DataFrame, path: String, options: (String, String)*): Unit = + df.write + .format("geoparquet") + .option("geoparquet.version", "2.0.0") + .options(options.toMap) + .save(path) + + /** + * Writes a GeoParquet 2 file to `path` with the writer that a write task gets, the way a caller + * does that hands it rows of its own. + */ + private def withWriter( + path: String, + schema: StructType, + options: Map[String, String] = Map.empty, + writeSupport: Option[Class[_]] = None)(run: OutputWriter => Unit): Unit = { + val all = options + ("geoparquet.version" -> "2.0.0") + val job = Job.getInstance(sparkSession.sessionState.newHadoopConfWithOptions(all)) + val factory = new GeoParquetFileFormat().prepareWrite(sparkSession, job, all, schema) + writeSupport.foreach { support => + job.getConfiguration.set(ParquetOutputFormat.WRITE_SUPPORT_CLASS, support.getName) + } + val context = new TaskAttemptContextImpl( + job.getConfiguration, + new TaskAttemptID("test", 0, TaskType.MAP, 0, 0)) + val writer = factory.newInstance(path, schema, context) + try run(writer) + catch { + case error: Throwable => + Try(writer.close()) + throw error + } + writer.close() + } + + private def withCaseSensitiveNames(run: => Unit): Unit = { + val key = "spark.sql.caseSensitive" + val before = sparkSession.conf.get(key) + sparkSession.conf.set(key, "true") + try run + finally sparkSession.conf.set(key, before) + } + + /** The SRID of each geometry read back from `path`, None for a null geometry. */ + private def sridsIn(path: String, column: String = "geometry"): Seq[Option[Int]] = + sparkSession.read + .format("geoparquet") + .load(path) + .collect() + .map(row => Option(row.getJtsGeometry(column)).map(_.getSRID)) + .toSeq + describe("Reading Parquet native geospatial types") { if (libraryHasGeospatialTypes) { it("reads the GeoParquet 2.0.0 example file") { @@ -277,20 +357,273 @@ class GeoParquetNativeTypesSuite extends TestBaseScala { Seq(4326 -> None, 3857 -> Some("EPSG:3857"), 0 -> Some("srid:0")).foreach { case (srid, crsProperty) => - it(s"takes the CRS of a GEOMETRY column from a native Spark type with SRID $srid") { - withPath { path => - val writer = - point(srid).write.format("geoparquet").option("geoparquet.version", "2.0.0") - if (SpatialTypeSupport.usesNativeTypes) { - writer.save(path) + it(s"takes the CRS of a GEOMETRY column from SRID $srid") { + // The SRID is part of a native Spark type and of each geometry of a GeometryUDT + Seq(point(srid), udtColumn(pointWithSrid(srid), pointWithSrid(srid))).foreach { df => + withPath { path => + writeVersion2(df, path) assert(geometryColumn(footer(path)) == geometry(crsProperty)) - } else { - // The SRID of a GeometryUDT column is only known per geometry - val error = intercept[Exception](writer.save(path)) - assert(messages(error).contains("geoparquet.crs")) + assert(sridsIn(path).forall(_.contains(srid))) + } + } + } + } + + it("takes the CRS of a GeometryUDT column from its first geometry after null rows") { + withPath { path => + writeVersion2(udtColumn(null, null, pointWithSrid(3857)), path) + assert(geometryColumn(footer(path)) == geometry(Some("EPSG:3857"))) + assert(sridsIn(path) == Seq(None, None, Some(3857))) + } + } + + it("takes the CRS of each GeometryUDT column from its own first geometry") { + withPath { path => + val df = udtColumns( + Seq("geometry", "other"), + Seq(pointWithSrid(4326), null), + Seq(pointWithSrid(4326), pointWithSrid(3857))) + writeVersion2(df, path) + val schema = footer(path).getFileMetaData.getSchema + def crsOf(column: String): Option[String] = ParquetGeospatialTypes + .describe(schema.getType(schema.getFieldIndex(column))) + .flatMap(_.crs) + assert(crsOf("geometry").isEmpty) + assert(crsOf("other").contains("EPSG:3857")) + assert(sridsIn(path) == Seq(Some(4326), Some(4326))) + assert(sridsIn(path, "other") == Seq(None, Some(3857))) + } + } + + it("fails when a GeometryUDT column holds a second SRID") { + withPath { path => + val error = intercept[Exception] { + writeVersion2(udtColumn(pointWithSrid(4326), pointWithSrid(3857)), path) + } + val message = messages(error) + assert(message.contains("SRID 4326") && message.contains("SRID 3857")) + assert(message.contains("geoparquet.crs")) + } + } + + it("writes an unknown CRS for a GeometryUDT column without geometries") { + Seq(udtColumn(null, null), udtColumn()).foreach { df => + withPath { path => + writeVersion2(df, path) + assert(geometryColumn(footer(path)) == geometry(Some("srid:0"))) + assert(geoMetadata(footer(path)) \ "columns" \ "geometry" \ "crs" == JNull) + } + } + } + + it("stops waiting for the first geometry when the rows held back reach the limit") { + val limit = "geoparquet.srid.lookahead.bytes" -> "1" + withPath { path => + // The CRS is fixed as unknown after the first row, which geometries without an SRID fit + writeVersion2(udtColumn(null, pointWithSrid(0)), path, limit) + assert(geometryColumn(footer(path)) == geometry(Some("srid:0"))) + assert(sridsIn(path) == Seq(None, Some(0))) + } + withPath { path => + val error = intercept[Exception] { + writeVersion2(udtColumn(null, pointWithSrid(3857)), path, limit) + } + assert(messages(error).contains("geoparquet.crs")) + } + } + + it("does not check the geometries of a GeometryUDT column against geoparquet.crs") { + withPath { path => + writeVersion2( + udtColumn(pointWithSrid(4326), pointWithSrid(3857)), + path, + "geoparquet.crs" -> "") + assert(geometryColumn(footer(path)) == geometry(None)) + } + } + + it("takes the CRS options whatever the case of their keys") { + // Spark takes the keys of the options of a write without regard to case + val df = udtColumns(Seq("Geom"), Seq(pointWithSrid(4326))) + Seq("geoparquet.crs.geom", "GeoParquet.CRS.Geom", "GEOPARQUET.CRS").foreach { key => + withPath { path => + writeVersion2(df, path, key -> webMercator) + assert(parquetCrs(path, "Geom").contains("EPSG:3857"), key) + } + } + withPath { path => + df.write + .format("geoparquet") + .option("geoparquet.version", "1.1.0") + .option("GEOPARQUET.CRS.GEOM", webMercator) + .save(path) + assert(geoMetadata(footer(path)) \ "columns" \ "Geom" \ "crs" == parse(webMercator)) + } + } + + it("takes the version whatever the case of its key") { + withPath { path => + point(3857).write.format("geoparquet").option("GeoParquet.Version", "2.0.0").save(path) + assert(geometryColumn(footer(path)).exists(_.crs.contains("EPSG:3857"))) + } + } + + it("gives the CRS option of a column to that column only") { + withCaseSensitiveNames { + val df = + udtColumns(Seq("Geom", "geom"), Seq(pointWithSrid(4326), pointWithSrid(32610))) + withPath { path => + writeVersion2(df, path, "geoparquet.crs.Geom" -> webMercator) + assert(parquetCrs(path, "Geom").contains("EPSG:3857")) + assert(parquetCrs(path, "geom").contains("EPSG:32610")) + } + withPath { path => + df.write + .format("geoparquet") + .option("geoparquet.version", "1.1.0") + .option("geoparquet.crs.Geom", webMercator) + .save(path) + val columns = geoMetadata(footer(path)) \ "columns" + assert(columns \ "Geom" \ "crs" == parse(webMercator)) + assert(columns \ "geom" \ "crs" \ "id" \ "code" == JInt(32610)) + } + } + } + + it("rejects a CRS option that names two columns in a case that neither has") { + withCaseSensitiveNames { + val df = + udtColumns(Seq("Geom", "geom"), Seq(pointWithSrid(4326), pointWithSrid(32610))) + withPath { path => + val message = messages(intercept[Exception] { + writeVersion2(df, path, "geoparquet.crs.GEOM" -> webMercator) + }) + assert(message.contains("geoparquet.crs.GEOM")) + assert(message.contains("'Geom'") && message.contains("'geom'")) + } + } + } + + it("prefers a CRS option of the write to the Hadoop configuration") { + val hadoop = sparkSession.sparkContext.hadoopConfiguration + // An empty CRS leaves the CRS of the column out of the file + hadoop.set("geoparquet.crs.geometry", "") + try { + withPath { path => + writeVersion2( + udtColumn(pointWithSrid(4326)), + path, + "geoparquet.crs.GEOMETRY" -> webMercator) + assert(parquetCrs(path, "geometry").contains("EPSG:3857")) + } + } finally hadoop.unset("geoparquet.crs.geometry") + } + + it("keeps the limit of the rows held back apart from the CRS options of the columns") { + withPath { path => + val df = udtColumns( + Seq("lookahead.bytes", "other"), + Seq(pointWithSrid(3857), pointWithSrid(4326))) + writeVersion2(df, path, "geoparquet.crs.lookahead.bytes" -> webMercator) + assert(parquetCrs(path, "lookahead.bytes").contains("EPSG:3857")) + assert(parquetCrs(path, "other").isEmpty) + } + } + + it("releases the file when the rows held back until the end show a second SRID") { + // Parquet lists the writers that are open, and offers no public way to read the list + def openWriters: Int = { + val manager = ParquetOutputFormat.getMemoryManager + val writers = manager.getClass.getDeclaredMethod("getWriterList") + writers.setAccessible(true) + writers.invoke(manager).asInstanceOf[java.util.Map[_, _]].size + } + withPath(path => writeVersion2(udtColumn(pointWithSrid(4326)), path)) + val before = openWriters + withPath { path => + // The second column shows no geometry, so the rows are held back until the file ends + val df = udtColumns( + Seq("geometry", "other"), + Seq(pointWithSrid(4326), null), + Seq(pointWithSrid(3857), null)) + val message = messages(intercept[Exception](writeVersion2(df, path))) + assert(message.contains("SRID 4326") && message.contains("SRID 3857")) + } + assert(openWriters == before) + } + + it("writes the row that ends the wait for a geometry as it is") { + val schema = StructType(Seq(StructField("geometry", GeometryUDT()))) + val toUnsafe = UnsafeProjection.create(schema) + def writtenAsGiven( + geometries: Seq[Geometry], + options: (String, String)*): Seq[Boolean] = { + val rows = geometries.map { geometry => + val value = if (geometry == null) null else GeometryUDT().serialize(geometry) + toUnsafe(new GenericInternalRow(Array[Any](value))).copy() + } + RecordingWriteSupport.rows.clear() + withPath { path => + withWriter(path, schema, options.toMap, Some(classOf[RecordingWriteSupport])) { + writer => rows.foreach(writer.write) + } + assert(sridsIn(path).size == geometries.size) + } + rows.zip(RecordingWriteSupport.rows).map { case (given, written) => given eq written } + } + // The row that shows the last geometry waited for opens the file, so only the row before + // it is written from a copy + assert( + writtenAsGiven(Seq(null, pointWithSrid(3857), pointWithSrid(3857))) == + Seq(false, true, true)) + // The row that reaches the limit opens the file too, however large it is + assert( + writtenAsGiven(Seq(null, null), "geoparquet.srid.lookahead.bytes" -> "1") == + Seq(true, true)) + } + + describe("with rows that are not UnsafeRows") { + val schema = + StructType( + Seq(StructField("geometry", GeometryUDT()), StructField("payload", BinaryType))) + def serialized(srid: Int): Any = GeometryUDT().serialize(pointWithSrid(srid)) + + it("holds back a copy that shares no values with the row") { + val payload = Array[Byte](1) + val row = new GenericInternalRow(Array[Any](null, payload)) + withPath { path => + withWriter(path, schema) { writer => + writer.write(row) + // The caller uses the row and its values again for the next one + payload(0) = 2 + row.update(0, serialized(3857)) + writer.write(row) + } + val payloads = sparkSession.read + .format("geoparquet") + .load(path) + .collect() + .map(_.getAs[Array[Byte]]("payload").toSeq) + .toSeq + assert(payloads == Seq(Seq[Byte](1), Seq[Byte](2))) + assert(sridsIn(path) == Seq(None, Some(3857))) + } + } + + it("counts the bytes of a row held back against the limit") { + withPath { path => + val error = intercept[Exception] { + withWriter(path, schema, Map("geoparquet.srid.lookahead.bytes" -> "4096")) { + writer => + // This row alone reaches the limit, so the file opens with an unknown CRS + writer.write(new GenericInternalRow(Array[Any](null, new Array[Byte](8192)))) + writer.write( + new GenericInternalRow(Array[Any](serialized(3857), Array[Byte](1)))) } } + assert(messages(error).contains("had no geometry in the first rows")) } + } } it("writes geospatial statistics for the row groups of a GEOMETRY column") { @@ -360,3 +693,15 @@ class GeoParquetNativeTypesSuite extends TestBaseScala { } } } + +/** Keeps the rows that the Parquet writer gets, to tell a row from a copy of it. */ +class RecordingWriteSupport extends GeoParquetWriteSupport { + override def write(row: InternalRow): Unit = { + RecordingWriteSupport.rows += row + super.write(row) + } +} + +object RecordingWriteSupport { + val rows: mutable.ArrayBuffer[InternalRow] = mutable.ArrayBuffer.empty +} diff --git a/spark/common/src/test/scala/org/apache/sedona/sql/geoparquetIOTests.scala b/spark/common/src/test/scala/org/apache/sedona/sql/geoparquetIOTests.scala index 4a9a826e8ba..7b7a6fce3fb 100644 --- a/spark/common/src/test/scala/org/apache/sedona/sql/geoparquetIOTests.scala +++ b/spark/common/src/test/scala/org/apache/sedona/sql/geoparquetIOTests.scala @@ -1332,6 +1332,47 @@ class geoparquetIOTests extends TestBaseScala with BeforeAndAfterAll { } } + it("GeoParquet gives a covering option to the column that its key names as it is written") { + // In lower case this key is the one of the covering mode + val df = sparkSession + .range(0, 10) + .toDF("id") + .withColumn("id", expr("CAST(id AS DOUBLE)")) + .withColumn("MODE", expr("ST_Point(id, id + 1)")) + .withColumn("other", expr("ST_Point(10 * id, 10 * id + 1)")) + .withColumn( + "test_cov", + expr("struct(id AS xmin, id + 1 AS ymin, id AS xmax, id + 1 AS ymax)")) + val geoParquetSavePath = + geoparquetoutputlocation + "/gp_with_covering_of_column_mode.parquet" + df.write + .format("geoparquet") + .option("geoparquet.covering.MODE", "test_cov") + .mode("overwrite") + .save(geoParquetSavePath) + validateGeoParquetMetadata(geoParquetSavePath) { geo => + implicit val formats: org.json4s.Formats = org.json4s.DefaultFormats + val covering = (geo \ "columns" \ "MODE" \ "covering").extract[Covering] + assert(covering.bbox.xmin == Seq("test_cov", "xmin")) + } + } + + it("GeoParquet takes the covering mode whatever the case of its key") { + val df = sparkSession + .range(0, 10) + .toDF("id") + .withColumn("id", expr("CAST(id AS DOUBLE)")) + .withColumn("geometry", expr("ST_Point(id, id + 1)")) + val geoParquetSavePath = + geoparquetoutputlocation + "/gp_with_covering_mode_in_another_case.parquet" + df.write + .format("geoparquet") + .option("GeoParquet.Covering.Mode", "legacy") + .mode("overwrite") + .save(geoParquetSavePath) + assert(!sparkSession.read.parquet(geoParquetSavePath).columns.contains("geometry_bbox")) + } + it("GeoParquet auto populates covering metadata for multiple geometry columns") { val df = sparkSession .range(0, 100)