You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@sedona.apache.org by "jiayuasu (via GitHub)" <gi...@apache.org> on 2026/10/14 22:03:51 UTC

[PR] feat(rust/sedona-functions): add ST_Geometries [sedona-db]

jiayuasu opened a new pull request, #1445:
URL: https://github.com/apache/sedona-db/pull/1445

   Closes #1429.
   
   ## What changes
   
   Adds `ST_Geometries(geom)`, which returns a geometry's direct members as a list:
   
   - the parts of a multi-geometry, or the members of a geometry collection, one level deep: a collection nested inside a collection is returned whole;
   - the geometry itself when it is not a collection, even when it is empty;
   - an empty list for an empty multi-geometry or collection, and NULL for NULL.
   
   This matches Shapely's `get_parts()`. The list items keep the input's spatial type, CRS, and edges (geometry and geography kernels), and each member's WKB is copied as is, so a member is stored once.
   
   `ST_Dump` recurses into nested collections down to their atomic parts, recording each part's position in `path` as PostGIS does, so it can't list a collection's members. Its reference page now says so and points to `ST_Geometries`. For `sedonadb-geopandas`, this lets `explode()` handle geometry collections in linear memory, as it already does for multi-geometries (follow-up once a release includes this function).
   
   `UNNEST` of the list currently returns WKB rather than geometry: DataFusion drops the list item field's metadata when unnesting (apache/datafusion#26331). The reference page shows wrapping it in `ST_GeomFromWKB` until that is fixed, and a strict expected-failure test will flag when it is.
   
   ## Testing
   
   - Rust: unit tests over geometry, geography, and a CRS-carrying type covering points, lines, polygons, empty members, nested collections, empty collections, Z, and NULL, plus the return type's kind and CRS.
   - Python: members compared against `shapely.get_parts` for the same corpus, NULL input, list items keeping the input's CRS and spherical edges, the documented `ST_GeomFromWKB(UNNEST(...))` pattern, and the expected failure for #26331.
   - `check_sql_function_docs.py` passes, and the generated `.geo.geometries()` accessor works.
   


-- 
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: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(rust/sedona-functions): add ST_Geometries [sedona-db]

Posted by "jiayuasu (via GitHub)" <gi...@apache.org>.
jiayuasu commented on code in PR #1445:
URL: https://github.com/apache/sedona-db/pull/1445#discussion_r4279157657


##########
docs/reference/sql/st_dump.qmd:
##########
@@ -29,6 +29,10 @@ kernels:
 
 If the geometry is simple it returns the geometry itself, if the geometry is collection or multi it returns record for each of collection components.
 
+Nested collections are expanded recursively down to their atomic parts, with `path`
+giving each part's position, as in PostGIS. To list only a geometry's direct members,
+use `ST_Geometries`.

Review Comment:
   Done in 3cbcfe25b: it now links [ST_Geometries](st_geometries.qmd), and the ST_Geometries page links back to ST_Dump and ST_GeometryN.
   



##########
docs/reference/sql/st_geometries.qmd:
##########
@@ -0,0 +1,56 @@
+---
+# 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
+
+title: ST_Geometries
+description: Returns the direct members of a geometry as a list, without recursing into nested collections.
+kernels:
+  - returns: list<geometry>
+    args: [geometry]
+  - returns: list<geography>
+    args: [geography]
+---
+
+## Description
+
+Returns the parts of a multi-geometry or the members of a geometry collection,
+one level deep: a collection nested inside a collection is returned whole. A
+geometry that is not a collection returns itself as the only member, even when
+it is empty, while an empty multi-geometry or collection returns an empty list.
+The members keep the input's spatial type and CRS, and NULL returns NULL.
+
+Unlike `ST_Dump`, which recurses into nested collections down to their atomic
+parts and records each part's position in a `path`, `ST_Geometries` returns
+only the members themselves, matching Shapely's `get_parts()`. Combined with
+`UNNEST`, it turns each member into its own row.
+
+`UNNEST` currently returns the members as WKB rather than geometry, because it
+drops the list's item type (apache/datafusion#26331); wrap it in
+`ST_GeomFromWKB` (and `ST_SetSRID`, to keep a CRS) until that is fixed.

