How to Find the Nearest Feature in Ibis Without sjoin_nearest

On this page

Problem statement

GeoPandas has sjoin_nearest, and Ibis has no equivalent method: no nearest-neighbour join, and no ORDER BY distance LIMIT 1 per row. What it does have is a distance join and window functions, and together they find the nearest feature for every row while DuckDB does the work. This page finds the nearest library to each of the 187 primary schools in Overture Maps places for Auckland, and checks the answer against sjoin_nearest. It also shows what the search radius quietly does to schools with no library inside it, and how to break ties so the result is the same on every run.

Quick answer

Join within a search radius, rank each school's candidates by distance with row_number, and keep the first; use a left join so schools with nothing in range stay in the result:

pairs = schools.left_join(libraries, schools.g.d_within(libraries.lg, distance=RADIUS))
ranked = pairs.mutate(dist=_.g.distance(_.lg)).mutate(
    rank=ibis.row_number().over(group_by=_.school_id, order_by=[_.dist, _.lib_id]))
nearest = ranked.filter(_.rank == 0).select("school_id", "school", "library", "dist")
result = nearest.execute()
print(f"{len(result)} schools; {result.dist.notna().sum()} with a library within {RADIUS:,} m, median {result.dist.median():,.0f} m")
187 schools; 182 with a library within 3,000 m, median 1,051 m

All 187 schools are in the result. 182 have a library within 3 km, and for them the nearest is a median 1,051 m away. The other five keep their row with an empty distance, which says "nothing within 3 km" instead of leaving them out.

Steps to find the nearest library to each school in Ibis without sjoin_nearest. nearest by ranking1left join with d_within, 3 km957 pairs2distance for each candidatemetres, NZTM20003row_number over school, by [dist, lib_id]ties broken by id4keep rank == 0187 schools, 182 matchedThe left join keeps the 5 schools with nothing in range spatialworkflow.io
Nearest by ranking: 187 schools in, 182 matched within 3 km.

Nearest by ranking

1. Candidates within a radius

cand = schools.join(libraries, schools.g.d_within(libraries.lg, distance=RADIUS))
per_school = cand.group_by("school_id").aggregate(k=_.count()).k.execute()
print(f"{cand.count().execute():,} school–library pairs within {RADIUS:,} m; "
      f"candidates per school: median {per_school.median():.0f}, max {per_school.max()}")
957 school–library pairs within 3,000 m; candidates per school: median 4, max 37

The radius sets how much work the ranking does. Within 3 km there are 957 school–library pairs, a median of 4 candidates per school and at most 37, against 187 × 121 = 22,627 pairs with no radius. d_within lets DuckDB find them with its spatial join instead of measuring every pair (why the spelling matters).

2. What an inner join loses

inner = (cand.mutate(dist=_.g.distance(_.lg))
         .mutate(rank=ibis.row_number().over(group_by=_.school_id, order_by=[_.dist, _.lib_id]))
         .filter(_.rank == 0))
print(f"inner join: {inner.count().execute()} of {schools.count().execute()} schools; "
      f"left join: {len(result)}, of which {result.dist.isna().sum()} have no library within {RADIUS:,} m")
inner join: 182 of 187 schools; left join: 187, of which 5 have no library within 3,000 m

An inner join returns 182 schools. The five without a candidate are not marked as far away; they are simply missing, and an average distance computed from the inner join describes only the schools that were close enough. The left join keeps them and makes the cut-off visible.

School–library pairs from all combinations to one nearest library per school. 187 schools × 121 librariesevery pair22,627d_within÷ 24within 3 km957rank == 0÷ 5.3nearest per school182 + 5 unmatchedband width is log-scaledThe radius cut the pairs to measure by a factor of 24 spatialworkflow.io
The radius cut the pairs to measure by a factor of 24.

3. Check against sjoin_nearest

gs = gpd.GeoDataFrame(schools.execute(), geometry="g", crs="EPSG:2193")
gl = gpd.GeoDataFrame(libraries.execute(), geometry="lg", crs="EPSG:2193")
ref = gpd.sjoin_nearest(gs, gl, distance_col="ref_m").sort_values(["school_id", "lib_id"]).drop_duplicates("school_id")
both = ref.merge(result, on="school_id", suffixes=("_ref", ""))
found = both[both.dist.notna()]
print(f"sjoin_nearest: {len(ref)} schools, farthest {ref.ref_m.max():,.0f} m")
print(f"within {RADIUS:,} m: {len(found)} schools, same distance for {(abs(found.dist - found.ref_m) < 1e-6).sum()}, "
      f"same library for {(found.library == found.library_ref).sum()}")
