Skip to content
Closed
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
1 change: 1 addition & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@
<jackson.version>2.13.4</jackson.version>
<jts.version>1.20.0</jts.version>
<jts.io.patch.version>1.21.0-datasyslab-3</jts.io.patch.version>
<sedona.spatial.type.impl>legacy</sedona.spatial.type.impl>
<jts2geojson.version>0.16.1</jts2geojson.version>
<spatial4j.version>0.8</spatial4j.version>

Expand Down
22 changes: 22 additions & 0 deletions spark/common/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,7 @@
<configuration>
<sources>
<source>src/main/scala-spark-${spark.major.version}</source>
<source>src/main/scala-spatial-${sedona.spatial.type.impl}</source>
</sources>
</configuration>
</execution>
Expand All @@ -334,6 +335,27 @@
<plugin>
<groupId>org.scalastyle</groupId>
<artifactId>scalastyle-maven-plugin</artifactId>
<configuration>
<sourceDirectories>
<sourceDirectory>${project.basedir}/src/main/scala</sourceDirectory>
<sourceDirectory>${project.basedir}/src/main/scala-spatial-${sedona.spatial.type.impl}</sourceDirectory>
</sourceDirectories>
</configuration>
</plugin>
<plugin>
<groupId>com.diffplug.spotless</groupId>
<artifactId>spotless-maven-plugin</artifactId>
<configuration>
<scala>
<includes>
<include>src/main/scala/**/*.scala</include>
<include>src/test/scala/**/*.scala</include>
<include>src/main/scala/**/*.sc</include>
<include>src/test/scala/**/*.sc</include>
<include>src/main/scala-spatial-${sedona.spatial.type.impl}/**/*.scala</include>
</includes>
</scala>
</configuration>
</plugin>
</plugins>
</build>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.spark.sql.sedona_sql.types

import org.apache.spark.sql.catalyst.expressions.SpecializedGetters
import org.apache.spark.sql.sedona_sql.UDT.GeometryUDT
import org.apache.spark.sql.types.DataType
import org.locationtech.jts.geom.Geometry

