Skip to main content

Spatial Indexes

A spatial index reduces the number of geometry pairs that need expensive comparison. It changes the search plan, not the geometric definition of intersects, within, dwithin, or nearest.

Prerequisites​

Complete zonal statistics and geometry validity and topology. You should be able to state the exact predicate and boundary behavior required by the question.

Learning goals​

  • Separate bounding-box candidate generation from exact predicate evaluation.
  • Inspect scalar and array query results without confusing positional indices with feature IDs.
  • Explain how geometry shape, overlap, CRS, and predicate selectivity affect index usefulness.
  • Benchmark end-to-end workloads rather than extrapolating from tiny fixtures.

Filter, then refine​

Tree indexes usually store axis-aligned envelopes. An envelope hit means “possibly relevant,” not “the geometries match.” A thin diagonal, a polygon with a hole, or many overlapping envelopes can produce false-positive candidates. The refinement step applies the exact geometry predicate.

GeoPandas exposes a spatial index through .sindex. A query without a predicate returns bounding-box candidates. Supplying a supported predicate adds exact filtering. Spatial joins use the index internally, but their join type, cardinality, missing geometry behavior, CRS, and predicate still belong in the public result contract.

Index effectiveness depends on workload. Querying a few objects may not repay index construction. Highly overlapping bounding boxes can leave many candidates. Nearest queries need a metric CRS and often a maximum distance. Updates may require rebuilding or maintaining the index. Report dataset size, index-build policy, candidate count, exact-match count, hardware, and query distribution before making performance claims.

Worked example​

The query line lies entirely inside the hole of a polygon. Their envelopes overlap, but the geometries do not.

import json
from pathlib import Path

import geopandas as gpd
from shapely.geometry import Polygon, shape

fixture = Path("tests/fixtures/geospatial-data-science")
document = json.loads((fixture / "routes.geojson").read_text(encoding="utf-8"))
route = shape(next(feature["geometry"] for feature in document["features"] if feature["properties"]["route_id"] == "cross-town"))
frame = Polygon(
[(13.38, 52.51), (13.42, 52.51), (13.42, 52.53), (13.38, 52.53)],
holes=[[(13.384, 52.519), (13.416, 52.519), (13.416, 52.521), (13.384, 52.521)]],
)
zones = gpd.GeoSeries([frame], index=["frame-with-hole"], crs=document["metadata"]["crs"])
candidate_positions = zones.sindex.query(route)
exact_positions = zones.sindex.query(route, predicate="intersects")
print(f"candidates={len(candidate_positions)} candidate_ids={zones.index[candidate_positions].tolist()}")
print(f"exact_intersects={len(exact_positions)} exact_ids={zones.index[exact_positions].tolist()}")
print(f"envelopes_intersect={frame.envelope.intersects(route.envelope)} geometries_intersect={frame.intersects(route)}")

Expected output:

candidates=1 candidate_ids=['frame-with-hole']
exact_intersects=0 exact_ids=[]
envelopes_intersect=True geometries_intersect=False

The index returns array positions; the example deliberately maps them back to stable IDs. Candidate generation is separate from the exact predicate. This one-row fixture demonstrates correctness, not speed, and is not a benchmark.

Limitations and common mistakes​

  • Never treat envelope hits as exact matches unless the domain truly asks about envelopes.
  • Empty or missing geometry needs an explicit outcome before index construction.
  • An index does not repair invalid geometry or mismatched CRSs.
  • Nearest by bounding boxes is not automatically nearest by the required feature-to-feature metric.
  • A faster query can still be semantically wrong through predicate direction, boundary rules, or duplicate matches.

Practice​

Design an indexed point-in-polygon service. Specify stable identifiers, CRS, validity policy, boundary predicate, one-to-many behavior, index refresh rule, and counters for candidates and exact matches. Name a geometry distribution that would make the index less selective.

Next steps​

Next, treat precision and retention as part of the contract in geocoding and location privacy.

Primary sources​

Checked 2026-10-18: GeoPandas, spatial indexing and exact predicate filtering; GeoPandas, spatial joins; Shapely, STRtree; Shapely, binary predicates.