sjoin_nearest: 187 schools, farthest 4,309 m
within 3,000 m: 182 schools, same distance for 182, same library for 182

GeoPandas's sjoin_nearest, which has no radius, finds a library for all 187 schools, the farthest 4,309 m away. For the 182 schools Ibis matched within 3 km, both methods choose the same library at the same distance. The ranking is exact inside the radius, and the radius is the only difference.

4. Widen the radius only where it is needed

missing = result[result.dist.isna()].school_id.tolist()
far = schools.filter(_.school_id.isin(missing))
second = (far.join(libraries, far.g.d_within(libraries.lg, distance=10_000)).mutate(dist=_.g.distance(_.lg))
          .mutate(rank=ibis.row_number().over(group_by=_.school_id, order_by=[_.dist, _.lib_id]))
          .filter(_.rank == 0).select("school", "library", "dist").order_by("dist").execute())
print(second.round(0).to_string(index=False))
                          school                    library   dist
               Laingholm Primary          Titirangi Library 3629.0
  Bucklands Beach Primary School      Highland Park Library 3802.0
                    Drury School Sir Edmund Hillary Library 3875.0
              Coatesville School   Auckland Regional Prison 4235.0
Hobsonville Point Primary School   Auckland Regional Prison 4309.0

Searching again with a 10 km radius, for the five unmatched schools only, finds their libraries between 3,629 m and 4,309 m away, the same farthest distance sjoin_nearest reported. Two of them get "Auckland Regional Prison", a place Overture classifies as a library. A second pass for the few rows the first missed keeps the main join small.

Duplicates, and the k nearest

The data used on this page

187 primary schools (elementary_school) and 121 libraries from Overture Maps' 2026-11-18.0 places for Auckland, from a saved copy; CDLA Permissive 2.0. Both are projected to NZTM2000, so every distance is in metres.

from pathlib import Path

import geopandas as gpd
import ibis
import requests
from ibis import _

Path("data").mkdir(exist_ok=True)
name = "overture-auckland-places-2026-11-18.0.parquet"     # from s3://overturemaps-us-west-2/release/2026-11-18.0/theme=places
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/)
places = con.sql(f"select * replace (geometry::GEOMETRY as geometry) from read_parquet('data/{name}')")
nztm = lambda g: g.convert("EPSG:4326", "EPSG:2193")
schools = places.filter(_.basic_category == "elementary_school").select(school_id=_.id, school=_.name, g=nztm(_.geometry))
libraries = places.filter(_.basic_category == "library").select(lib_id=_.id, library=_.name, lg=nztm(_.geometry))
RADIUS = 3_000                                      # metres
print(f"{schools.count().execute()} primary schools, {libraries.count().execute()} libraries")
187 primary schools, 121 libraries

Example 1: one library, two places

other = libraries.select(lib_b=_.lib_id, library_b=_.library, lg_b=_.lg)
twins = (libraries.join(other, [libraries.lib_id < other.lib_b, libraries.lg.d_within(other.lg_b, distance=30)])
         .mutate(m=_.lg.distance(_.lg_b)).order_by("m"))
tw = twins.execute()
print(f"library pairs closer than 30 m: {len(tw)}")
print(tw[["library", "library_b", "m"]].round(1).to_string(index=False))
twin_ids = set(tw.lib_id) | set(tw.lib_b)
top3 = (cand.mutate(dist=_.g.distance(_.lg))
        .mutate(rank=ibis.row_number().over(group_by=_.school_id, order_by=[_.dist, _.lib_id]))
        .filter(_.rank < 3).execute())
pairs_in_top3 = top3.groupby("school_id").lib_id.apply(lambda ids: any({a, b} <= set(ids) for a, b in zip(tw.lib_id, tw.lib_b)))
print(f"schools whose three nearest include both places of one pair: {int(pairs_in_top3.sum())}")
library pairs closer than 30 m: 5
                                         library                   library_b    m
                                 Remuera Library             Remuera Library 10.5
Auckland Libraries Corporate Information Service                      Hāpaia 15.7
                  Ponsonby Community Toy Library      Leys Institute Library 20.2
                            Central City Library Auckland Libraries Research 23.4
                    St Heliers Community Library      St Heliers Bay Library 25.4
