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
25 changes: 25 additions & 0 deletions docs/api/sql/Parameter.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.<column_name>` | 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.<column_name>` | 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 `<column_name>_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.
25 changes: 25 additions & 0 deletions docs/api/sql/Parameter.zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.<column_name>` | 单个几何列的 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.<column_name>` | 单个几何列的边界框列 | 见 `geoparquet.covering.mode` | 包含 `xmin`、`ymin`、`xmax`、`ymax` 的顶层 struct 列的名称 | v1.6.1 |
| `geoparquet.covering.mode` | 写出 GeoParquet `1.1.0` 时,如何处理没有 covering 选项的几何列 | `auto` | `auto`(以 `<column_name>_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)。
16 changes: 7 additions & 9 deletions docs/tutorial/files/geoparquet-sedona-spark.md
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,8 @@ The value of `geoparquet.crs` and `geoparquet.crs.<column_name>` 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).
Expand Down Expand Up @@ -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.
Expand All @@ -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.<column_name>`.
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.<column_name>` 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`.

Expand Down
16 changes: 7 additions & 9 deletions docs/tutorial/files/geoparquet-sedona-spark.zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` 字段会被省略。
Expand Down Expand Up @@ -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。
Expand All @@ -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.<column_name>` 给出每个几何列的 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.<column_name>` 可以自行指定 CRS。此时 Sedona 按给定值写出,不再与几何对象的 SRID 比较。

Spark 3.5 和 4.0 自带的 Parquet 库早于 `GEOMETRY` 逻辑类型。Sedona 在这些版本上写出 GeoParquet 1.1,并拒绝把 `geoparquet.version` 设为 `2.0.0`。

Expand Down
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading
Loading