Review Comment:
   Agreed, done in 3cbcfe25b: the page now describes it as `ST_GeometryN(geom, n)` for each member, with the workaround and the Shapely comparison removed. It keeps one line on the edge cases: a non-collection (even an empty one) is its own single member, and an empty multi-geometry or collection gives an empty list.
   



##########
python/sedonadb/tests/functions/test_functions.py:
##########
@@ -1368,6 +1370,100 @@ def test_st_dimension(eng, geom, expected):
     eng.assert_query_result(f"SELECT ST_Dimension({geom_or_null(geom)})", expected)
 
 
+@pytest.mark.parametrize(
+    "wkt",
+    [
+        "POINT (1 2)",
+        "POINT EMPTY",
+        "LINESTRING (1 1, 2 2)",
+        "POLYGON ((1 1, 2 2, 2 1, 1 1))",
+        "MULTIPOINT (0 1, 1 2)",
+        "MULTIPOINT EMPTY",
+        "MULTILINESTRING ((1 1, 2 2), EMPTY, (3 3, 4 4))",
+        "MULTIPOLYGON (((1 1, 2 2, 2 1, 1 1)), EMPTY, ((3 3, 4 4, 4 3, 3 3)))",
+        "GEOMETRYCOLLECTION (POINT (1 2), GEOMETRYCOLLECTION (MULTILINESTRING ((1 1, 2 2), EMPTY, (3 3, 4 4)), LINESTRING (1 1, 2 2)))",
+        "GEOMETRYCOLLECTION EMPTY",
+        "MULTIPOINT Z ((0 1 2), (1 2 3))",
+    ],
+)
+def test_st_geometries(wkt):
+    # A geometry's direct members, one level deep, as shapely.get_parts gives
+    # them: a nested collection is a member, where ST_Dump recurses into it.
+    eng = SedonaDB.create_or_skip()
+    table = eng.con.sql(
+        f"SELECT ST_Geometries({geom_or_null(wkt)}) AS g"
+    ).to_arrow_table()
+    members = table.column("g").to_pylist()[0]
+    expected = shapely.get_parts(shapely.from_wkt(wkt))
+    assert [shapely.from_wkb(m).wkt for m in members] == [g.wkt for g in expected]
+
+
+def test_st_geometries_null():
+    eng = SedonaDB.create_or_skip()
+    table = eng.con.sql("SELECT ST_Geometries(NULL) AS g").to_arrow_table()
+    assert table.column("g").to_pylist() == [None]
+
+
+@pytest.mark.parametrize(
+    ("constructor", "expected"),
+    [
+        ("ST_SetSRID(ST_GeomFromText('MULTIPOINT (0 1, 1 2)'), 3857)", {"crs"}),
+        ("ST_GeogFromWKT('MULTIPOINT (0 1, 1 2)')", {"crs", "edges"}),
+    ],
+)
+def test_st_geometries_members_keep_the_input_type(constructor, expected):
+    # Each list item has the input's spatial type: its CRS, and for
+    # geography its spherical edges.
+    eng = SedonaDB.create_or_skip()
+    df = eng.con.sql(
+        f"SELECT {constructor} AS g, ST_Geometries({constructor}) AS parts"
+    )
+    schema = pa.schema(df.schema)
+    item_name, item_meta = _extension(schema.field("parts").type.value_field)
+    input_name, input_meta = _extension(schema.field("g"))
+    assert item_name == input_name == "geoarrow.wkb"
+    assert expected <= set(item_meta)
+    assert item_meta == input_meta
+
+
+def _extension(field):
+    """A field's extension name and metadata, whether or not the extension
+    type is registered with pyarrow (geoarrow-pyarrow registers it)."""
+    if isinstance(field.type, pa.ExtensionType):
+        serialized = field.type.__arrow_ext_serialize__() or b"{}"
+        return field.type.extension_name, json.loads(serialized)
+    return (
+        field.metadata[b"ARROW:extension:name"].decode(),
+        json.loads(field.metadata[b"ARROW:extension:metadata"]),
+    )
+
+
+@pytest.mark.xfail(
+    strict=True,
+    reason="unnest drops the list item's type (apache/datafusion#26331)",
+)
+def test_st_geometries_unnest_keeps_the_type():
+    eng = SedonaDB.create_or_skip()
+    parts = eng.con.sql(
+        "SELECT UNNEST(ST_Geometries(ST_SetSRID("
+        "ST_GeomFromText('MULTIPOINT (0 1, 1 2)'), 3857))) AS part"
+    )
+    assert parts.schema.field("part").type.crs is not None
+
+
+def test_st_geometries_unnest_with_st_geomfromwkb():
+    # The documented workaround until unnest keeps the item type.
+    eng = SedonaDB.create_or_skip()
+    parts = eng.con.sql(
+        "SELECT ST_GeomFromWKB(UNNEST(ST_Geometries("
+        "ST_GeomFromText('MULTIPOINT (0 1, 1 2)')))) AS part"
+    ).to_arrow_table()
+    assert [shapely.from_wkb(m).wkt for m in parts.column("part").to_pylist()] == [
+        "POINT (0 1)",
+        "POINT (1 2)",
+    ]
+
+

