paleolimbot commented on code in PR #1163:
URL: https://github.com/apache/sedona-db/pull/1163#discussion_r3788174525


##########
rust/sedona-functions/src/st_geohash.rs:
##########
@@ -0,0 +1,360 @@
+// 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.
+
+use std::sync::Arc;
+
+use crate::executor::WkbExecutor;
+use arrow_array::builder::StringBuilder;
+use arrow_schema::DataType;
+use datafusion_common::{cast::as_int64_array, error::Result};
+use datafusion_expr::{ColumnarValue, Volatility};
+use geo_traits::GeometryTrait;
+use sedona_common::sedona_internal_datafusion_err;
+use sedona_expr::{
+    item_crs::ItemCrsKernel,
+    scalar_udf::{SedonaScalarKernel, SedonaScalarUDF},
+};
+use sedona_geometry::{bounds::geo_traits_bounds_xy, interval::IntervalTrait};
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+
+/// The base32 alphabet used by geohash encoding (Gustavo Niemeyer's 
specification)
+const BASE32: &[u8; 32] = b"0123456789bcdefghjkmnpqrstuvwxyz";
+
+/// The maximum number of geohash characters (matches Apache Sedona's
+/// PointGeoHashEncoder, which caps precision at 20)
+const MAX_PRECISION: i64 = 20;
+
+/// ST_GeoHash() scalar UDF
+///
+/// Native implementation to compute the geohash of a geometry at the given
+/// precision (number of base32 characters)
+pub fn st_geohash_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "st_geohash",
+        ItemCrsKernel::wrap_impl(vec![Arc::new(STGeoHash {})]),
+        Volatility::Immutable,
+    )
+}
+
+#[derive(Debug)]
+struct STGeoHash {}
+
+impl SedonaScalarKernel for STGeoHash {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(
+            vec![ArgMatcher::is_geometry(), ArgMatcher::is_integer()],

Review Comment:
   PostGIS and BigQuery also support the single arg versions of these (BigQuery 
only supports points; PostGIS returns the largest cell that completely contains 
the geometry or a level 20 cell for points). The non-point case with no 
specified level sounds hard so you could just error for it.



##########
rust/sedona-functions/src/st_geohash.rs:
##########
@@ -0,0 +1,360 @@
+// 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.
+
+use std::sync::Arc;
+
+use crate::executor::WkbExecutor;
+use arrow_array::builder::StringBuilder;
+use arrow_schema::DataType;
+use datafusion_common::{cast::as_int64_array, error::Result};
+use datafusion_expr::{ColumnarValue, Volatility};
+use geo_traits::GeometryTrait;
+use sedona_common::sedona_internal_datafusion_err;
+use sedona_expr::{
+    item_crs::ItemCrsKernel,
+    scalar_udf::{SedonaScalarKernel, SedonaScalarUDF},
+};
+use sedona_geometry::{bounds::geo_traits_bounds_xy, interval::IntervalTrait};
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+
+/// The base32 alphabet used by geohash encoding (Gustavo Niemeyer's 
specification)
+const BASE32: &[u8; 32] = b"0123456789bcdefghjkmnpqrstuvwxyz";
+
+/// The maximum number of geohash characters (matches Apache Sedona's
+/// PointGeoHashEncoder, which caps precision at 20)
+const MAX_PRECISION: i64 = 20;
+
+/// ST_GeoHash() scalar UDF
+///
+/// Native implementation to compute the geohash of a geometry at the given
+/// precision (number of base32 characters)
+pub fn st_geohash_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "st_geohash",
+        ItemCrsKernel::wrap_impl(vec![Arc::new(STGeoHash {})]),
+        Volatility::Immutable,
+    )
+}
+
+#[derive(Debug)]
+struct STGeoHash {}
+
+impl SedonaScalarKernel for STGeoHash {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(
+            vec![ArgMatcher::is_geometry(), ArgMatcher::is_integer()],
+            SedonaType::Arrow(DataType::Utf8),
+        );
+
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = WkbExecutor::new(arg_types, args);
+        let mut builder = StringBuilder::with_capacity(
+            executor.num_iterations(),
+            MAX_PRECISION as usize * executor.num_iterations(),
+        );
+
+        let precision_value = args[1]
+            .cast_to(&DataType::Int64, None)?
+            .to_array(executor.num_iterations())?;
+        let precision_array = as_int64_array(&precision_value)?;
+        let mut precision_iter = precision_array.iter();
+
+        executor.execute_wkb_void(|maybe_wkb| {
+            match (maybe_wkb, precision_iter.next().unwrap()) {
+                (Some(wkb), Some(precision)) => match invoke_scalar(wkb, 
precision)? {
+                    Some(geohash) => builder.append_value(geohash),
+                    // Geometry was empty or outside the lon/lat bounds
+                    None => builder.append_null(),
+                },
+                _ => builder.append_null(),
+            }
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+/// Compute the geohash of a geometry
+///
+/// Follows Apache Sedona's GeometryGeoHashEncoder.calculate(): the point that
+/// is hashed is the center of the geometry's bounding box, and null is
+/// returned when the bounding box is not fully contained in
+/// [-180, 180] x [-90, 90]. Unlike Sedona's Java implementation (where an
+/// empty geometry yields JTS' "null envelope" and thus an accidental hash of
+/// (-0.5, -0.5)), empty geometries return null here.
+fn invoke_scalar(geom: impl GeometryTrait<T = f64>, precision: i64) -> 
Result<Option<String>> {
+    let bounds = geo_traits_bounds_xy(geom)
+        .map_err(|e| sedona_internal_datafusion_err!("Error computing bounds: 
{e}"))?;
+    let (x, y) = (bounds.x(), bounds.y());
+    if x.is_empty() || y.is_empty() {
+        return Ok(None);
+    }
+
+    // Longitude can take values in [-180, 180]; latitude can take values in 
[-90, 90]
+    if x.lo() < -180.0 || y.lo() < -90.0 || x.hi() > 180.0 || y.hi() > 90.0 {
+        return Ok(None);
+    }

Review Comment:
   This would be better normalizing to the -180, 180 range and validating that 
we have lon/lat CRS (you could check what PostGIS does for this case...we have 
a "get geographic params" to check if this is a CRS we know is in 
longitude/latitude units, or maybe we only want this if it's bona-fide WGS84). 
This is easy for type level CRS but sort of a pain for item level CRS.



##########
python/sedonadb/tests/functions/test_functions.py:
##########
@@ -1778,6 +1778,47 @@ def test_st_geometrytype(eng, geom, expected):
     eng.assert_query_result(f"SELECT ST_GeometryType({arg})", expected)
 
 
[email protected]("eng", [SedonaDB, PostGIS])
[email protected](
+    ("geom", "precision", "expected"),
+    [
+        (None, 10, None),

Review Comment:
   I know it seems silly, but could you add all the empties (POINT EMPTY .... 
GEOMETRYCOLLECTION EMPTY) here?



##########
rust/sedona-functions/src/st_geohash.rs:
##########
@@ -0,0 +1,360 @@
+// 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.
+
+use std::sync::Arc;
+
+use crate::executor::WkbExecutor;
+use arrow_array::builder::StringBuilder;
+use arrow_schema::DataType;
+use datafusion_common::{cast::as_int64_array, error::Result};
+use datafusion_expr::{ColumnarValue, Volatility};
+use geo_traits::GeometryTrait;
+use sedona_common::sedona_internal_datafusion_err;
+use sedona_expr::{
+    item_crs::ItemCrsKernel,
+    scalar_udf::{SedonaScalarKernel, SedonaScalarUDF},
+};
+use sedona_geometry::{bounds::geo_traits_bounds_xy, interval::IntervalTrait};
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+
+/// The base32 alphabet used by geohash encoding (Gustavo Niemeyer's 
specification)
+const BASE32: &[u8; 32] = b"0123456789bcdefghjkmnpqrstuvwxyz";
+
+/// The maximum number of geohash characters (matches Apache Sedona's
+/// PointGeoHashEncoder, which caps precision at 20)
+const MAX_PRECISION: i64 = 20;
+
+/// ST_GeoHash() scalar UDF
+///
+/// Native implementation to compute the geohash of a geometry at the given
+/// precision (number of base32 characters)
+pub fn st_geohash_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "st_geohash",
+        ItemCrsKernel::wrap_impl(vec![Arc::new(STGeoHash {})]),
+        Volatility::Immutable,
+    )
+}
+
+#[derive(Debug)]
+struct STGeoHash {}
+
+impl SedonaScalarKernel for STGeoHash {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(
+            vec![ArgMatcher::is_geometry(), ArgMatcher::is_integer()],
+            SedonaType::Arrow(DataType::Utf8),
+        );
+
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = WkbExecutor::new(arg_types, args);
+        let mut builder = StringBuilder::with_capacity(
+            executor.num_iterations(),
+            MAX_PRECISION as usize * executor.num_iterations(),
+        );
+
+        let precision_value = args[1]
+            .cast_to(&DataType::Int64, None)?
+            .to_array(executor.num_iterations())?;
+        let precision_array = as_int64_array(&precision_value)?;
+        let mut precision_iter = precision_array.iter();
+
+        executor.execute_wkb_void(|maybe_wkb| {
+            match (maybe_wkb, precision_iter.next().unwrap()) {
+                (Some(wkb), Some(precision)) => match invoke_scalar(wkb, 
precision)? {
+                    Some(geohash) => builder.append_value(geohash),
+                    // Geometry was empty or outside the lon/lat bounds
+                    None => builder.append_null(),
+                },
+                _ => builder.append_null(),
+            }
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+/// Compute the geohash of a geometry
+///
+/// Follows Apache Sedona's GeometryGeoHashEncoder.calculate(): the point that
+/// is hashed is the center of the geometry's bounding box, and null is
+/// returned when the bounding box is not fully contained in
+/// [-180, 180] x [-90, 90]. Unlike Sedona's Java implementation (where an
+/// empty geometry yields JTS' "null envelope" and thus an accidental hash of
+/// (-0.5, -0.5)), empty geometries return null here.
+fn invoke_scalar(geom: impl GeometryTrait<T = f64>, precision: i64) -> 
Result<Option<String>> {
+    let bounds = geo_traits_bounds_xy(geom)
+        .map_err(|e| sedona_internal_datafusion_err!("Error computing bounds: 
{e}"))?;
+    let (x, y) = (bounds.x(), bounds.y());

Review Comment:
   I believe you can use the bounder from the config options to support 
Geography here, too. BigQuery supports this but only for points...you can punt 
on the integration tests there since you need credentials to set them up.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to