You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sedona.apache.org by ji...@apache.org on 2022/12/30 03:45:46 UTC
[incubator-sedona] branch master updated: [SEDONA-226] Support reading and writing GeoParquet file metadata (#740)
This is an automated email from the ASF dual-hosted git repository.
jiayu pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-sedona.git
The following commit(s) were added to refs/heads/master by this push:
new 8ddd353a [SEDONA-226] Support reading and writing GeoParquet file metadata (#740)
8ddd353a is described below
commit 8ddd353a68aea026e04f9edf7807f9822c2d8384
Author: Kristin Cowalcijk <mo...@yeah.net>
AuthorDate: Fri Dec 30 11:45:41 2022 +0800
[SEDONA-226] Support reading and writing GeoParquet file metadata (#740)
---
.../geoparquet/example-1.0.0-beta.1.parquet | Bin 0 -> 27814 bytes
core/src/test/resources/geoparquet/plain.parquet | Bin 0 -> 2238 bytes
docs/tutorial/sql.md | 20 +---
python/Pipfile | 3 +-
python/tests/sql/test_geoparquet.py | 55 ++++++++++
.../datasources/parquet/GeoParquetFileFormat.scala | 55 ++++++++--
.../datasources/parquet/GeoParquetMetaData.scala | 51 +++++++++
.../datasources/parquet/GeoParquetOptions.scala | 27 -----
.../parquet/GeoParquetReadSupport.scala | 2 +-
.../parquet/GeoParquetSchemaConverter.scala | 36 ++++---
.../parquet/GeoParquetWriteSupport.scala | 102 ++++++++++++++++--
.../datasources/parquet/GeometryField.scala | 28 -----
.../org/apache/sedona/sql/geoparquetIOTests.scala | 116 ++++++++++++++++++---
13 files changed, 376 insertions(+), 119 deletions(-)
diff --git a/core/src/test/resources/geoparquet/example-1.0.0-beta.1.parquet b/core/src/test/resources/geoparquet/example-1.0.0-beta.1.parquet
new file mode 100644
index 00000000..f9efd0d0
Binary files /dev/null and b/core/src/test/resources/geoparquet/example-1.0.0-beta.1.parquet differ
diff --git a/core/src/test/resources/geoparquet/plain.parquet b/core/src/test/resources/geoparquet/plain.parquet
new file mode 100644
index 00000000..188209e1
Binary files /dev/null and b/core/src/test/resources/geoparquet/plain.parquet differ
diff --git a/docs/tutorial/sql.md b/docs/tutorial/sql.md
index b4d0c586..07732f7b 100644
--- a/docs/tutorial/sql.md
+++ b/docs/tutorial/sql.md
@@ -138,7 +138,7 @@ Shapefile and GeoJSON must be loaded by SpatialRDD and converted to DataFrame us
## Load GeoParquet
-Since v`1.3.0`, Sedona natively supports loading GeoParquet file. GeoParquet must be loaded using DataFrame if default name is geometry.
+Since v`1.3.0`, Sedona natively supports loading GeoParquet file. Sedona will infer geometry fields using the "geo" metadata in GeoParquet files.
```Scala
val df = sparkSession.read.format("geoparquet").load(geoparquetdatalocation1)
@@ -155,24 +155,6 @@ root
|-- gdp_md_est: double (nullable = true)
|-- geometry: geometry (nullable = true)
```
-If geometry column name is different
-
-```Scala
-var df = sparkSession.read.format("geoparquet").option("fieldGeometry", "new_geometry").load(geoparquetdatalocation1)
-```
-
-The output will be as follows:
-
-```
-root
- |-- pop_est: long (nullable = true)
- |-- continent: string (nullable = true)
- |-- name: string (nullable = true)
- |-- iso_a3: string (nullable = true)
- |-- gdp_md_est: double (nullable = true)
- |-- new_geometry: geometry (nullable = true)
-```
-
## Transform the Coordinate Reference System
diff --git a/python/Pipfile b/python/Pipfile
index bdf77311..a11eb58b 100644
--- a/python/Pipfile
+++ b/python/Pipfile
@@ -13,9 +13,10 @@ pytest-cov = "*"
[packages]
shapely="==1.8.5"
pandas="*"
-geopandas="==0.6.0"
+geopandas="==0.10.2"
pyspark=">=2.3.0"
attrs="*"
+pyarrow="*"
[requires]
python_version = "3.7"
diff --git a/python/tests/sql/test_geoparquet.py b/python/tests/sql/test_geoparquet.py
new file mode 100644
index 00000000..00e1a160
--- /dev/null
+++ b/python/tests/sql/test_geoparquet.py
@@ -0,0 +1,55 @@
+# 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.
+
+import os.path
+
+from shapely.geometry import Point
+from shapely.geometry import LineString
+from shapely.geometry.base import BaseGeometry
+from shapely.wkt import loads as wkt_loads
+import geopandas
+
+from tests.test_base import TestBase
+
+
+class TestGeoParquet(TestBase):
+ def test_interoperability_with_geopandas(self, tmp_path):
+ test_data = [
+ [1, Point(0, 0), LineString([(1, 2), (3, 4), (5, 6)])],
+ [2, LineString([(1, 2), (3, 4), (5, 6)]), Point(1, 1)],
+ [3, Point(1, 1), LineString([(1, 2), (3, 4), (5, 6)])]
+ ]
+ df = self.spark.createDataFrame(data=test_data, schema=["id", "g0", "g1"]).repartition(1)
+ geoparquet_save_path = os.path.join(tmp_path, "test.parquet")
+ df.write.format("geoparquet").save(geoparquet_save_path)
+
+ # Load geoparquet file written by sedona using geopandas
+ gdf = geopandas.read_parquet(geoparquet_save_path)
+ assert gdf.dtypes['g0'].name == 'geometry'
+ assert gdf.dtypes['g1'].name == 'geometry'
+
+ # Load geoparquet file written by geopandas using sedona
+ gdf = geopandas.GeoDataFrame([
+ {'g': wkt_loads('POINT (1 2)'), 'i': 10},
+ {'g': wkt_loads('LINESTRING (1 2, 3 4)'), 'i': 20}
+ ], geometry='g')
+ geoparquet_save_path2 = os.path.join(tmp_path, "test_2.parquet")
+ gdf.to_parquet(geoparquet_save_path2)
+ df2 = self.spark.read.format("geoparquet").load(geoparquet_save_path2)
+ assert df2.count() == 2
+ row = df2.collect()[0]
+ assert isinstance(row['g'], BaseGeometry)
diff --git a/sql/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/GeoParquetFileFormat.scala b/sql/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/GeoParquetFileFormat.scala
index 8059fc4a..c9fac3f5 100644
--- a/sql/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/GeoParquetFileFormat.scala
+++ b/sql/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/GeoParquetFileFormat.scala
@@ -15,7 +15,8 @@
package org.apache.spark.sql.execution.datasources.parquet
import org.apache.hadoop.conf.Configuration
-import org.apache.hadoop.fs.{FileStatus, Path}
+import org.apache.hadoop.fs.FileStatus
+import org.apache.hadoop.fs.Path
import org.apache.hadoop.mapreduce._
import org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl
import org.apache.parquet.filter2.compat.FilterCompat
@@ -31,6 +32,7 @@ import org.apache.spark.sql._
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions._
import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.catalyst.parser.LegacyTypeStringParser
import org.apache.spark.sql.catalyst.util.DateTimeUtils
import org.apache.spark.sql.execution.datasources._
import org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat.readParquetFootersInParallel
@@ -40,6 +42,9 @@ import org.apache.spark.sql.types._
import org.apache.spark.util.SerializableConfiguration
import java.net.URI
+import scala.collection.JavaConverters._
+import scala.util.Failure
+import scala.util.Try
class GeoParquetFileFormat extends ParquetFileFormat with FileFormat with DataSourceRegister with Logging with Serializable {
@@ -47,12 +52,12 @@ class GeoParquetFileFormat extends ParquetFileFormat with FileFormat with DataSo
override def equals(other: Any): Boolean = other.isInstanceOf[GeoParquetFileFormat]
+ override def hashCode(): Int = getClass.hashCode()
+
override def inferSchema(
sparkSession: SparkSession,
parameters: Map[String, String],
files: Seq[FileStatus]): Option[StructType] = {
- val fieldGeometry = new GeoParquetOptions(parameters).fieldGeometry
- GeometryField.setFieldGeometry(fieldGeometry)
GeoParquetUtils.inferSchema(sparkSession, parameters, files)
}
@@ -302,6 +307,8 @@ class GeoParquetFileFormat extends ParquetFileFormat with FileFormat with DataSo
}
override def supportDataType(dataType: DataType): Boolean = super.supportDataType(dataType)
+
+ override def supportBatch(sparkSession: SparkSession, schema: StructType): Boolean = false
}
object GeoParquetFileFormat extends Logging {
@@ -328,14 +335,46 @@ object GeoParquetFileFormat extends Logging {
val assumeInt96IsTimestamp = sparkSession.sessionState.conf.isParquetINT96AsTimestamp
val reader = (files: Seq[FileStatus], conf: Configuration, ignoreCorruptFiles: Boolean) => {
- // Converter used to convert Parquet `MessageType` to Spark SQL `StructType`
- val converter = new GeoParquetToSparkSchemaConverter(
- assumeBinaryIsString = assumeBinaryIsString,
- assumeInt96IsTimestamp = assumeInt96IsTimestamp)
readParquetFootersInParallel(conf, files, ignoreCorruptFiles)
- .map(ParquetFileFormat.readSchemaFromFooter(_, converter))
+ .map { footer =>
+ // Converter used to convert Parquet `MessageType` to Spark SQL `StructType`
+ val keyValueMetaData = footer.getParquetMetadata.getFileMetaData.getKeyValueMetaData
+ val converter = new GeoParquetToSparkSchemaConverter(
+ keyValueMetaData = keyValueMetaData,
+ assumeBinaryIsString = assumeBinaryIsString,
+ assumeInt96IsTimestamp = assumeInt96IsTimestamp)
+ readSchemaFromFooter(footer, converter)
+ }
}
GeoSchemaMergeUtils.mergeSchemasInParallel(sparkSession, parameters, filesToTouch, reader)
}
+
+ private def readSchemaFromFooter(footer: Footer, converter: GeoParquetToSparkSchemaConverter): StructType = {
+ val fileMetaData = footer.getParquetMetadata.getFileMetaData
+ fileMetaData
+ .getKeyValueMetaData
+ .asScala.toMap
+ .get(ParquetReadSupport.SPARK_METADATA_KEY)
+ .flatMap(deserializeSchemaString)
+ .getOrElse(converter.convert(fileMetaData.getSchema))
+ }
+
+ private def deserializeSchemaString(schemaString: String): Option[StructType] = {
+ // Tries to deserialize the schema string as JSON first, then falls back to the case class
+ // string parser (data generated by older versions of Spark SQL uses this format).
+ Try(DataType.fromJson(schemaString).asInstanceOf[StructType]).recover {
+ case _: Throwable =>
+ logInfo(
+ "Serialized Spark schema in Parquet key-value metadata is not in JSON format, " +
+ "falling back to the deprecated DataType.fromCaseClassString parser.")
+ LegacyTypeStringParser.parseString(schemaString).asInstanceOf[StructType]
+ }.recoverWith {
+ case cause: Throwable =>
+ logWarning(
+ "Failed to parse and ignored serialized Spark schema in " +
+ s"Parquet key-value metadata:\n\t$schemaString", cause)
+ Failure(cause)
+ }.toOption
+ }
}
diff --git a/sql/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/GeoParquetMetaData.scala b/sql/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/GeoParquetMetaData.scala
new file mode 100644
index 00000000..c2419410
--- /dev/null
+++ b/sql/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/GeoParquetMetaData.scala
@@ -0,0 +1,51 @@
+/**
+ *
+ * Licensed 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.parquet
+
+/**
+ * A case class that holds CRS metadata for geometry columns. This class is left empty since CRS
+ * metadata was not implemented yet.
+ */
+case class CRSMetaData()
+
+/**
+ * A case class that holds the metadata of geometry column in GeoParquet metadata
+ * @param encoding Name of the geometry encoding format. Currently only "WKB" is supported
+ * @param geometryTypes The geometry types of all geometries, or an empty array if they are not known.
+ * @param bbox Bounding Box of the geometries in the file, formatted according to RFC 7946, section 5.
+ */
+case class GeometryFieldMetaData(
+ encoding: String,
+ geometryTypes: Seq[String],
+ bbox: Seq[Double],
+ crs: Option[CRSMetaData] = None)
+
+/**
+ * A case class that holds the metadata of GeoParquet file
+ * @param version The version identifier for the GeoParquet specification.
+ * @param primaryColumn The name of the "primary" geometry column.
+ * @param columns Metadata about geometry columns.
+ */
+case class GeoParquetMetaData(
+ version: Option[String], // defined as optional for compatibility with old GeoParquet specs
+ primaryColumn: String,
+ columns: Map[String, GeometryFieldMetaData])
+
+object GeoParquetMetaData {
+ // We're conforming to version 1.0.0-beta.1 of the GeoParquet specification, please refer to
+ // https://github.com/opengeospatial/geoparquet/blob/v1.0.0-beta.1/format-specs/geoparquet.md
+ // for more details.
+ val VERSION = "1.0.0-beta.1"
+}
diff --git a/sql/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/GeoParquetOptions.scala b/sql/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/GeoParquetOptions.scala
deleted file mode 100644
index 9305023e..00000000
--- a/sql/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/GeoParquetOptions.scala
+++ /dev/null
@@ -1,27 +0,0 @@
-/**
- *
- * Licensed 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.parquet
-
-import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
-
-class GeoParquetOptions(@transient private val parameters: CaseInsensitiveMap[String]) extends Serializable {
- def this(parameters: Map[String, String]) = this(CaseInsensitiveMap(parameters))
- /**
- * geometry field name. Default: geometry
- */
-
- val fieldGeometry = parameters.getOrElse("fieldGeometry", "geometry")
-
-}
diff --git a/sql/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/GeoParquetReadSupport.scala b/sql/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/GeoParquetReadSupport.scala
index ff2dce75..275cf071 100644
--- a/sql/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/GeoParquetReadSupport.scala
+++ b/sql/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/GeoParquetReadSupport.scala
@@ -121,7 +121,7 @@ class GeoParquetReadSupport (
new GeoParquetRecordMaterializer(
parquetRequestedSchema,
GeoParquetReadSupport.expandUDT(catalystRequestedSchema),
- new GeoParquetToSparkSchemaConverter(conf),
+ new GeoParquetToSparkSchemaConverter(keyValueMetaData, conf),
convertTz,
datetimeRebaseMode,
int96RebaseMode)
diff --git a/sql/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/GeoParquetSchemaConverter.scala b/sql/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/GeoParquetSchemaConverter.scala
index 5e20bcb1..3ca1d948 100644
--- a/sql/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/GeoParquetSchemaConverter.scala
+++ b/sql/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/GeoParquetSchemaConverter.scala
@@ -28,6 +28,7 @@ import org.apache.spark.sql.execution.datasources.parquet.ParquetSchemaConverter
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.sedona_sql.UDT.GeometryUDT
import org.apache.spark.sql.types._
+import org.json4s.jackson.JsonMethods.parse
/**
* This converter class is used to convert Parquet [[MessageType]] to Spark SQL [[StructType]].
@@ -43,23 +44,33 @@ import org.apache.spark.sql.types._
* [[TimestampType]] fields.
*/
class GeoParquetToSparkSchemaConverter(
- assumeBinaryIsString: Boolean = SQLConf.PARQUET_BINARY_AS_STRING.defaultValue.get,
- assumeInt96IsTimestamp: Boolean = SQLConf.PARQUET_INT96_AS_TIMESTAMP.defaultValue.get)
-extends ParquetToSparkSchemaConverter(assumeBinaryIsString, assumeInt96IsTimestamp) {
+ keyValueMetaData: java.util.Map[String, String],
+ assumeBinaryIsString: Boolean = SQLConf.PARQUET_BINARY_AS_STRING.defaultValue.get,
+ assumeInt96IsTimestamp: Boolean = SQLConf.PARQUET_INT96_AS_TIMESTAMP.defaultValue.get) {
+
+ private val geoParquetMetaData: GeoParquetMetaData = {
+ val geo = keyValueMetaData.get("geo")
+ if (geo == null) {
+ throw new AnalysisException("GeoParquet file does not contain valid geo metadata")
+ }
+ implicit val formats: org.json4s.Formats = org.json4s.DefaultFormats
+ parse(geo).camelizeKeys.extract[GeoParquetMetaData]
+ }
- def this(conf: SQLConf) = this(
+ def this(keyValueMetaData: java.util.Map[String, String], conf: SQLConf) = this(
+ keyValueMetaData = keyValueMetaData,
assumeBinaryIsString = conf.isParquetBinaryAsString,
assumeInt96IsTimestamp = conf.isParquetINT96AsTimestamp)
- def this(conf: Configuration) = this(
+ def this(keyValueMetaData: java.util.Map[String, String], conf: Configuration) = this(
+ keyValueMetaData = keyValueMetaData,
assumeBinaryIsString = conf.get(SQLConf.PARQUET_BINARY_AS_STRING.key).toBoolean,
assumeInt96IsTimestamp = conf.get(SQLConf.PARQUET_INT96_AS_TIMESTAMP.key).toBoolean)
-
/**
* Converts Parquet [[MessageType]] `parquetSchema` to a Spark SQL [[StructType]].
*/
- override def convert(parquetSchema: MessageType): StructType = convert(parquetSchema.asGroupType())
+ def convert(parquetSchema: MessageType): StructType = convert(parquetSchema.asGroupType())
private def convert(parquetSchema: GroupType): StructType = {
val fields = parquetSchema.getFields.asScala.map { field =>
@@ -90,6 +101,9 @@ extends ParquetToSparkSchemaConverter(assumeBinaryIsString, assumeInt96IsTimesta
case t: GroupType => convertGroupField(t.asGroupType())
}
+ private def isGeometryField(fieldName: String): Boolean =
+ geoParquetMetaData.columns.contains(fieldName)
+
private def convertPrimitiveField(field: PrimitiveType): DataType = {
val typeName = field.getPrimitiveTypeName
val originalType = field.getOriginalType
@@ -161,7 +175,7 @@ extends ParquetToSparkSchemaConverter(assumeBinaryIsString, assumeInt96IsTimesta
case BINARY =>
originalType match {
case UTF8 | ENUM | JSON => StringType
- case null if GeoParquetSchemaConverter.checkGeomFieldName(field.getName) => GeometryUDT
+ case null if isGeometryField(field.getName) => GeometryUDT
case null if assumeBinaryIsString => StringType
case null => BinaryType
case BSON => BinaryType
@@ -558,12 +572,6 @@ extends SparkToParquetSchemaConverter(writeLegacyParquetFormat, outputTimestampT
}
private[sql] object GeoParquetSchemaConverter {
- def checkGeomFieldName(name: String): Boolean = {
- if (name.equals(GeometryField.getFieldGeometry())) {
- true
- } else false
- }
-
def checkFieldName(name: String): Unit = {
// ,;{}()\n\t= and space are special characters in Parquet schema
checkConversionRequirement(
diff --git a/sql/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/GeoParquetWriteSupport.scala b/sql/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/GeoParquetWriteSupport.scala
index 9f14c443..30f04f5d 100644
--- a/sql/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/GeoParquetWriteSupport.scala
+++ b/sql/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/GeoParquetWriteSupport.scala
@@ -17,13 +17,12 @@
package org.apache.spark.sql.execution.datasources.parquet
-import java.nio.{ByteBuffer, ByteOrder}
-import java.util
-import scala.collection.JavaConverters.mapAsJavaMapConverter
import org.apache.hadoop.conf.Configuration
import org.apache.parquet.hadoop.api.WriteSupport
+import org.apache.parquet.hadoop.api.WriteSupport.FinalizedWriteContext
import org.apache.parquet.hadoop.api.WriteSupport.WriteContext
-import org.apache.parquet.io.api.{Binary, RecordConsumer}
+import org.apache.parquet.io.api.Binary
+import org.apache.parquet.io.api.RecordConsumer
import org.apache.sedona.common.utils.GeomUtils
import org.apache.spark.SPARK_VERSION_SHORT
import org.apache.spark.internal.Logging
@@ -31,12 +30,23 @@ import org.apache.spark.sql.SPARK_VERSION_METADATA_KEY
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.execution.datasources.parquet.GeoParquetWriteSupport.GeometryColumnInfo
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.internal.SQLConf.LegacyBehaviorPolicy
import org.apache.spark.sql.sedona_sql.UDT.GeometryUDT
import org.apache.spark.sql.types._
+import org.json4s.DefaultFormats
+import org.json4s.Extraction
+import org.json4s.jackson.compactJson
+import org.locationtech.jts.geom.Geometry
import org.locationtech.jts.io.WKBWriter
+import java.nio.ByteBuffer
+import java.nio.ByteOrder
+import java.util
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+
/**
* A Parquet [[WriteSupport]] implementation that writes Catalyst [[InternalRow]]s as Parquet
* messages. This class can write Parquet data in two modes:
@@ -91,6 +101,11 @@ class GeoParquetWriteSupport extends WriteSupport[InternalRow] with Logging {
private val int96RebaseFunc = GeoDataSourceUtils.creteTimestampRebaseFuncInWrite(
int96RebaseMode, "Parquet INT96")
+ // A mapping from geometry field ordinal to bounding box. According to the geoparquet specification,
+ // "Geometry columns MUST be at the root of the schema", so we don't need to worry about geometry
+ // fields in nested structures.
+ private val geometryColumnInfoMap: mutable.Map[Int, GeometryColumnInfo] = mutable.Map.empty
+
override def init(configuration: Configuration): WriteContext = {
val schemaString = configuration.get(ParquetWriteSupport.SPARK_ROW_SCHEMA)
this.schema = StructType.fromString(schemaString)
@@ -106,7 +121,13 @@ class GeoParquetWriteSupport extends WriteSupport[InternalRow] with Logging {
SQLConf.ParquetOutputTimestampType.withName(configuration.get(key))
}
- this.rootFieldWriters = schema.map(_.dataType).map(makeWriter).toArray[ValueWriter]
+ this.rootFieldWriters = schema.zipWithIndex.map { case (field, ordinal) =>
+ makeWriter(field.dataType, Some(ordinal))
+ }.toArray[ValueWriter]
+
+ if (geometryColumnInfoMap.isEmpty) {
+ throw new RuntimeException("No geometry column found in the schema")
+ }
val messageType = new SparkToParquetSchemaConverter(configuration).convert(schema)
val metadata = Map(
@@ -140,6 +161,27 @@ class GeoParquetWriteSupport extends WriteSupport[InternalRow] with Logging {
this.recordConsumer = recordConsumer
}
+ override def finalizeWrite(): WriteSupport.FinalizedWriteContext = {
+ val metadata = new util.HashMap[String, String]()
+ if (geometryColumnInfoMap.nonEmpty) {
+ val primaryColumnIndex = geometryColumnInfoMap.keys.head
+ val primaryColumn = schema.fields(primaryColumnIndex).name
+ val columns = geometryColumnInfoMap.map { case (ordinal, columnInfo) =>
+ val columnName = schema.fields(ordinal).name
+ val geometryTypes = columnInfo.seenGeometryTypes.toSeq
+ val bbox = if (geometryTypes.nonEmpty) {
+ Seq(columnInfo.bbox.minX, columnInfo.bbox.minY, columnInfo.bbox.maxX, columnInfo.bbox.maxY)
+ } else Seq(0.0, 0.0, 0.0, 0.0)
+ columnName -> GeometryFieldMetaData("WKB", geometryTypes, bbox)
+ }.toMap
+ val geoParquetMetadata = GeoParquetMetaData(Some(GeoParquetMetaData.VERSION), primaryColumn, columns)
+ implicit val formats: org.json4s.Formats = DefaultFormats.preservingEmptyValues
+ val geoParquetMetadataJson = compactJson(Extraction.decompose(geoParquetMetadata).underscoreKeys)
+ metadata.put("geo", geoParquetMetadataJson)
+ }
+ new FinalizedWriteContext(metadata)
+ }
+
override def write(row: InternalRow): Unit = {
consumeMessage {
writeFields(row, schema, rootFieldWriters)
@@ -159,7 +201,7 @@ class GeoParquetWriteSupport extends WriteSupport[InternalRow] with Logging {
}
}
- private def makeWriter(dataType: DataType): ValueWriter = {
+ private def makeWriter(dataType: DataType, rootOrdinal: Option[Int] = None): ValueWriter = {
dataType match {
case BooleanType =>
(row: SpecializedGetters, ordinal: Int) =>
@@ -228,7 +270,7 @@ class GeoParquetWriteSupport extends WriteSupport[InternalRow] with Logging {
makeDecimalWriter(precision, scale)
case t: StructType =>
- val fieldWriters = t.map(_.dataType).map(makeWriter).toArray[ValueWriter]
+ val fieldWriters = t.map(_.dataType).map(makeWriter(_, None)).toArray[ValueWriter]
(row: SpecializedGetters, ordinal: Int) =>
consumeGroup {
writeFields(row.getStruct(ordinal, t.length), t, fieldWriters)
@@ -239,11 +281,20 @@ class GeoParquetWriteSupport extends WriteSupport[InternalRow] with Logging {
case t: MapType => makeMapWriter(t)
case GeometryUDT =>
- (row: SpecializedGetters, ordinal: Int) =>
+ val geometryColumnInfo = rootOrdinal match {
+ case Some(ordinal) =>
+ geometryColumnInfoMap.getOrElseUpdate(ordinal, new GeometryColumnInfo())
+ case None => null
+ }
+ (row: SpecializedGetters, ordinal: Int) => {
val serializedGeometry = row.getBinary(ordinal)
val geom = GeometryUDT.deserialize(serializedGeometry)
val wkbWriter = new WKBWriter(GeomUtils.getDimension(geom))
recordConsumer.addBinary(Binary.fromReusedByteArray(wkbWriter.write(geom)))
+ if (geometryColumnInfo != null) {
+ geometryColumnInfo.update(geom)
+ }
+ }
case t: UserDefinedType[_] => makeWriter(t.sqlType)
@@ -481,3 +532,38 @@ class GeoParquetWriteSupport extends WriteSupport[InternalRow] with Logging {
recordConsumer.endField(field, index)
}
}
+
+object GeoParquetWriteSupport {
+ class GeometryColumnInfo {
+ val bbox: GeometryColumnBoundingBox = new GeometryColumnBoundingBox()
+
+ // GeoParquet column metadata has a `geometry_types` property, which contains a list of geometry types
+ // that are present in the column.
+ val seenGeometryTypes: mutable.Set[String] = mutable.Set.empty
+
+ def update(geom: Geometry): Unit = {
+ bbox.update(geom)
+ // In case of 3D geometries, a " Z" suffix gets added (e.g. ["Point Z"]).
+ val hasZ = {
+ val coordinate = geom.getCoordinate
+ if (coordinate != null) !coordinate.getZ.isNaN else false
+ }
+ val geometryType = if (!hasZ) geom.getGeometryType else geom.getGeometryType + " Z"
+ seenGeometryTypes.add(geometryType)
+ }
+ }
+
+ class GeometryColumnBoundingBox(
+ var minX: Double = Double.PositiveInfinity,
+ var minY: Double = Double.PositiveInfinity,
+ var maxX: Double = Double.NegativeInfinity,
+ var maxY: Double = Double.NegativeInfinity) {
+ def update(geom: Geometry): Unit = {
+ val env = geom.getEnvelopeInternal
+ minX = math.min(minX, env.getMinX)
+ minY = math.min(minY, env.getMinY)
+ maxX = math.max(maxX, env.getMaxX)
+ maxY = math.max(maxY, env.getMaxY)
+ }
+ }
+}
diff --git a/sql/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/GeometryField.scala b/sql/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/GeometryField.scala
deleted file mode 100644
index 65f52c05..00000000
--- a/sql/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/GeometryField.scala
+++ /dev/null
@@ -1,28 +0,0 @@
-/**
- *
- * Licensed 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.parquet
-
-object GeometryField {
-
- var fieldGeometry: String = ""
-
- def getFieldGeometry(): String ={
- fieldGeometry
- }
-
- def setFieldGeometry(fieldName: String): Unit ={
- fieldGeometry = fieldName
- }
-}
\ No newline at end of file
diff --git a/sql/src/test/scala/org/apache/sedona/sql/geoparquetIOTests.scala b/sql/src/test/scala/org/apache/sedona/sql/geoparquetIOTests.scala
index ad4995dd..cdb15f55 100644
--- a/sql/src/test/scala/org/apache/sedona/sql/geoparquetIOTests.scala
+++ b/sql/src/test/scala/org/apache/sedona/sql/geoparquetIOTests.scala
@@ -19,16 +19,31 @@
package org.apache.sedona.sql
import org.apache.commons.io.FileUtils
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.fs.Path
+import org.apache.parquet.hadoop.ParquetFileReader
+import org.apache.parquet.hadoop.util.HadoopInputFile
+import org.apache.spark.SparkException
+import org.apache.spark.sql.Row
import org.apache.spark.sql.SaveMode
+import org.apache.spark.sql.sedona_sql.UDT.GeometryUDT
+import org.apache.spark.sql.types.IntegerType
+import org.apache.spark.sql.types.StructField
+import org.apache.spark.sql.types.StructType
+import org.json4s.jackson.parseJson
import org.locationtech.jts.geom.Geometry
+import org.locationtech.jts.io.WKTReader
import org.scalatest.BeforeAndAfterAll
import java.io.File
+import java.util.Collections
+import scala.collection.JavaConverters._
class geoparquetIOTests extends TestBaseScala with BeforeAndAfterAll {
val geoparquetdatalocation1: String = resourceFolder + "geoparquet/example1.parquet"
val geoparquetdatalocation2: String = resourceFolder + "geoparquet/example2.parquet"
val geoparquetdatalocation3: String = resourceFolder + "geoparquet/example3.parquet"
+ val geoparquetdatalocation4: String = resourceFolder + "geoparquet/example-1.0.0-beta.1.parquet"
val geoparquetoutputlocation: String = resourceFolder + "geoparquet/geoparquet_output/"
override def afterAll(): Unit = FileUtils.deleteDirectory(new File(geoparquetoutputlocation))
@@ -60,7 +75,7 @@ class geoparquetIOTests extends TestBaseScala with BeforeAndAfterAll {
assert(newrows.getAs[Geometry]("geometry").toString == "POINT (12.453386544971766 41.903282179960115)")
}
it("GEOPARQUET Test example3 i.e. nybb dataset's Read and Write"){
- val df=sparkSession.read.format("geoparquet").load(geoparquetdatalocation3)
+ val df = sparkSession.read.format("geoparquet").load(geoparquetdatalocation3)
val rows = df.collect()(0)
assert(rows.getAs[Long]("BoroCode") == 5)
assert(rows.getAs[String]("BoroName") == "Staten Island")
@@ -72,18 +87,93 @@ class geoparquetIOTests extends TestBaseScala with BeforeAndAfterAll {
val newrows = df2.collect()(0)
assert(newrows.getAs[Geometry]("geometry").toString.startsWith("MULTIPOLYGON (((970217.022"))
}
- it("GEOPARQUET Test example3 i.e. nybb dataset's Read and Write Options"){
- val df=sparkSession.read.format("geoparquet").option("fieldGeometry", "geometry").load(geoparquetdatalocation3)
- val rows = df.collect()(0)
- assert(rows.getAs[Long]("BoroCode") == 5)
- assert(rows.getAs[String]("BoroName") == "Staten Island")
- assert(rows.getAs[Double]("Shape_Leng") == 330470.010332)
- assert(rows.getAs[Double]("Shape_Area") == 1.62381982381E9)
- assert(rows.getAs[Geometry]("geometry").toString.startsWith("MULTIPOLYGON (((970217.022"))
- df.write.format("geoparquet").mode(SaveMode.Overwrite).save(geoparquetoutputlocation + "/gp_sample3o.parquet")
- val df2 = sparkSession.read.format("geoparquet").load(geoparquetoutputlocation + "/gp_sample3.parquet")
- val newrows = df2.collect()(0)
- assert(newrows.getAs[Geometry]("geometry").toString.startsWith("MULTIPOLYGON (((970217.022"))
+ it("GEOPARQUET Test example-1.0.0-beta.1.parquet") {
+ val df = sparkSession.read.format("geoparquet").load(geoparquetdatalocation4)
+ val count = df.count()
+ val rows = df.collect()
+ assert(rows(0).getAs[AnyRef]("geometry").isInstanceOf[Geometry])
+ assert(count == rows.length)
+ df.write.format("geoparquet").mode(SaveMode.Overwrite).save(geoparquetoutputlocation + "/gp_sample4.parquet")
+ val df2 = sparkSession.read.format("geoparquet").load(geoparquetoutputlocation + "/gp_sample4.parquet")
+ val newRows = df2.collect()
+ assert(rows.length == newRows.length)
+ assert(newRows(0).getAs[AnyRef]("geometry").isInstanceOf[Geometry])
+ assert(rows sameElements newRows)
+ }
+
+ it("GeoParquet with multiple geometry columns") {
+ val wktReader = new WKTReader()
+ val testData = Seq(
+ Row(1, wktReader.read("POINT (1 2)"), wktReader.read("POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))")),
+ Row(2, wktReader.read("POINT Z(1 2 3)"), wktReader.read("POLYGON Z((0 0 2, 1 0 2, 1 1 2, 0 1 2, 0 0 2))")),
+ Row(3, wktReader.read("MULTIPOINT (0 0, 1 1, 2 2)"), wktReader.read("MULTILINESTRING ((0 0, 1 1), (2 2, 3 3))"))
+ )
+ val schema = StructType(Seq(
+ StructField("id", IntegerType, nullable = false),
+ StructField("g0", GeometryUDT, nullable = false),
+ StructField("g1", GeometryUDT, nullable = false)
+ ))
+ val df = sparkSession.createDataFrame(testData.asJava, schema).repartition(1)
+ val geoParquetSavePath = geoparquetoutputlocation + "/multi_geoms.parquet"
+ df.write.format("geoparquet").save(geoParquetSavePath)
+
+ // Find parquet files in geoParquetSavePath directory and validate their metadata
+ val parquetFiles = new File(geoParquetSavePath).listFiles().filter(_.getName.endsWith(".parquet"))
+ parquetFiles.foreach { filePath =>
+ val metadata = ParquetFileReader.open(
+ HadoopInputFile.fromPath(new Path(filePath.getPath), new Configuration()))
+ .getFooter.getFileMetaData.getKeyValueMetaData
+ assert(metadata.containsKey("geo"))
+ val geo = parseJson(metadata.get("geo"))
+ implicit val formats : org.json4s.Formats = org.json4s.DefaultFormats
+ val g0Types = (geo \ "columns" \ "g0" \ "geometry_types").extract[Seq[String]]
+ val g1Types = (geo \ "columns" \ "g1" \ "geometry_types").extract[Seq[String]]
+ assert(g0Types.sorted == Seq("Point", "Point Z", "MultiPoint").sorted)
+ assert(g1Types.sorted == Seq("Polygon", "Polygon Z", "MultiLineString").sorted)
+ }
+
+ // Read GeoParquet with multiple geometry columns
+ val df2 = sparkSession.read.format("geoparquet").load(geoParquetSavePath)
+ assert(df2.schema.fields(1).dataType.isInstanceOf[GeometryUDT])
+ assert(df2.schema.fields(2).dataType.isInstanceOf[GeometryUDT])
+ val rows = df2.collect()
+ assert(testData.length == rows.length)
+ assert(rows(0).getAs[AnyRef]("g0").isInstanceOf[Geometry])
+ assert(rows(0).getAs[AnyRef]("g1").isInstanceOf[Geometry])
+ }
+
+ it("GeoParquet save should work with empty dataframes") {
+ val schema = StructType(Seq(
+ StructField("id", IntegerType, nullable = false),
+ StructField("g", GeometryUDT, nullable = false)
+ ))
+ val df = sparkSession.createDataFrame(Collections.emptyList[Row](), schema)
+ val geoParquetSavePath = geoparquetoutputlocation + "/empty.parquet"
+ df.write.format("geoparquet").save(geoParquetSavePath)
+ val df2 = sparkSession.read.format("geoparquet").load(geoParquetSavePath)
+ assert(df2.schema.fields(1).dataType.isInstanceOf[GeometryUDT])
+ assert(0 == df2.count())
+
+ val parquetFiles = new File(geoParquetSavePath).listFiles().filter(_.getName.endsWith(".parquet"))
+ parquetFiles.foreach { filePath =>
+ val metadata = ParquetFileReader.open(
+ HadoopInputFile.fromPath(new Path(filePath.getPath), new Configuration()))
+ .getFooter.getFileMetaData.getKeyValueMetaData
+ assert(metadata.containsKey("geo"))
+ val geo = parseJson(metadata.get("geo"))
+ implicit val formats: org.json4s.Formats = org.json4s.DefaultFormats
+ val g0Types = (geo \ "columns" \ "g" \ "geometry_types").extract[Seq[String]]
+ val g0BBox = (geo \ "columns" \ "g" \ "bbox").extract[Seq[Double]]
+ assert(g0Types.isEmpty)
+ assert(g0BBox == Seq(0.0, 0.0, 0.0, 0.0))
+ }
+ }
+
+ it("GeoParquet load should raise exception when loading plain parquet files") {
+ val e = intercept[SparkException] {
+ sparkSession.read.format("geoparquet").load(resourceFolder + "geoparquet/plain.parquet")
+ }
+ assert(e.getMessage.contains("does not contain valid geo metadata"))
}
}
}