/** Version-selected geometry boundary used by the DataFrame/RDD adapters. */
object SpatialTypeSupport {
def geometryType: DataType = GeometryUDT()
def isGeometry(dataType: DataType): Boolean = dataType.isInstanceOf[GeometryUDT]
def externalGeometry(value: Geometry): Any = value
def externalGeometry(value: Geometry, dataType: DataType): Any = value
def fromExternalGeometry(value: Any): Geometry = value.asInstanceOf[Geometry]
def readGeometry(row: SpecializedGetters, ordinal: Int, dataType: DataType): Geometry =
if (row.isNullAt(ordinal)) null else GeometryUDT.deserialize(row.get(ordinal, dataType))
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import org.apache.sedona.core.spatialRDD.SpatialRDD
import java.sql.{Date, Timestamp}
import org.apache.spark.api.java.JavaPairRDD
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.sedona_sql.UDT.GeometryUDT
import org.apache.spark.sql.sedona_sql.types.SpatialTypeSupport
import org.apache.spark.sql.types._
import org.apache.spark.sql.{DataFrame, Row, SparkSession}
import org.apache.spark.sql.catalyst.expressions.GenericRowWithSchema
Expand Down Expand Up @@ -141,9 +141,12 @@ object Adapter {
sparkSession: SparkSession): DataFrame = {
val rowRdd = spatialRDD.rawSpatialRDD.rdd.map[Row](geom => {
val stringRow = extractUserData(geom)
Row.fromSeq(stringRow)
Row.fromSeq(stringRow.map {
case geometry: Geometry => SpatialTypeSupport.externalGeometry(geometry)
case value => value
})
})
var cols: Seq[StructField] = Seq(StructField("geometry", GeometryUDT()))
var cols: Seq[StructField] = Seq(StructField("geometry", SpatialTypeSupport.geometryType))
if (fieldNames != null && fieldNames.nonEmpty) {
cols = cols ++ fieldNames.map(f => StructField(f, StringType))
}
Expand Down Expand Up @@ -193,12 +196,15 @@ object Adapter {
row = f,
leftFieldnames = leftFieldnames,
rightFieldnames = rightFieldNames)
Row.fromSeq(stringRow)
Row.fromSeq(stringRow.map {
case geometry: Geometry => SpatialTypeSupport.externalGeometry(geometry)
case value => value
})
})
var cols: Seq[StructField] = Seq(StructField("leftgeometry", GeometryUDT()))
var cols: Seq[StructField] = Seq(StructField("leftgeometry", SpatialTypeSupport.geometryType))
if (leftFieldnames != null && leftFieldnames.nonEmpty)
cols = cols ++ leftFieldnames.map(fName => StructField(fName, StringType))
cols = cols ++ Seq(StructField("rightgeometry", GeometryUDT()))
cols = cols ++ Seq(StructField("rightgeometry", SpatialTypeSupport.geometryType))
if (rightFieldNames != null && rightFieldNames.nonEmpty)
cols = cols ++ rightFieldNames.map(fName => StructField(fName, StringType))
val schema = StructType(cols)
Expand Down Expand Up @@ -292,7 +298,7 @@ object Adapter {

private def toRdd(dataFrame: DataFrame, geometryColId: Int): RDD[Geometry] = {
dataFrame.rdd.map[Geometry](f => {
var geometry = f.get(geometryColId).asInstanceOf[Geometry]
val geometry = SpatialTypeSupport.fromExternalGeometry(f.get(geometryColId))
var fieldSize = f.size
var userData: String = null
if (fieldSize > 1) {
Expand Down Expand Up @@ -333,7 +339,9 @@ object Adapter {
val parsedRow = stringRow.zipWithIndex.map { case (value, idx) =>
val desiredDataType = schema(idx).dataType
// Don't convert geometry data, only user data
if (desiredDataType == GeometryUDT) value else parseString(value.toString, desiredDataType)
if (SpatialTypeSupport.isGeometry(desiredDataType))
SpatialTypeSupport.externalGeometry(value.asInstanceOf[Geometry], desiredDataType)
else parseString(value.toString, desiredDataType)
}

Row.fromSeq(parsedRow)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@
*/
package org.apache.sedona.util

import org.apache.spark.sql.sedona_sql.UDT.GeometryUDT
import org.apache.spark.sql.sedona_sql.types.SpatialTypeSupport
import org.apache.spark.sql.types.StructType

object DfUtils {
def getGeometryColumnName(schema: StructType): String = {
val geomFields = schema.fields.filter(_.dataType == GeometryUDT)
val geomFields = schema.fields.filter(field => SpatialTypeSupport.isGeometry(field.dataType))

if (geomFields.isEmpty)
throw new IllegalArgumentException(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,15 @@ package org.apache.spark.sql.sedona_sql.adapters

import org.apache.sedona.core.spatialPartitioning.GenericUniquePartitioner
import org.apache.sedona.core.spatialRDD.SpatialRDD
import org.apache.sedona.sql.utils.GeometrySerializer
import org.apache.sedona.util.DfUtils
import org.apache.spark.api.java.JavaPairRDD
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.types.{DataType, StructType}
import org.apache.spark.sql.{DataFrame, Row, SparkSession}
import org.apache.spark.sql.sedona_sql.DataFrameShims
import org.locationtech.jts.geom.Geometry
import org.apache.spark.sql.sedona_sql.types.SpatialTypeSupport
import org.locationtech.jts.geom.{Geometry, GeometryFactory}
import org.slf4j.{Logger, LoggerFactory}

/**
Expand All @@ -53,7 +53,7 @@ object StructuredAdapter {
} else spatialRDD.schema = rdd.first().schema
spatialRDD.rawSpatialRDD = rdd
.map(row => {
val geom = row.getAs[Geometry](geometryFieldName)
val geom = SpatialTypeSupport.fromExternalGeometry(row.getAs[Any](geometryFieldName))
geom.setUserData(row.copy())
geom
})
Expand Down Expand Up @@ -108,9 +108,12 @@ object StructuredAdapter {
val spatialRDD = new SpatialRDD[Geometry]
spatialRDD.schema = schema
val ordinal = spatialRDD.schema.fieldIndex(geometryFieldName)
val geometryType = schema(ordinal).dataType
spatialRDD.rawSpatialRDD = rdd
.map(row => {
val geom = GeometrySerializer.deserialize(row.getBinary(ordinal))
// Keep the existing empty carrier for null internal geometry; user data retains the null.
val geom = Option(SpatialTypeSupport.readGeometry(row, ordinal, geometryType))
.getOrElse(new GeometryFactory().createGeometryCollection())
geom.setUserData(row.copy())
geom
})
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
/*
* 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.sedona.sql

import org.apache.sedona.common.S2Geography.WKBGeography
import org.apache.sedona.core.spatialRDD.SpatialRDD
import org.apache.sedona.sql.utils.Adapter
import org.apache.sedona.util.DfUtils
import org.apache.spark.sql.Row
import org.apache.spark.sql.sedona_sql.UDT.{GeographyUDT, GeometryUDT}
import org.apache.spark.sql.sedona_sql.adapters.StructuredAdapter
import org.apache.spark.sql.types._
import org.locationtech.jts.geom.{Coordinate, Geometry, GeometryFactory, PrecisionModel}

class SpatialAdapterBoundaryTest extends TestBaseScala {
private def point(x: Double): Geometry =
new GeometryFactory(new PrecisionModel(), 4326).createPoint(new Coordinate(x, 2))

describe("spatial adapter boundaries") {
it("preserves the default geometry schema and string attributes through Adapter") {
val geometry = point(1)
geometry.setUserData("alpha\t")
val spatialRDD = new SpatialRDD[Geometry]
spatialRDD.rawSpatialRDD = sc.parallelize(Seq(geometry)).toJavaRDD()
val frame = Adapter.toDf(spatialRDD, Seq("label", "empty"), sparkSession)
assert(
frame.schema == StructType(
Seq(
StructField("geometry", GeometryUDT()),
StructField("label", StringType),
StructField("empty", StringType))))
val row = frame.head()
assert(row.getAs[Geometry](0).getSRID == 4326)
assert(row.getString(1) == "alpha")
assert(row.getString(2) == "")
val restored = Adapter.toSpatialRdd(frame, "geometry").rawSpatialRDD.first()
assert(restored.equalsExact(geometry))
assert(restored.getUserData == "alpha\t")
assert(geometry.getUserData == "alpha\t")
}

it("preserves an explicitly requested GeometryUDT schema") {
val geometry = point(3)
geometry.setUserData("7")
val spatialRDD = new SpatialRDD[Geometry]
spatialRDD.rawSpatialRDD = sc.parallelize(Seq(geometry)).toJavaRDD()
val schema =
StructType(Seq(StructField("shape", GeometryUDT()), StructField("number", IntegerType)))
val frame = Adapter.toDf(spatialRDD, schema, sparkSession)
assert(frame.schema == schema)
assert(frame.head().getAs[Geometry](0).equalsExact(geometry))
assert(frame.head().getInt(1) == 7)
}

it("keeps full rows and geography values through StructuredAdapter") {
val geometry = point(4)
val geography = WKBGeography.fromJTS(point(5))
val schema = StructType(
Seq(
StructField("id", IntegerType, nullable = false),
StructField("shape", GeometryUDT()),
StructField("globe", GeographyUDT()),
StructField("label", StringType)))
val source = sparkSession.createDataFrame(
sc.parallelize(Seq(Row(7, geometry, geography, null))),
schema)
val spatialRDD = StructuredAdapter.toSpatialRdd(source)
val converted = StructuredAdapter.toDf(spatialRDD, sparkSession)
assert(converted.schema == schema)
val row = converted.head()
assert(row.getInt(0) == 7)
assert(row.getAs[Geometry](1).equalsExact(geometry))
assert(row.getAs[WKBGeography](2).getSRID == 4326)
assert(row.getAs[WKBGeography](2).getWKBBytes.sameElements(geography.getWKBBytes))
assert(row.isNullAt(3))
val fromRows = StructuredAdapter.toSpatialRdd(source.rdd, "shape")
val restoredRow = StructuredAdapter.toRowRdd(fromRows).first()
assert(restoredRow.schema == schema)
assert(restoredRow.getAs[Geometry]("shape").equalsExact(geometry))
}

it("retains null internal geometry as an empty carrier and restores the original null") {
val schema =
StructType(Seq(StructField("geometry", GeometryUDT()), StructField("id", IntegerType)))
val source = sparkSession.createDataFrame(sc.parallelize(Seq(Row(null, 9))), schema)
val spatialRDD = StructuredAdapter.toSpatialRdd(source)
assert(spatialRDD.rawSpatialRDD.first().isEmpty)
val restored = StructuredAdapter.toDf(spatialRDD, sparkSession).head()
assert(restored.isNullAt(0))
assert(restored.getInt(1) == 9)
}

it("detects geometry columns without selecting geography or hiding ambiguity") {
def schema(names: String*): StructType = StructType(
Seq(StructField("globe", GeographyUDT())) ++ names.map(StructField(_, GeometryUDT())))
assert(DfUtils.getGeometryColumnName(schema("shape")) == "shape")
assert(DfUtils.getGeometryColumnName(schema("left", "geometry")) == "geometry")
intercept[IllegalArgumentException] { DfUtils.getGeometryColumnName(schema()) }
intercept[IllegalArgumentException] {
DfUtils.getGeometryColumnName(schema("left", "right"))
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* 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.sedona.sql

import org.apache.spark.sql.Row
import org.apache.spark.sql.sedona_sql.types.SpatialTypeSupport
import org.locationtech.jts.geom.Geometry

/** Geometry result access for semantic tests across external SQL representations. */
object SpatialTestValues {
def geometry(value: Any): Geometry = SpatialTypeSupport.fromExternalGeometry(value)

def geometry(row: Row, ordinal: Int): Geometry = geometry(row.get(ordinal))

def geometry(row: Row, field: String): Geometry = geometry(row, row.fieldIndex(field))
}
Loading
Loading