Review Comment:
   Makes sense, removed both UNNEST tests in 3cbcfe25b; the DataFusion fix (apache/datafusion#26331) will carry through on its own.
   



##########
rust/sedona-functions/src/st_geometries.rs:
##########
@@ -0,0 +1,306 @@
+// 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 arrow_array::{
+    ListArray,
+    builder::{BinaryBuilder, NullBufferBuilder, OffsetBufferBuilder},
+};
+use arrow_schema::{DataType, FieldRef};
+use datafusion_common::{Result, config::ConfigOptions};
+use datafusion_expr::{ColumnarValue, Volatility};
+use geo_traits::{
+    GeometryCollectionTrait, GeometryTrait, GeometryType, MultiLineStringTrait, MultiPointTrait,
+    MultiPolygonTrait,
+};
+use sedona_common::sedona_internal_err;
+use sedona_expr::scalar_udf::{SedonaScalarKernel, SedonaScalarUDF};
+use sedona_geometry::wkb_factory::WKB_MIN_PROBABLE_BYTES;
+use sedona_schema::{
+    datatypes::{SedonaType, WKB_GEOGRAPHY, WKB_GEOMETRY},
+    matchers::ArgMatcher,
+};
+use std::sync::Arc;
+
+use crate::executor::WkbExecutor;
+
+/// ST_Geometries() scalar UDF
+///
+/// Lists a geometry's direct members: the parts of a multi-geometry or the
+/// members of a geometry collection, one level deep (a nested collection is
+/// returned whole, unlike ST_Dump, which recurses), or the geometry itself
+/// when it is not a collection.
+pub fn st_geometries_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "st_geometries",
+        vec![
+            Arc::new(STGeometries {
+                matcher: ArgMatcher::new(vec![ArgMatcher::is_geometry()], WKB_GEOMETRY),
+            }),
+            Arc::new(STGeometries {
+                matcher: ArgMatcher::new(vec![ArgMatcher::is_geography()], WKB_GEOGRAPHY),
+            }),
+        ],
+        Volatility::Immutable,
+    )
+}
+
+#[derive(Debug)]
+struct STGeometries {
+    matcher: ArgMatcher,
+}
+
+/// Builds a list of WKB members per input row
+struct STGeometriesBuilder {
+    geom_builder: BinaryBuilder,
+    offsets_builder: OffsetBufferBuilder<i32>,
+    null_builder: NullBufferBuilder,
+    item_field: FieldRef,
+}
+
+impl STGeometriesBuilder {
+    fn new(num_iter: usize, return_type: &SedonaType) -> Result<Self> {
+        let SedonaType::Arrow(DataType::List(item_field)) = return_type else {
+            return sedona_internal_err!("Unexpected return type in st_geometries()");
+        };
+
+        Ok(Self {
+            geom_builder: BinaryBuilder::with_capacity(num_iter, WKB_MIN_PROBABLE_BYTES * num_iter),

Review Comment:
   Done in 3cbcfe25b without much code: since the members are slices of the input's WKB, the builder is sized from the input slice (`array.to_data().get_slice_memory_size()`), falling back to the per-row estimate for scalars or when that size isn't available. I also added WkbView inputs to the tests to cover that path.
   



##########
rust/sedona-functions/src/st_geometries.rs:
##########
@@ -0,0 +1,306 @@
+// 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 arrow_array::{
+    ListArray,
+    builder::{BinaryBuilder, NullBufferBuilder, OffsetBufferBuilder},
+};
+use arrow_schema::{DataType, FieldRef};
+use datafusion_common::{Result, config::ConfigOptions};
+use datafusion_expr::{ColumnarValue, Volatility};
+use geo_traits::{
+    GeometryCollectionTrait, GeometryTrait, GeometryType, MultiLineStringTrait, MultiPointTrait,
+    MultiPolygonTrait,
+};
+use sedona_common::sedona_internal_err;
+use sedona_expr::scalar_udf::{SedonaScalarKernel, SedonaScalarUDF};
+use sedona_geometry::wkb_factory::WKB_MIN_PROBABLE_BYTES;
+use sedona_schema::{
+    datatypes::{SedonaType, WKB_GEOGRAPHY, WKB_GEOMETRY},
+    matchers::ArgMatcher,
+};
+use std::sync::Arc;
+
+use crate::executor::WkbExecutor;
+
+/// ST_Geometries() scalar UDF
+///
+/// Lists a geometry's direct members: the parts of a multi-geometry or the
+/// members of a geometry collection, one level deep (a nested collection is
+/// returned whole, unlike ST_Dump, which recurses), or the geometry itself
+/// when it is not a collection.
+pub fn st_geometries_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "st_geometries",
+        vec![
+            Arc::new(STGeometries {
+                matcher: ArgMatcher::new(vec![ArgMatcher::is_geometry()], WKB_GEOMETRY),
+            }),
+            Arc::new(STGeometries {
+                matcher: ArgMatcher::new(vec![ArgMatcher::is_geography()], WKB_GEOGRAPHY),
+            }),

Review Comment:
   Tracked as #1450 (covering ST_Dump as well, which doesn't have them either). `ItemCrsKernel::wrap_impl` only rewraps a geometry or geography output with the row's CRS, so for a list output it would drop the per-row CRS; it needs an output type that carries each row's CRS first.
   



-- 
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: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(rust/sedona-functions): add ST_Geometries [sedona-db]

Posted by "paleolimbot (via GitHub)" <gi...@apache.org>.
paleolimbot commented on code in PR #1445:
URL: https://github.com/apache/sedona-db/pull/1445#discussion_r4278362573


##########
docs/reference/sql/st_geometries.qmd:
##########
@@ -0,0 +1,56 @@
+---
+# 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
+
+title: ST_Geometries
+description: Returns the direct members of a geometry as a list, without recursing into nested collections.
+kernels:
+  - returns: list<geometry>
+    args: [geometry]
+  - returns: list<geography>
+    args: [geography]
+---
+
+## Description
+
+Returns the parts of a multi-geometry or the members of a geometry collection,
+one level deep: a collection nested inside a collection is returned whole. A
+geometry that is not a collection returns itself as the only member, even when
+it is empty, while an empty multi-geometry or collection returns an empty list.
+The members keep the input's spatial type and CRS, and NULL returns NULL.
+
+Unlike `ST_Dump`, which recurses into nested collections down to their atomic
+parts and records each part's position in a `path`, `ST_Geometries` returns
+only the members themselves, matching Shapely's `get_parts()`. Combined with
+`UNNEST`, it turns each member into its own row.
+
+`UNNEST` currently returns the members as WKB rather than geometry, because it
+drops the list's item type (apache/datafusion#26331); wrap it in
+`ST_GeomFromWKB` (and `ST_SetSRID`, to keep a CRS) until that is fixed.

Review Comment:
   I think you can just document the function and what it does for now without the workaround, and I'm not sure Shapely is the best analog to refer to here. Maybe better to describe as `ST_GeometryN()` for all `n`.



##########
rust/sedona-functions/src/st_geometries.rs:
##########
@@ -0,0 +1,306 @@
+// 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 arrow_array::{
+    ListArray,
+    builder::{BinaryBuilder, NullBufferBuilder, OffsetBufferBuilder},
+};
+use arrow_schema::{DataType, FieldRef};
+use datafusion_common::{Result, config::ConfigOptions};
+use datafusion_expr::{ColumnarValue, Volatility};
+use geo_traits::{
+    GeometryCollectionTrait, GeometryTrait, GeometryType, MultiLineStringTrait, MultiPointTrait,
+    MultiPolygonTrait,
+};
+use sedona_common::sedona_internal_err;
+use sedona_expr::scalar_udf::{SedonaScalarKernel, SedonaScalarUDF};
+use sedona_geometry::wkb_factory::WKB_MIN_PROBABLE_BYTES;
+use sedona_schema::{
+    datatypes::{SedonaType, WKB_GEOGRAPHY, WKB_GEOMETRY},
+    matchers::ArgMatcher,
+};
+use std::sync::Arc;
+
+use crate::executor::WkbExecutor;
+
+/// ST_Geometries() scalar UDF
+///
+/// Lists a geometry's direct members: the parts of a multi-geometry or the
+/// members of a geometry collection, one level deep (a nested collection is
+/// returned whole, unlike ST_Dump, which recurses), or the geometry itself
+/// when it is not a collection.
+pub fn st_geometries_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "st_geometries",
+        vec![
+            Arc::new(STGeometries {
+                matcher: ArgMatcher::new(vec![ArgMatcher::is_geometry()], WKB_GEOMETRY),
+            }),
+            Arc::new(STGeometries {
+                matcher: ArgMatcher::new(vec![ArgMatcher::is_geography()], WKB_GEOGRAPHY),
+            }),
+        ],
+        Volatility::Immutable,
+    )
+}
+
+#[derive(Debug)]
+struct STGeometries {
+    matcher: ArgMatcher,
+}
+
+/// Builds a list of WKB members per input row
+struct STGeometriesBuilder {
+    geom_builder: BinaryBuilder,
+    offsets_builder: OffsetBufferBuilder<i32>,
+    null_builder: NullBufferBuilder,
+    item_field: FieldRef,
+}
+
+impl STGeometriesBuilder {
+    fn new(num_iter: usize, return_type: &SedonaType) -> Result<Self> {
+        let SedonaType::Arrow(DataType::List(item_field)) = return_type else {
+            return sedona_internal_err!("Unexpected return type in st_geometries()");
+        };
+
+        Ok(Self {
+            geom_builder: BinaryBuilder::with_capacity(num_iter, WKB_MIN_PROBABLE_BYTES * num_iter),

Review Comment:
   If there's a non-verbose way to do this, the capacity will be very close to the size of the input array. If not, we have an issue tracking this for other functions



##########
rust/sedona-functions/src/st_geometries.rs:
##########
@@ -0,0 +1,306 @@
+// 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 arrow_array::{
+    ListArray,
+    builder::{BinaryBuilder, NullBufferBuilder, OffsetBufferBuilder},
+};
+use arrow_schema::{DataType, FieldRef};
+use datafusion_common::{Result, config::ConfigOptions};
+use datafusion_expr::{ColumnarValue, Volatility};
+use geo_traits::{
+    GeometryCollectionTrait, GeometryTrait, GeometryType, MultiLineStringTrait, MultiPointTrait,
+    MultiPolygonTrait,
+};
+use sedona_common::sedona_internal_err;
+use sedona_expr::scalar_udf::{SedonaScalarKernel, SedonaScalarUDF};
+use sedona_geometry::wkb_factory::WKB_MIN_PROBABLE_BYTES;
+use sedona_schema::{
+    datatypes::{SedonaType, WKB_GEOGRAPHY, WKB_GEOMETRY},
+    matchers::ArgMatcher,
+};
+use std::sync::Arc;
+
+use crate::executor::WkbExecutor;
+
+/// ST_Geometries() scalar UDF
+///
+/// Lists a geometry's direct members: the parts of a multi-geometry or the
+/// members of a geometry collection, one level deep (a nested collection is
+/// returned whole, unlike ST_Dump, which recurses), or the geometry itself
+/// when it is not a collection.
+pub fn st_geometries_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "st_geometries",
+        vec![
+            Arc::new(STGeometries {
+                matcher: ArgMatcher::new(vec![ArgMatcher::is_geometry()], WKB_GEOMETRY),
+            }),
+            Arc::new(STGeometries {
+                matcher: ArgMatcher::new(vec![ArgMatcher::is_geography()], WKB_GEOGRAPHY),
+            }),

Review Comment:
   Because you're here and we're thinking about this, it would be nice to also include ItemCrs kernels for this (can also be tracked as a follow-up issue, I forget if we ever did this for ST_Dump)



##########
python/sedonadb/tests/functions/test_functions.py:
##########
@@ -1368,6 +1370,100 @@ def test_st_dimension(eng, geom, expected):
     eng.assert_query_result(f"SELECT ST_Dimension({geom_or_null(geom)})", expected)
 
 
+@pytest.mark.parametrize(
+    "wkt",
+    [
+        "POINT (1 2)",
+        "POINT EMPTY",
+        "LINESTRING (1 1, 2 2)",
+        "POLYGON ((1 1, 2 2, 2 1, 1 1))",
+        "MULTIPOINT (0 1, 1 2)",
+        "MULTIPOINT EMPTY",
+        "MULTILINESTRING ((1 1, 2 2), EMPTY, (3 3, 4 4))",
+        "MULTIPOLYGON (((1 1, 2 2, 2 1, 1 1)), EMPTY, ((3 3, 4 4, 4 3, 3 3)))",
+        "GEOMETRYCOLLECTION (POINT (1 2), GEOMETRYCOLLECTION (MULTILINESTRING ((1 1, 2 2), EMPTY, (3 3, 4 4)), LINESTRING (1 1, 2 2)))",
+        "GEOMETRYCOLLECTION EMPTY",
+        "MULTIPOINT Z ((0 1 2), (1 2 3))",
+    ],
+)
+def test_st_geometries(wkt):
+    # A geometry's direct members, one level deep, as shapely.get_parts gives
+    # them: a nested collection is a member, where ST_Dump recurses into it.
+    eng = SedonaDB.create_or_skip()
+    table = eng.con.sql(
+        f"SELECT ST_Geometries({geom_or_null(wkt)}) AS g"
+    ).to_arrow_table()
+    members = table.column("g").to_pylist()[0]
+    expected = shapely.get_parts(shapely.from_wkt(wkt))
+    assert [shapely.from_wkb(m).wkt for m in members] == [g.wkt for g in expected]
+
+
+def test_st_geometries_null():
+    eng = SedonaDB.create_or_skip()
+    table = eng.con.sql("SELECT ST_Geometries(NULL) AS g").to_arrow_table()
+    assert table.column("g").to_pylist() == [None]
+
+
+@pytest.mark.parametrize(
+    ("constructor", "expected"),
+    [
+        ("ST_SetSRID(ST_GeomFromText('MULTIPOINT (0 1, 1 2)'), 3857)", {"crs"}),
+        ("ST_GeogFromWKT('MULTIPOINT (0 1, 1 2)')", {"crs", "edges"}),
+    ],
+)
+def test_st_geometries_members_keep_the_input_type(constructor, expected):
+    # Each list item has the input's spatial type: its CRS, and for
+    # geography its spherical edges.
+    eng = SedonaDB.create_or_skip()
+    df = eng.con.sql(
+        f"SELECT {constructor} AS g, ST_Geometries({constructor}) AS parts"
+    )
+    schema = pa.schema(df.schema)
+    item_name, item_meta = _extension(schema.field("parts").type.value_field)
+    input_name, input_meta = _extension(schema.field("g"))
+    assert item_name == input_name == "geoarrow.wkb"
+    assert expected <= set(item_meta)
+    assert item_meta == input_meta
+
+
+def _extension(field):
+    """A field's extension name and metadata, whether or not the extension
+    type is registered with pyarrow (geoarrow-pyarrow registers it)."""
+    if isinstance(field.type, pa.ExtensionType):
+        serialized = field.type.__arrow_ext_serialize__() or b"{}"
+        return field.type.extension_name, json.loads(serialized)
+    return (
+        field.metadata[b"ARROW:extension:name"].decode(),
+        json.loads(field.metadata[b"ARROW:extension:metadata"]),
+    )
+
+
+@pytest.mark.xfail(
+    strict=True,
+    reason="unnest drops the list item's type (apache/datafusion#26331)",
+)
+def test_st_geometries_unnest_keeps_the_type():
+    eng = SedonaDB.create_or_skip()
+    parts = eng.con.sql(
+        "SELECT UNNEST(ST_Geometries(ST_SetSRID("
+        "ST_GeomFromText('MULTIPOINT (0 1, 1 2)'), 3857))) AS part"
+    )
+    assert parts.schema.field("part").type.crs is not None
+
+
+def test_st_geometries_unnest_with_st_geomfromwkb():
+    # The documented workaround until unnest keeps the item type.
+    eng = SedonaDB.create_or_skip()
+    parts = eng.con.sql(
+        "SELECT ST_GeomFromWKB(UNNEST(ST_Geometries("
+        "ST_GeomFromText('MULTIPOINT (0 1, 1 2)')))) AS part"
+    ).to_arrow_table()
+    assert [shapely.from_wkb(m).wkt for m in parts.column("part").to_pylist()] == [
+        "POINT (0 1)",
+        "POINT (1 2)",
+    ]
+
+

Review Comment:
   I think these are better untested. We'll fix the bug in DataFusion and it will trickle down here (or if it's important, we can track separately to override the planner with our own operators to fix it).



##########
docs/reference/sql/st_dump.qmd:
##########
@@ -29,6 +29,10 @@ kernels:
 
 If the geometry is simple it returns the geometry itself, if the geometry is collection or multi it returns record for each of collection components.
 
+Nested collections are expanded recursively down to their atomic parts, with `path`
+giving each part's position, as in PostGIS. To list only a geometry's direct members,
+use `ST_Geometries`.

Review Comment:
   I think you can cross reference here (I had Codex do that for me on at least one other docs page)



-- 
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: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(rust/sedona-functions): add ST_Geometries [sedona-db]

Posted by "jiayuasu (via GitHub)" <gi...@apache.org>.
jiayuasu merged PR #1445:
URL: https://github.com/apache/sedona-db/pull/1445


-- 
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: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org