How to Call DuckDB Spatial Functions That Ibis Does Not Wrap
On this page
Problem statement
Ibis 12 has 53 geometry methods, and on DuckDB 23 of them do not compile, among them perimeter, simplify and x_max. DuckDB's spatial extension has 166 ST_ functions, so most of what it can do has no Ibis method at all: distance and area on the ellipsoid, Hilbert ordering, an extent aggregate, validity repair. You do not have to drop back to a SQL string for them. Ibis can declare any DuckDB function as a built-in UDF, a typed Python name that compiles straight to the function call. This page declares eight on Overture Maps places and suburbs in Auckland, shows the axis-order trap that makes two of them return NaN, and shows the SQL escape hatch for what a function call cannot express.
Quick answer
Declare the function with @ibis.udf.scalar.builtin, typed with ibis.expr.datatypes, and use it like a method:
@ibis.udf.scalar.builtin(name="ST_Distance_Spheroid")
def distance_spheroid(a: dt.geometry, b: dt.geometry) -> dt.float64:
"""Metres on the WGS 84 ellipsoid; DuckDB expects latitude first."""
metres = pair.select(m=distance_spheroid(_.a.flip_coordinates(), _.b.flip_coordinates())).execute().m.iloc[0]
print(f"Sky Tower to the airport on the ellipsoid: {metres:,.1f} m")
Sky Tower to the airport on the ellipsoid: 17,140.1 m
The decorated function has no body. Ibis uses its name, argument types and return type to build an expression, and compiles a call to it as ST_Distance_Spheroid(a, b). From the Sky Tower to the airport terminal that is 17,140.1 m on the ellipsoid, once the points are given latitude first.
Declaring a DuckDB function in Ibis
1. Which methods compile on DuckDB
t = ibis.table({"a": "geometry", "b": "geometry", "p": "point", "q": "point", "l": "linestring"}, name="t")
special = {"convert": ("a", ("EPSG:4326", "EPSG:2193"), {}), "azimuth": ("p", (t.q,), {}),
"line_locate_point": ("l", (t.p,), {}), "line_substring": ("l", (0.1, 0.9), {})}
compiles, undefined = [], []
for name, fn in inspect.getmembers(GeoSpatialValue, inspect.isfunction):
if name.startswith("_") or fn.__qualname__.split(".")[0] != "GeoSpatialValue":
continue
col, args, kw = special.get(name, ("a", (), {}))
if name not in special: # fill each required argument with a geometry or a number
args, kw = [], {}
for prm in list(inspect.signature(fn).parameters.values())[1:]:
if prm.default is not prm.empty:
continue
value = t.b if "Geo" in str(prm.annotation) else 1.0
if prm.kind is prm.KEYWORD_ONLY:
kw[prm.name] = value
else:
args.append(value)
try:
expr = getattr(t[col], name)(*args, **kw)
ibis.to_sql(expr.as_table() if isinstance(expr, ibis.expr.types.Scalar) else t.select(x=expr), dialect="duckdb")
compiles.append(name)
except OperationNotDefinedError:
undefined.append(name)
print(f"{len(compiles) + len(undefined)} geometry methods: {len(compiles)} compile on DuckDB, {len(undefined)} do not")
print("not defined:", ", ".join(undefined))
con.load_extension("spatial")
n_st = con.raw_sql("select count(distinct function_name) from duckdb_functions() where function_name ilike 'st\\_%' escape '\\'").fetchone()[0]
print(f"DuckDB spatial functions named ST_…: {n_st}")
53 geometry methods: 30 compile on DuckDB, 23 do not
not defined: as_binary, as_ewkb, as_ewkt, azimuth, contains_properly, d_fully_within, geometry_n, line_locate_point, line_merge, line_substring, max_distance, n_rings, ordering_equals, perimeter, point_n, set_srid, simplify, srid, transform, x_max, x_min, y_max, y_min
DuckDB spatial functions named ST_…: 166
Compiling each method against an unbound table, without any data, shows which ones the DuckDB backend has rules for: 30 of the 53. The 23 without include perimeter, simplify, x_max and as_binary, which DuckDB has as functions (ST_Perimeter, ST_Simplify, ST_XMax, ST_AsWKB). DuckDB itself offers 166 ST_ functions. Each one Ibis lacks is one declaration away.
2. Types, not strings
try:
@ibis.udf.scalar.builtin(name="ST_MakeValid")
def make_valid_str(g: "geometry") -> "geometry": ...
except NameError as error:
print(f"string annotations: {type(error).__name__}: {error}")
@ibis.udf.scalar.builtin(name="ST_MakeValid")
def make_valid(g: dt.geometry) -> dt.geometry: ...
print("dt annotations:", suburbs.select(v=make_valid(_.geometry)).schema()["v"])
string annotations: NameError: name 'geometry' is not defined
dt annotations: geospatial:geometry
Ibis reads the declaration's type hints with typing.get_type_hints, which evaluates string annotations as Python names. "geometry" is not a name, so the declaration fails with NameError before it reaches DuckDB. Annotate with the datatype objects from ibis.expr.datatypes (dt.geometry, dt.float64) and the expression gets the right type.
3. Latitude first, or NaN
both = pair.select(lon_first=distance_spheroid(_.a, _.b),
lat_first=distance_spheroid(_.a.flip_coordinates(), _.b.flip_coordinates())).execute().iloc[0]
d = pair.select(x1=_.a.x(), y1=_.a.y(), x2=_.b.x(), y2=_.b.y()).execute().iloc[0]
print(f"longitude first: {both.lon_first}; latitude first: {both.lat_first:,.1f} m; "
f"pyproj on GRS80: {Geod(ellps='GRS80').inv(d.x1, d.y1, d.x2, d.y2)[2]:,.1f} m")
longitude first: nan; latitude first: 17,140.1 m; pyproj on GRS80: 17,140.1 m
ST_Distance_Spheroid follows EPSG:4326's axis order, latitude then longitude. Given Overture's longitude-first points it reads 174.76 as a latitude and returns NaN, without an error. Ibis's flip_coordinates, which does compile on DuckDB, swaps the axes, and the result, 17,140.1 m, agrees with pyproj's geodesic on GRS80 to the tenth of a metre.
4. Area on the ellipsoid, without projecting
@ibis.udf.scalar.builtin(name="ST_Area_Spheroid")
def area_spheroid(g: dt.geometry) -> dt.float64: ...
a = suburbs.aggregate(ellipsoid=area_spheroid(_.geometry.flip_coordinates()).sum() / 1e6,
lon_first=area_spheroid(_.geometry).sum() / 1e6,
nztm=_.geometry.convert("EPSG:4326", "EPSG:2193").area().sum() / 1e6).execute().iloc[0]
print(f"167 suburbs: {a.ellipsoid:.2f} km² on the ellipsoid, {a.nztm:.2f} km² on NZTM2000, longitude first: {a.lon_first}")
167 suburbs: 656.92 km² on the ellipsoid, 656.80 km² on NZTM2000, longitude first: nan
656.92 km² by ST_Area_Spheroid against 656.80 km² by convert and area: 0.12 km² apart over 167 suburbs. Fed longitude first, the declared function returns NaN again.
5. An aggregate, and the methods that were missing
@ibis.udf.agg.builtin(name="ST_Extent_Agg")
def extent_agg(g: dt.geometry) -> dt.geometry: ...
@ibis.udf.scalar.builtin(name="ST_XMin")
def st_xmin(g: dt.geometry) -> dt.float64: ...
@ibis.udf.scalar.builtin(name="ST_XMax")
def st_xmax(g: dt.geometry) -> dt.float64: ...
subs = suburbs.select(suburb=_.name, sg=_.geometry)
per_suburb = (places.join(subs, places.geometry.within(subs.sg))
.group_by("suburb").aggregate(n=_.count(), box=extent_agg(_.geometry))
.mutate(west=st_xmin(_.box), east=st_xmax(_.box))
.mutate(km=(_.east - _.west) * 89.05) # km per degree of longitude at 36.9° S
.order_by(ibis.desc("km")).limit(3).execute())
print(per_suburb[["suburb", "n", "west", "east", "km"]].round(3).to_string(index=False))
all_box = places.aggregate(box=extent_agg(_.geometry)).execute().box.iloc[0]
print("extent of all places:", [round(v, 4) for v in all_box.bounds])
suburb n west east km
Wiri 512 174.809 174.892 7.417
Māngere 820 174.745 174.824 7.096
Massey 303 174.571 174.638 5.940
extent of all places: [174.55, -37.0998, 175.0499, -36.7001]
An aggregate is declared with @ibis.udf.agg.builtin and used inside aggregate like sum. ST_Extent_Agg gives each suburb's bounding box, and two scalar declarations, ST_XMin and ST_XMax, stand in for the x_min and x_max methods that do not compile. Wiri's places spread furthest east to west, about 7.4 km. Over all places the extent is the box they were cut from, 174.55–175.05° E.
Ordering, and the SQL escape hatch
The data used on this page
The Sky Tower, the airport terminal, every café and the 167 suburbs, all from Overture Maps 2026-11-18.0 for Auckland, read from a saved copy. Places CDLA Permissive 2.0, suburbs ODbL 1.0 (© OpenStreetMap contributors).
from pathlib import Path
import inspect
import duckdb
import ibis
import ibis.expr.datatypes as dt
import requests
from ibis import _
from ibis.common.exceptions import OperationNotDefinedError
from ibis.expr.types.geospatial import GeoSpatialValue
from pyproj import Geod
Path("data").mkdir(exist_ok=True)
# saved from s3://overturemaps-us-west-2/release/2026-11-18.0/ (theme=places, theme=divisions)
for layer in ["places", "suburbs"]:
name = f"overture-auckland-{layer}-2026-11-18.0.parquet"
if not Path(f"data/{name}").exists():
Path(f"data/{name}").write_bytes(requests.get(f"https://data.spatialworkflow.io/{name}", timeout=300).content)
con = ibis.duckdb.connect()
# the cast is for Ibis 12, which cannot read DuckDB's GEOMETRY('OGC:CRS84') type (see /ibis-keyerror-ogc-crs84/)
read = lambda layer: con.sql("select * replace (geometry::GEOMETRY as geometry) "
f"from read_parquet('data/overture-auckland-{layer}-2026-11-18.0.parquet')")
places, suburbs = read("places"), read("suburbs")
pair = (places.filter(_.name == "Sky Tower").select(a=_.geometry)
.cross_join(places.filter(_.id == "d001fa55-3bcb-4041-b8e6-1b6883f5a6b3").select(b=_.geometry))) # the airport terminal
print(f"{places.count().execute():,} places, {suburbs.count().execute()} suburbs")
56,465 places, 167 suburbs
Example 1: write places in Hilbert order
BOX_2D = dt.Struct({"min_x": "float64", "min_y": "float64", "max_x": "float64", "max_y": "float64"})
@ibis.udf.scalar.builtin(name="ST_Extent")
def st_extent(g: dt.geometry) -> BOX_2D: ...
@ibis.udf.scalar.builtin(name="ST_Hilbert")
def hilbert(g: dt.geometry, bounds: BOX_2D) -> dt.uint32: ...
bounds = st_extent(ibis.literal(all_box, type="geometry")) # the extent from step 5
for label, expr in [("by id", places), ("Hilbert", places.order_by(hilbert(_.geometry, bounds)))]:
path = f"data/places_{label.split()[0].lower()}.parquet"
expr.select("id", x=_.geometry.x(), y=_.geometry.y()).to_parquet(path, row_group_size=2_000)
groups = con.sql(f"""
select row_group_id,
max(case when path_in_schema = 'x' then stats_max_value::double end)
- max(case when path_in_schema = 'x' then stats_min_value::double end) as dx,
max(case when path_in_schema = 'y' then stats_max_value::double end)
- max(case when path_in_schema = 'y' then stats_min_value::double end) as dy
from parquet_metadata('{path}') group by row_group_id""").execute()
print(f"{label:8} {len(groups)} row groups of 2,000 places; median extent {groups.dx.median():.3f}° × {groups.dy.median():.3f}°")
by id 28 row groups of 2,000 places; median extent 0.496° × 0.394°
Hilbert 28 row groups of 2,000 places; median extent 0.062° × 0.056°
ST_Hilbert needs the bounds of the whole dataset as a BOX_2D, a struct in DuckDB, so the declaration types it as one and ST_Extent builds it from the extent found in step 5. Written in id order, each 2,000-place row group spans almost the whole box, a median 0.496° × 0.394°. Sorted along the Hilbert curve, each spans 0.062° × 0.056°, about one fiftieth of the area. A reader filtering the file to one suburb can then skip most row groups by their statistics.
Example 2: SQL for what a function call cannot say
con.load_extension("spatial") # Ibis loads it for its own geometry methods, not for SQL you write
cafes = places.filter(_.basic_category == "cafe").select("id", "name", "geometry").alias("cafes")
gaps = cafes.sql("""
with g as (select id, name, geometry::GEOMETRY as geom from cafes) -- WKB when Ibis reads the schema, GEOMETRY when it runs
select id, name,
ST_Distance(ST_Transform(geom, 'EPSG:4326', 'EPSG:2193', true),
lag(ST_Transform(geom, 'EPSG:4326', 'EPSG:2193', true))
over (order by ST_Hilbert(geom, ST_Extent(ST_MakeEnvelope(174.55, -37.10, 175.05, -36.70)))))
as metres_from_previous
from g
""")
print(type(gaps).__name__, gaps.schema()["metres_from_previous"])
print(f"{gaps.metres_from_previous.median().execute():.1f} m median between cafés that are neighbours in Hilbert order")
Table float64
230.8 m median between cafés that are neighbours in Hilbert order
A window function over a computed order, here the distance from each café to the one before it along the Hilbert curve, is easier to write as SQL. Table.sql runs SQL against an Ibis table and returns an Ibis Table again, so the result keeps working with methods: its median() is 230.8 m. Two details make it work. Ibis loads the spatial extension for its own methods but not for SQL you write, hence load_extension. And the table's geometry column arrives as WKB when Ibis infers the result's schema and as GEOMETRY when the query runs, so geometry::GEOMETRY is the one expression valid for both.
Example 3: two declarations that go wrong quietly
@ibis.udf.scalar.builtin(name="ST_X")
def st_x_int(g: dt.geometry) -> dt.int64: ... # ST_X returns a double
fresh = ibis.duckdb.connect()
fp = fresh.sql("select * replace (geometry::GEOMETRY as geometry) from 'data/overture-auckland-places-2026-11-18.0.parquet'")
try:
fp.select(x=st_x_int(_.geometry)).limit(1).execute()
except duckdb.CatalogException as error:
print("fresh connection:", str(error).splitlines()[0][:96])
fresh.load_extension("spatial")
r = fp.select(x=st_x_int(_.geometry), real=_.geometry.x()).filter(_.real > 0).limit(2).execute()
print("declared int64:", r.x.tolist(), "· the method:", r.real.round(4).tolist())
fresh connection: Catalog Error: Scalar Function with name "st_x" is not in the catalog, but it exists in the spat
declared int64: [174, 174] · the method: [174.767, 174.9159]
On a fresh connection the declared ST_X fails with DuckDB's "not in the catalog", because nothing in the query told Ibis to load the spatial extension. Once it is loaded, the declaration's wrong return type turns longitudes of 174.767 and 174.9159 into 174 and 174, with no warning. Comparing a declared function with an Ibis method, where one exists, catches both.
How a built-in UDF compiles
A built-in UDF is a declaration, not a function: Ibis records the name and types and the compiler writes NAME(arg, …) into the SQL. No Python runs per row, and DuckDB sees the same query it would see if you had typed the call. The types are the whole contract. Ibis checks them when the expression is built, and DuckDB checks the function's real signature when the query runs. A wrong argument type therefore fails in DuckDB, with DuckDB's list of candidate signatures. A wrong return type is not checked by either: the result is converted to what the declaration says, as ST_X declared as an integer shows.
Signatures that do not match
- Axis order. DuckDB's
_Spheroidfunctions take latitude first and returnNaNotherwise;ST_Distance_Spheretakes latitude first too but returns a plausible wrong number for longitude first, which is worse. Flip, and check one result against pyproj. - DuckDB types Ibis has no name for.
BOX_2Dis a struct of four doubles, sodt.Structdeclares it. - A connection with only declared functions. Ibis loads the spatial extension when an expression uses one of its own geometry methods. A query made only of declared functions, on a fresh connection, fails with "not in the catalog" until
con.load_extension("spatial")runs (Example 3). - Return types are trusted. Declared as
dt.int64,ST_Xcomes back as 174 for a longitude of 174.767 (Example 3): the result is converted to the declared type without a warning. - Names that already exist. A declared
x_minbeside the methodx_minis confusing; this page prefixes declarations withst_.
Internal links
- How to see the SQL behind an Ibis spatial query — checking what a declared function compiles to
- How to measure distances and buffers in metres in Ibis — the projected alternative to the ellipsoid functions
- Fixing Ibis OperationNotDefinedError for transform — an Ibis method that exists but does not compile on DuckDB
- Ibis for spatial data explained — what an expression is, and why a declared function is enough
FAQ
Does a built-in UDF run Python code?
No. The decorated function's body is never called. It exists for its name and type hints, and the work is done by DuckDB's own implementation of the function.
What if the function has optional arguments?
Declare one Python function per signature you use. ST_Hilbert has several: this page declares the two-argument form with a geometry and a BOX_2D.