schools whose three nearest include both places of one pair: 12

Overture merges sources, and some libraries appear twice: two "Remuera Library" places 10.5 m apart, and St Heliers's library under two names 25.4 m apart. Five library pairs are closer than 30 m. A single nearest match is not affected, but a "three nearest" list is: for 12 schools it holds both places of one pair, so it counts one building twice. Merge places like these before ranking when the count matters.

The five Auckland primary schools with no library within 3 km and their nearest library. found by a second pass at 10 kmschoolnearest "library"metresLaingholm PrimaryTitirangi Library3,629Bucklands Beach PrimaryHighland Park Library3,802Drury SchoolSir Edmund Hillary Library3,875Coatesville SchoolAuckland Regional Prison4,235Hobsonville Point PrimaryAuckland Regional Prison4,309sjoin_nearest found the same farthest distance, 4,309 m spatialworkflow.io
Two of the five nearest 'libraries' are a prison library.

Example 2: the three nearest

k3 = (cand.mutate(dist=_.g.distance(_.lg))
      .mutate(rank=ibis.row_number().over(group_by=_.school_id, order_by=[_.dist, _.lib_id]))
      .filter(_.rank < 3)
      .group_by("school_id").aggregate(k=_.count(), mean_m=_.dist.mean()))
k = k3.execute()
print(f"schools with three libraries within {RADIUS:,} m: {(k.k == 3).sum()}; "
      f"mean distance to their three nearest: median {k[k.k == 3].mean_m.median():,.0f} m")
schools with three libraries within 3,000 m: 134; mean distance to their three nearest: median 1,603 m

Changing rank == 0 to rank < 3 keeps the three nearest. Within 3 km, 134 schools have three candidates, and their median mean distance to them is 1,603 m. The other 53 have fewer than three within the radius, the same cut-off as before applied to the third library instead of the first.

Why a radius is part of the question

What a search radius changes in an Ibis nearest-feature join. the radius is part of the questionno radius✕every pair measured: 22,627✕a match even 4.3 km away✕grows with rows × rows3 km radius✓957 pairs measured✓5 schools without a match✓same answer as sjoin_nearest for 182Report how many rows the radius left unmatched spatialworkflow.io
The radius makes the join cheap and leaves some rows without a match.

A nearest-neighbour join is a join plus a choice: pair each row with every candidate, then keep the best per row. Without an index-backed nearest operator, the pairing is the expensive part, and the radius is what makes it cheap enough. It also changes the answer: "the nearest library" becomes "the nearest library within 3 km, or none". GeoPandas's sjoin_nearest hides the same trade-off behind its max_distance argument, which defaults to no limit. In Ibis the limit is explicit, so pick it from the question, the distance beyond which a library no longer counts as near a school, and report how many rows it left without a match.

Where the ranking goes wrong

Checks for a nearest-feature join written with row_number in Ibis. before using the nearest matchleft join, not inner5 of 187 would vanishrank == 0 is the firstIbis counts from 0a tiebreaker after distancestable from run to runduplicates merged before k-nearest12 schools counted one twiceFive library pairs were closer than 30 m spatialworkflow.io
Four checks before using the nearest match.
  • row_number starts at 0. In Ibis, unlike SQL's ROW_NUMBER(), the first row is 0, so the nearest is rank == 0 and the three nearest are rank < 3.
  • A tiebreaker in the order. Ordering by distance alone leaves two libraries at the same distance in an arbitrary order that can change between runs. This page orders by [dist, lib_id] so the choice is stable.
  • Category noise. Overture's library includes a prison, a bank's learning centre and a toy library. Filter the candidates before ranking, or the nearest "library" may not be one.
  • Projected coordinates. The radius and the distances are metres because both sides were converted to NZTM2000 (distances in metres). On longitude/latitude the same code ranks by degrees.

FAQ

Can Ibis do a nearest join without a radius?

Yes, with a cross join ranked the same way, but it measures every pair: 22,627 here, which is fine, and millions for larger tables, which is not. A generous radius plus a second pass for the unmatched rows gives the same answer much faster.

Why not use sjoin_nearest on the executed tables?

For tables that fit in memory, that works and is what step 3 does as a check. The Ibis version keeps the work in DuckDB, so it also runs on tables read from files too large to load.