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 2026/04/29 14:28:32 UTC

(sedona) branch master updated: [GH-2830] Adds Geography dual-dispatch to ST_Length (#2854)

This is an automated email from the ASF dual-hosted git repository.

jiayuasu pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sedona.git


The following commit(s) were added to refs/heads/master by this push:
     new 442bb9073c [GH-2830] Adds Geography dual-dispatch to ST_Length (#2854)
442bb9073c is described below

commit 442bb9073c8331a06465e0367b5c2b7d2975925c
Author: Feng Zhang <fe...@apache.org>
AuthorDate: Wed Apr 29 07:28:26 2026 -0700

    [GH-2830] Adds Geography dual-dispatch to ST_Length (#2854)
---
 .../apache/sedona/common/geography/Functions.java  | 37 +++++++++-
 .../sedona/common/Geography/FunctionTest.java      | 43 +++++++++++-
 docs/api/sql/geography/Geography-Functions.md      |  1 +
 .../sql/geography/Geography-Functions/ST_Length.md | 50 ++++++++++++++
 .../ST_Length_geography/ST_Length_geography.svg    | 80 ++++++++++++++++++++++
 .../sql/sedona_sql/expressions/Functions.scala     |  9 ++-
 .../sql/geography/GeographyFunctionTest.scala      | 22 +++++-
 7 files changed, 233 insertions(+), 9 deletions(-)

diff --git a/common/src/main/java/org/apache/sedona/common/geography/Functions.java b/common/src/main/java/org/apache/sedona/common/geography/Functions.java
index b3d1cc2a43..0d767736f4 100644
--- a/common/src/main/java/org/apache/sedona/common/geography/Functions.java
+++ b/common/src/main/java/org/apache/sedona/common/geography/Functions.java
@@ -183,7 +183,39 @@ public class Functions {
     return toJTS(g).toText();
   }
 
-  // ─── Level 2: JTS + S2 geodesic metrics ──────────────────────────────────
+  // ─── Level 2: Geodesic metrics ───────────────────────────────────────────
+
+  /**
+   * Spherical length in meters of a geography, calculated on the sphere. Edges are interpreted as
+   * great-circle arcs; the summed arc-angle is scaled by {@link Haversine#AVG_EARTH_RADIUS}.
+   * Multi-polylines sum the children's lengths; geography collections recurse. Returns {@code 0.0}
+   * for point/polygon geographies and for {@code null}.
+   */
+  public static double length(Geography g) {
+    if (g == null) return 0.0;
+    Geography typed = (g instanceof WKBGeography) ? ((WKBGeography) g).getS2Geography() : g;
+    double radians = sphericalLength(typed);
+    return radians * Haversine.AVG_EARTH_RADIUS;
+  }
+
+  /** Arc-angle (radians) of {@code g} on the unit sphere; 0 for non-linear kinds. */
+  private static double sphericalLength(Geography g) {
+    if (g instanceof PolylineGeography) {
+      double sum = 0.0;
+      for (S2Polyline pl : ((PolylineGeography) g).getPolylines()) {
+        sum += pl.getArclengthAngle().radians();
+      }
+      return sum;
+    }
+    if (g instanceof GeographyCollection) {
+      double sum = 0.0;
+      for (Geography feature : ((GeographyCollection) g).getFeatures()) {
+        sum += sphericalLength(feature);
+      }
+      return sum;
+    }
+    return 0.0;
+  }
 
   /**
    * Spherical area in square meters of a geography, calculated on the sphere. The Earth is modeled
@@ -233,8 +265,7 @@ public class Functions {
 
   /**
    * Geometry-to-geometry geodesic distance in meters. Uses S2ClosestEdgeQuery for true minimum
-   * distance between any two points on the geometries (not centroid-to-centroid). Consistent with
-   * sedona-db's s2_distance implementation.
+   * distance between any two points on the geometries (not centroid-to-centroid).
    */
   public static Double distance(Geography g1, Geography g2) {
     if (g1 == null || g2 == null) return null;
diff --git a/common/src/test/java/org/apache/sedona/common/Geography/FunctionTest.java b/common/src/test/java/org/apache/sedona/common/Geography/FunctionTest.java
index 52ca928925..6f01bb3539 100644
--- a/common/src/test/java/org/apache/sedona/common/Geography/FunctionTest.java
+++ b/common/src/test/java/org/apache/sedona/common/Geography/FunctionTest.java
@@ -332,7 +332,48 @@ public class FunctionTest {
     assertNull(Functions.asText(null));
   }
 
-  // ─── Level 2: ST_Area, ST_Distance ───────────────────────────────────────
+  // ─── Level 2: ST_Length, ST_Area, ST_Distance ────────────────────────────
+
+  @Test
+  public void length_equatorDegree() throws ParseException {
+    Geography g = Constructors.geogFromWKT("LINESTRING (0 0, 1 0)", 4326);
+    double len = Functions.length(g);
+    // Sphere of radius 6371008 m: 1° along a great circle is ~111,195 m.
+    assertEquals(111195.10, len, 1.0);
+  }
+
+  @Test
+  public void length_meridianDegree() throws ParseException {
+    Geography g = Constructors.geogFromWKT("LINESTRING (0 0, 0 1)", 4326);
+    double len = Functions.length(g);
+    // Meridians are great circles on a sphere — same length as the equator degree.
+    assertEquals(111195.10, len, 1.0);
+  }
+
+  @Test
+  public void length_point_returnsZero() throws ParseException {
+    Geography g = Constructors.geogFromWKT("POINT (1 2)", 4326);
+    assertEquals(0.0, Functions.length(g), 0.0);
+  }
+
+  @Test
+  public void length_polygon_returnsZero() throws ParseException {
+    Geography g = Constructors.geogFromWKT("POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))", 4326);
+    assertEquals(0.0, Functions.length(g), 0.0);
+  }
+
+  @Test
+  public void length_multilinestring_sumsChildren() throws ParseException {
+    Geography g = Constructors.geogFromWKT("MULTILINESTRING ((0 0, 1 0), (5 0, 6 0))", 4326);
+    double len = Functions.length(g);
+    // Two disjoint 1° equatorial arcs → 2 * (R * 1° in radians) ≈ 222,390 m.
+    assertEquals(2 * 111195.10, len, 2.0);
+  }
+
+  @Test
+  public void length_nullHandling() {
+    assertEquals(0.0, Functions.length(null), 0.0);
+  }
 
   @Test
   public void area_unitBoxAtEquator() throws ParseException {
diff --git a/docs/api/sql/geography/Geography-Functions.md b/docs/api/sql/geography/Geography-Functions.md
index 32b4faf7f8..bf22fa40f9 100644
--- a/docs/api/sql/geography/Geography-Functions.md
+++ b/docs/api/sql/geography/Geography-Functions.md
@@ -51,5 +51,6 @@ These functions operate on geography type objects.
 | [ST_NPoints](Geography-Functions/ST_NPoints.md) | Integer | Return the number of points (vertices) in a geography. | v1.9.0 |
 | [ST_NumGeometries](Geography-Functions/ST_NumGeometries.md) | Integer | Return the number of sub-geometries in a geography (1 for single geometries). | v1.9.1 |
 | [ST_Distance](Geography-Functions/ST_Distance.md) | Double | Return the minimum geodesic distance between two geographies in meters. | v1.9.0 |
+| [ST_Length](Geography-Functions/ST_Length.md) | Double | Return the spherical length of a geography in meters, summed along great-circle edges. | v1.9.1 |
 | [ST_Contains](Geography-Functions/ST_Contains.md) | Boolean | Test whether geography A fully contains geography B. | v1.9.0 |
 | [ST_Equals](Geography-Functions/ST_Equals.md) | Boolean | Test whether two geographies are spatially equal. | v1.9.1 |
diff --git a/docs/api/sql/geography/Geography-Functions/ST_Length.md b/docs/api/sql/geography/Geography-Functions/ST_Length.md
new file mode 100644
index 0000000000..2cbfbb1b87
--- /dev/null
+++ b/docs/api/sql/geography/Geography-Functions/ST_Length.md
@@ -0,0 +1,50 @@
+<!--
+ 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.
+ -->
+
+# ST_Length
+
+Introduction: Returns the spherical length of a geography in meters, calculated on the sphere. The Earth is modeled as a sphere of radius `R = 6 371 008 m` (the authalic Earth radius). Each edge between successive vertices is interpreted as a great-circle arc; the per-edge arc-angles are summed and scaled by `R`.
+
+Multi-linestrings sum the children's lengths; geography collections recurse and add up the lengths of their linear members. Returns `0.0` for non-linear geographies (points, polygons) and for `NULL`.
+
+![ST_Length on a Geography on the sphere](../../../../image/ST_Length_geography/ST_Length_geography.svg "ST_Length on a Geography (sphere-native)")
+
+If you specifically want the WGS84 ellipsoidal length (which differs from the spherical value by up to ~0.5 % depending on latitude), convert via `ST_GeogToGeometry` first and call the Geometry-typed `ST_Length(..., useSpheroid => true)` overload instead.
+
+Format:
+
+`ST_Length (A: Geography)`
+
+Return type: `Double`
+
+Since: `v1.9.1`
+
+SQL Example
+
+```sql
+SELECT ST_Length(ST_GeogFromWKT('LINESTRING (0 0, 1 0)'));
+```
+
+Output (in meters):
+
+```
+111195.10117748393
+```
+
+The result is approximately 111.2 km — one degree of arc on a sphere of radius `R = 6 371 008 m`.
diff --git a/docs/image/ST_Length_geography/ST_Length_geography.svg b/docs/image/ST_Length_geography/ST_Length_geography.svg
new file mode 100644
index 0000000000..06fd8d4e7b
--- /dev/null
+++ b/docs/image/ST_Length_geography/ST_Length_geography.svg
@@ -0,0 +1,80 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 540 320" width="540" height="320" style="background:#ffffff">
+  <defs>
+    <style>
+      text { font-family: 'Segoe UI', Arial, Helvetica, sans-serif; }
+    </style>
+    <radialGradient id="globeFill" cx="40%" cy="38%" r="65%">
+      <stop offset="0%" stop-color="#f4f8fc"/>
+      <stop offset="100%" stop-color="#cfd9e6"/>
+    </radialGradient>
+  </defs>
+
+  <!-- Title -->
+  <text x="270" y="24" text-anchor="middle" font-size="15" font-weight="bold" fill="#333333">ST_Length on a Geography (sphere-native)</text>
+
+  <!-- ─── Globe panel (left) ───────────────────────────────────────── -->
+  <g transform="translate(20,40)">
+    <!-- Globe sphere -->
+    <circle cx="130" cy="130" r="120" fill="url(#globeFill)" stroke="#8a99a8" stroke-width="1.2"/>
+
+    <!-- Latitude lines -->
+    <ellipse cx="130" cy="130" rx="120" ry="22" fill="none" stroke="#aab6c2" stroke-width="0.7" stroke-dasharray="2,2"/>
+    <ellipse cx="130" cy="130" rx="118" ry="60" fill="none" stroke="#aab6c2" stroke-width="0.6" stroke-dasharray="2,2"/>
+    <ellipse cx="130" cy="130" rx="113" ry="95" fill="none" stroke="#aab6c2" stroke-width="0.5" stroke-dasharray="2,2"/>
+
+    <!-- Longitude meridians -->
+    <ellipse cx="130" cy="130" rx="22" ry="120" fill="none" stroke="#aab6c2" stroke-width="0.7" stroke-dasharray="2,2"/>
+    <ellipse cx="130" cy="130" rx="60" ry="118" fill="none" stroke="#aab6c2" stroke-width="0.6" stroke-dasharray="2,2"/>
+    <ellipse cx="130" cy="130" rx="95" ry="113" fill="none" stroke="#aab6c2" stroke-width="0.5" stroke-dasharray="2,2"/>
+
+    <!-- Polyline on the sphere as 3 great-circle arcs -->
+    <path d="M 60 175 Q 90 150 120 138" fill="none" stroke="#e02020" stroke-width="2.6"/>
+    <path d="M 120 138 Q 150 130 175 110" fill="none" stroke="#e02020" stroke-width="2.6"/>
+    <path d="M 175 110 Q 195 100 215 88" fill="none" stroke="#e02020" stroke-width="2.6"/>
+
+    <!-- Vertices -->
+    <circle cx="60"  cy="175" r="4" fill="#0b1f3a"/>
+    <circle cx="120" cy="138" r="3.5" fill="#0b1f3a"/>
+    <circle cx="175" cy="110" r="3.5" fill="#0b1f3a"/>
+    <circle cx="215" cy="88"  r="4" fill="#0b1f3a"/>
+
+    <!-- Edge labels (arc-angle θ_i) -->
+    <text x="80"  y="148" font-size="11" fill="#333333" font-style="italic">θ₁</text>
+    <text x="142" y="124" font-size="11" fill="#333333" font-style="italic">θ₂</text>
+    <text x="190" y="96"  font-size="11" fill="#333333" font-style="italic">θ₃</text>
+
+    <!-- Caption under globe -->
+    <text x="130" y="276" text-anchor="middle" font-size="11" fill="#555555">edges are great-circle arcs</text>
+  </g>
+
+  <!-- ─── Formula / steps panel (right) ───────────────────────────── -->
+  <g transform="translate(290,55)">
+    <rect x="0" y="0" width="230" height="220" rx="6" fill="#fbfbfc" stroke="#cfd6dd" stroke-width="1"/>
+
+    <text x="115" y="22" text-anchor="middle" font-size="12" font-weight="bold" fill="#333333">How length is measured</text>
+
+    <!-- Step 1 -->
+    <circle cx="20" cy="50" r="9" fill="#2a4db3"/>
+    <text x="20" y="54" text-anchor="middle" font-size="11" fill="#ffffff" font-weight="bold">1</text>
+    <text x="36" y="48" font-size="11" fill="#333333">For each edge, compute its</text>
+    <text x="36" y="62" font-size="11" fill="#333333">arc-angle <tspan font-style="italic">θᵢ</tspan> on the unit sphere.</text>
+
+    <!-- Step 2 -->
+    <circle cx="20" cy="98" r="9" fill="#2a4db3"/>
+    <text x="20" y="102" text-anchor="middle" font-size="11" fill="#ffffff" font-weight="bold">2</text>
+    <text x="36" y="96" font-size="11" fill="#333333">Sum the arc-angles across</text>
+    <text x="36" y="110" font-size="11" fill="#333333">all edges and sub-features.</text>
+
+    <!-- Step 3 -->
+    <circle cx="20" cy="146" r="9" fill="#2a4db3"/>
+    <text x="20" y="150" text-anchor="middle" font-size="11" fill="#ffffff" font-weight="bold">3</text>
+    <text x="36" y="144" font-size="11" fill="#333333">Multiply by Earth radius R</text>
+    <text x="36" y="158" font-size="11" fill="#333333">(6 371 008 m) to get meters.</text>
+
+    <!-- Formula -->
+    <line x1="14" y1="178" x2="216" y2="178" stroke="#cfd6dd" stroke-width="0.8"/>
+    <text x="115" y="200" text-anchor="middle" font-size="13" fill="#0b1f3a">
+      length = R · Σ <tspan font-style="italic">θᵢ</tspan>
+    </text>
+  </g>
+</svg>
diff --git a/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/expressions/Functions.scala b/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/expressions/Functions.scala
index da4cf3b653..af93648598 100644
--- a/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/expressions/Functions.scala
+++ b/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/expressions/Functions.scala
@@ -252,12 +252,17 @@ private[apache] case class ST_Expand(inputExpressions: Seq[Expression])
 }
 
 /**
- * Return the length measurement of a Geometry
+ * Return the length measurement of a Geometry or Geography. Supports both Geometry (JTS, planar
+ * length in the input's coordinate units) and Geography (S2, geodesic length in meters on the
+ * WGS84 spheroid) via InferredExpression dual dispatch.
  *
  * @param inputExpressions
+ *   Geometry or Geography
  */
 private[apache] case class ST_Length(inputExpressions: Seq[Expression])
-    extends InferredExpression(Functions.length _) {
+    extends InferredExpression(
+      inferrableFunction1(Functions.length),
+      inferrableFunction1(org.apache.sedona.common.geography.Functions.length)) {
 
   protected def withNewChildrenInternal(newChildren: IndexedSeq[Expression]) = {
     copy(inputExpressions = newChildren)
diff --git a/spark/common/src/test/scala/org/apache/sedona/sql/geography/GeographyFunctionTest.scala b/spark/common/src/test/scala/org/apache/sedona/sql/geography/GeographyFunctionTest.scala
index 790b5e206d..7629e271f6 100644
--- a/spark/common/src/test/scala/org/apache/sedona/sql/geography/GeographyFunctionTest.scala
+++ b/spark/common/src/test/scala/org/apache/sedona/sql/geography/GeographyFunctionTest.scala
@@ -27,8 +27,8 @@ import org.locationtech.jts.geom.Point
 import org.locationtech.jts.io.WKTReader
 
 /**
- * Spark SQL integration tests for Geography ST functions. Tests one representative function per
- * architecture level: L1 (ST_NPoints), L2 (ST_Distance), L3 (ST_Contains).
+ * Spark SQL integration tests for Geography ST functions. Representative functions per
+ * architecture level: L1 (ST_NPoints), L2 (ST_Distance, ST_Length), L3 (ST_Contains).
  */
 class GeographyFunctionTest extends TestBaseScala {
 
@@ -143,10 +143,26 @@ class GeographyFunctionTest extends TestBaseScala {
     }
   }
 
-  // ─── Level 2: ST_Area, ST_Distance ─────────────────────────────────────
+  // ─── Level 2: ST_Length, ST_Area, ST_Distance ──────────────────────────
 
   describe("Level 2: Geodesic metrics") {
 
+    it("ST_Length along the equator") {
+      val row = sparkSession
+        .sql("SELECT ST_Length(ST_GeogFromWKT('LINESTRING (0 0, 1 0)', 4326)) AS l")
+        .first()
+      val len = row.getDouble(0)
+      // Sphere of radius 6371008 m: 1° along a great circle is ~111,195 m.
+      assertEquals(111195.10, len, 1.0)
+    }
+
+    it("ST_Length of a point returns 0") {
+      val row = sparkSession
+        .sql("SELECT ST_Length(ST_GeogFromWKT('POINT (1 2)', 4326)) AS l")
+        .first()
+      assertEquals(0.0, row.getDouble(0), 0.0)
+    }
+
     it("ST_Area unit box at equator") {
       val row = sparkSession
         .sql("SELECT ST_Area(ST_GeogFromWKT('POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))', 4326)) AS a")