Spatial Databases

Spatial Database

GIS projects usually start with files: a shapefile of counties, a CSV of monitoring sites, a GeoTIFF of elevation. Files work well until several people edit the same layer, the data no longer fit in memory, or the same spatial question has to be answered many times a day. A spatial database stores geometries next to ordinary attributes, indexes them, and answers spatial questions in SQL. This notebook introduces the ideas that the rest of the module builds on, using real public health data from the USA Health Data Atlas.

Fifteen notebooks take a layer from a file into SQL, then into rasters, routes, time, and engines that outgrow one PostGIS server.

  • Spatial Database. This notebook. What a spatial database adds to a file, Simple Features, SRIDs, geometry and geography, vector and raster storage, and R-tree, GiST, and quadtree indexes. Counties and Superfund sites from the USA Health Data Atlas.
  • Environment setup. A PostGIS server in Docker, the Python clients, and psql, ogr2ogr, raster2pgsql, and shp2pgsql.
  • File-based spatial databases. SpatiaLite and GeoPackage: a full spatial database in one file.
  • Loading and Exporting Data. Getting layers into PostGIS and writing results back out.
  • Spatial SQL fundamentals. Area, length, distance, and ST_Transform, and when to use geography.
  • Spatial relationships and joins. Which county contains a site, which sites lie within a distance, which counties share a border, and which monitor is nearest.
  • Geometry processing. Buffer, dissolve, clip, simplify, and repair of invalid geometries.
  • Indexing and performance. GiST, SP-GiST, and BRIN, and how the planner uses them on a large table.
  • Rasters in PostGIS. Elevation and other grids stored as indexed tiles and combined with vectors.
  • Network analysis with pgRouting. pgRouting for distance and travel time along roads.
  • Spatiotemporal data. Monitors, site status, and rates that change from year to year.
  • In-database spatial analytics. Clustering, hex grids, and the H3 index, computed where the rows live.
  • DuckDB spatial and GeoParquet. GeoParquet queried in process, with no server.
  • Big data and cloud spatial engines. BigQuery GIS, Snowflake, and Apache Sedona when the table reaches billions of rows or many teams share it.
  • Analyzing New York City taxi trips. One kilometre pickup squares, the busiest zones and boroughs, peak hours, and short trips against long ones.

Library: geolattice.geolatticedb

Learning objectives

  1. Explain what a spatial database adds to a file-based workflow, and measure the difference on a real query.
  2. Describe the OGC Simple Features geometry model and read geometries in WKT, WKB and EWKB.
  3. Use SRIDs and the EPSG registry, and show how the choice of coordinate system changes areas and distances.
  4. Distinguish geometry from geography types, and vector from raster storage.
  5. Explain how R-tree, GiST and quadtree indexes prune spatial searches.
  6. Compare PostGIS, SpatiaLite, GeoPackage, DuckDB and the cloud engines (BigQuery GIS, Snowflake, Apache Sedona).

Data

Data Source Use
US county boundaries (3,221 counties) USA Health Data Atlas (assets/geojson_counties_fips.json, Census cartographic boundaries) Files vs. database, areas, R-tree
EPA Superfund National Priorities List sites (1,840 sites) USA Health Data Atlas (assets/superfund_npl_data.js) Point-in-polygon, quadtree
Onondaga County DEM GeoLattice Data/00_shared/raster_data/USA/Onondaga_DEM.tif Raster tiling

Contents

  1. Setup
  2. What a spatial database is
  3. The OGC Simple Features model: WKT, WKB and EWKB
  4. SRIDs and the EPSG registry
  5. Geometry vs. geography
  6. Vector vs. raster storage
  7. Spatial indexes: R-tree, GiST and quadtree
  8. The main options
  9. Summary and exercises

Setup

Installation. This notebook needs installation option 1 (vector, raster, CRS and visualization): pip install "geolattice[core]". See “Installation options” in the GeoLattice README.

Code
import warnings  # warning control
warnings.filterwarnings("ignore", category=UserWarning)  # hide routine library warnings

import struct  # decode binary (WKB) bytes
import time  # wall-clock timing
import numpy as np  # arrays
import pandas as pd  # tables
import geopandas as gpd  # vector data in Python
import shapely  # geometry engine (GEOS)
from shapely.geometry import (Point, LineString, Polygon, MultiPoint, MultiLineString,
                              MultiPolygon, GeometryCollection, box)  # OGC geometry classes
from pyproj import CRS, Geod  # coordinate reference systems and geodesic calculations
import rasterio  # raster reading
import matplotlib.pyplot as plt  # figures
from matplotlib.patches import Rectangle  # rectangles for index plots

from geolattice import geolatticedb as pdb  # GeoLattice spatial database tools (one API for four backends)

plt.rcParams.update({"figure.dpi": 110})  # figure resolution
Code
import os  # environment variables
import json  # JSON parsing
import urllib.request  # download files over HTTP
from pathlib import Path  # file paths

# The GeoLattice repository root: the first folder above this notebook that holds data/ and Tutorials/
HERE = Path.cwd()  # folder of this notebook
ROOT = next(p for p in [HERE, *HERE.parents] if (p / "Data").is_dir() and (p / "Tutorials").is_dir())
GEOLATTICE_DATA = ROOT / "Data"  # shared GeoLattice data folder
DATA = ROOT / "Data" / "06_spatialDB"  # data folder of this module
OUT = DATA / "outputs" / "06_01_01"  # outputs written by this notebook
OUT.mkdir(parents=True, exist_ok=True)  # create it if needed

# USA Health Data Atlas (https://zia207.github.io/USA-Health-Data-Atlas/): raw files on GitHub
ATLAS = "https://raw.githubusercontent.com/zia207/USA-Health-Data-Atlas/main"

def fetch(rel, base=ATLAS, folder="atlas"):  # download helper
    """Download a file once (default: from the Atlas repository) and return its local path."""
    path = DATA / folder / rel  # local cache path
    if not path.exists():  # download only if missing
        path.parent.mkdir(parents=True, exist_ok=True)  # create the cache folder
        print(f"Downloading {rel} ...")  # progress message
        urllib.request.urlretrieve(f"{base}/{rel}", path)  # copy the URL to the local path
    return path  # the local path

def atlas_js(rel):  # read an Atlas data file
    """Atlas data files are JavaScript (`window.X = {...};`); return the JSON object inside."""
    text = fetch(rel).read_text(encoding="utf-8")  # whole file as text
    return json.loads(text[text.index("=") + 1:].strip().rstrip(";"))  # strip the assignment and parse

def atlas_counties():  # county polygons of the Atlas
    """US county polygons (Census cartographic boundaries, EPSG:4326) with a 5-digit FIPS code."""
    g = gpd.read_file(fetch("assets/geojson_counties_fips.json"))  # GeoJSON from the Atlas
    g["fips"] = g["STATE"] + g["COUNTY"]  # state + county code = FIPS
    g = g.rename(columns={"NAME": "name", "STATE": "statefp", "CENSUSAREA": "census_sqmi"})  # tidy names
    return g[["fips", "statefp", "name", "census_sqmi", "geometry"]].set_crs(4326, allow_override=True)

def superfund_sites():  # EPA Superfund National Priorities List sites from the Atlas
    """Superfund NPL sites as points (EPSG:4326)."""
    s = pd.DataFrame(atlas_js("assets/superfund_npl_data.js")["sites"])  # one row per site
    s = s.dropna(subset=["lat", "lon"])  # keep sites with coordinates
    s = s[["epa_id", "name", "status", "state", "city", "county", "score", "listed", "lat", "lon"]]  # main fields
    return gpd.GeoDataFrame(s, geometry=gpd.points_from_xy(s.lon, s.lat), crs=4326)  # points

# PostGIS connection string (see 06_01_02 for the Docker container); override with GEOLATTICE_PG_DSN
PG_DSN = os.environ.get("GEOLATTICE_PG_DSN", "postgresql://postgres:geolattice@localhost:5432/geolattice")
print("Repository:", ROOT)  # where the data are read from
Repository: /home/zia207/Github/GeoLattice
Code
counties = atlas_counties()  # all US county polygons
sites = superfund_sites()  # Superfund NPL sites
print(f"{len(counties):,} counties, {len(sites):,} Superfund sites")  # sizes
sites.head(3)  # first rows
3,221 counties, 1,840 Superfund sites
epa_id name status state city county score listed lat lon geometry
0 CTD980670814 Kellogg-Deering Well Field NPL Site CT Norwalk Fairfield 39.92 09/21/1984 41.130550 -73.431950 POINT (-73.43195 41.13055)
1 CTD980670806 Old Southington Landfill Deleted NPL Site CT Southington Hartford 54.35 09/21/1984 41.579169 -72.881939 POINT (-72.88194 41.57917)
2 CTD004532610 Revere Textile Prints Corp. Deleted NPL Site CT Sterling Windham 41.06 07/22/1987 41.708331 -71.829169 POINT (-71.82917 41.70833)

Spatial database

A spatial database is a database management system (DBMS) with four additions:

  1. Geometry types that store points, lines and polygons in table columns, next to ordinary attributes.
  2. Spatial functions in SQL (ST_Area, ST_Intersects, ST_Buffer, …), defined by the OGC Simple Features for SQL and ISO 19125 standards.
  3. Spatial indexes that find candidate geometries without scanning the whole table.
  4. A catalog of coordinate reference systems (spatial_ref_sys) so every geometry carries an SRID.

Everything a DBMS already does still applies: many users read and write at the same time, changes happen inside transactions that either complete or roll back, constraints keep the data consistent, and the query planner decides how to answer each question.

Property Files (Shapefile, GeoJSON, CSV) Spatial database
Reading one feature Usually parse the whole file Index lookup, only matching rows
Several users editing Last save wins, risk of corruption Concurrent transactions, row locks
Data larger than memory Must fit in RAM to analyze Streams from disk, returns only results
Integrity None (any value, any geometry) Types, keys, CHECK constraints, valid SRIDs
Sharing Copy files around One copy, access by users and roles
Analysis language Python/R scripts SQL, plus Python/R clients

Files remain the right choice for exchange and archiving. The database is the right choice when data are shared, updated or queried repeatedly. We measure the difference on one simple question: which county is a Superfund site in, and how many sites does each New York county have?

File workflow

A GeoJSON file has no index, so finding one county means reading the whole file. The cell below loads geojson_counties_fips.json into a GeoDataFrame (all 3,221 county polygons), builds a FIPS code from the state and county codes, and keeps 36067 (Onondaga County, New York). The clock is the lesson: that one row is available only after every polygon has been parsed.

Code
# File workflow: every question starts by reading the files again
t0 = time.perf_counter()  # start the clock
c_file = gpd.read_file(fetch("assets/geojson_counties_fips.json"))  # parse all 3,221 polygons
c_file["fips"] = c_file["STATE"] + c_file["COUNTY"]  # FIPS code
onondaga_file = c_file[c_file.fips == "36067"]  # keep one county
t_file = time.perf_counter() - t0  # elapsed time
print(f"File: read all {len(c_file):,} features to get 1 county in {t_file*1000:.0f} ms")  # report
File: read all 3,221 features to get 1 county in 94 ms

Database workflow

The counties and Superfund sites are copied once into a DuckDB file, atlas.duckdb. duck.load stores the geometries and builds an R-tree on them, and a B-tree index is added on counties.fips. The same county as above (36067) is then one indexed lookup, and the clock compares that lookup with the full file read.

Code
# Database workflow: load once, then ask questions with SQL
db_path = OUT / "atlas.duckdb"  # a DuckDB database file
db_path.unlink(missing_ok=True)  # start fresh
duck = pdb.connect("duckdb", path=db_path)  # open (create) the database
duck.load(counties, "counties")  # copy the counties into a table (with an R-tree index)
duck.load(sites, "superfund")  # copy the sites
duck.execute("CREATE INDEX counties_fips ON counties (fips)")  # ordinary B-tree index on the FIPS code

t0 = time.perf_counter()  # start the clock
onondaga_db = duck.query("SELECT fips, name, geom FROM counties WHERE fips = '36067'")  # one county
t_db = time.perf_counter() - t0  # elapsed time
print(f"Database: indexed lookup of 1 county in {t_db*1000:.1f} ms ({t_file/t_db:.0f} times faster)")
onondaga_db  # the result is a GeoDataFrame
Database: indexed lookup of 1 county in 3.4 ms (28 times faster)
fips name geom
0 36067 Onondaga POLYGON ((-76.49931 43.09795, -76.47922 43.227...

The query counts Superfund sites inside each New York county. counties is aliased c and superfund is aliased s. ST_Within(s.geom, c.geom) keeps a site only when its point lies inside the county polygon, so the join is point-in-polygon. statefp = '36' limits the counties to New York. GROUP BY c.name makes one row per county: count(s.epa_id) is the number of sites, and round(avg(s.score), 1) is the mean Hazard Ranking System score to one decimal place. The rows are sorted by that count, and LIMIT 8 keeps the eight counties with the most sites. duck.query runs the statement and returns the table.

Code
# A spatial question in SQL: Superfund sites per New York county (point-in-polygon)
sql = '''
SELECT c.name AS county, count(s.epa_id) AS n_sites, round(avg(s.score), 1) AS mean_hrs_score
FROM counties c
JOIN superfund s ON ST_Within(s.geom, c.geom)   -- spatial join predicate
WHERE c.statefp = '36'                           -- New York
GROUP BY c.name
ORDER BY n_sites DESC
LIMIT 8
'''
duck.query(sql)  # run it and return a table
county n_sites mean_hrs_score
0 Nassau 18 43.6
1 Suffolk 16 40.2
2 Broome 8 35.7
3 Niagara 7 37.0
4 Dutchess 6 44.9
5 Saratoga 4 45.5
6 Orange 4 38.3
7 Oswego 4 26.0

The file workflow has to parse every polygon before it can return one; the database answers from an index and returns only the requested row. The spatial join reads like the question itself, and the database chooses how to run it (here with the R-tree index on counties.geom). Suffolk and Nassau counties on Long Island have the most Superfund sites in New York, many of them groundwater contamination sites. The HRS score is the EPA Hazard Ranking System score used to list a site.

Transactions protect the data. The cell below counts the county rows, opens a transaction with BEGIN, and deletes every New York county (statefp = '36'). The count falls while that transaction is open. ROLLBACK throws the delete away, and the count returns to the number from before BEGIN. Other sessions do not see the change until COMMIT.

Code
n_before = duck.execute("SELECT count(*) FROM counties")[0][0]  # rows before
duck.execute("BEGIN TRANSACTION")  # start a transaction
duck.execute("DELETE FROM counties WHERE statefp = '36'")  # delete New York by mistake
n_during = duck.execute("SELECT count(*) FROM counties")[0][0]  # rows inside the transaction
duck.execute("ROLLBACK")  # undo everything since BEGIN
n_after = duck.execute("SELECT count(*) FROM counties")[0][0]  # rows after the rollback
print(f"before: {n_before:,}   inside transaction: {n_during:,}   after ROLLBACK: {n_after:,}")
before: 3,221   inside transaction: 3,159   after ROLLBACK: 3,221

The OGC Simple Features model: WKT, WKB and EWKB

The Open Geospatial Consortium (OGC) Simple Features specification (ISO 19125) defines the geometry types used by every spatial database, GDAL, GEOS and Shapely. Each geometry is built from coordinates joined by straight lines:

Type Built from Example in public health
POINT one coordinate a hospital, an air quality monitor
LINESTRING two or more points a road segment, a river
POLYGON one closed exterior ring, optional holes a county, a ZIP code area
MULTIPOINT, MULTILINESTRING, MULTIPOLYGON collections of one type the islands of a county
GEOMETRYCOLLECTION any mix the result of an intersection

Coordinates can have a third (Z, elevation) and a fourth (M, a measure such as time) dimension. Geometries travel between programs in two encodings:

  • WKT (Well-Known Text): human-readable, e.g. POINT (-76.15 43.05).
  • WKB (Well-Known Binary): compact bytes used inside databases and GeoPackage/GeoParquet files.

PostGIS extends both with an SRID: EWKT (SRID=4326;POINT (-76.15 43.05)) and EWKB.

Code
examples = {  # one example of each OGC type (lon/lat)
    "POINT": Point(-76.15, 43.05),
    "LINESTRING": LineString([(-76.3, 42.9), (-76.15, 43.05), (-75.95, 43.0)]),
    "POLYGON": Polygon([(-76.4, 42.8), (-75.9, 42.8), (-75.9, 43.2), (-76.4, 43.2)],
                       holes=[[(-76.2, 42.95), (-76.05, 42.95), (-76.05, 43.05), (-76.2, 43.05)]]),
    "MULTIPOINT": MultiPoint([(-76.3, 42.9), (-76.0, 43.1), (-76.2, 43.15)]),
    "MULTILINESTRING": MultiLineString([[(-76.4, 42.9), (-76.1, 42.9)], [(-76.3, 43.1), (-76.0, 43.15)]]),
    "MULTIPOLYGON": MultiPolygon([box(-76.4, 42.8, -76.2, 43.0), box(-76.1, 43.0, -75.9, 43.2)]),
}
examples["GEOMETRYCOLLECTION"] = GeometryCollection([examples["POINT"], examples["LINESTRING"]])  # a mix
rows = []  # one row per type
for name, g in examples.items():  # every example
    rows.append({"type": g.geom_type, "WKT": g.wkt[:60] + ("..." if len(g.wkt) > 60 else ""),
                 "WKB bytes": len(g.wkb), "coordinates": shapely.get_num_coordinates(g),
                 "dimension": shapely.get_dimensions(g)})  # 0 = point, 1 = line, 2 = area
pd.DataFrame(rows)  # show the table
type WKT WKB bytes coordinates dimension
0 Point POINT (-76.15 43.05) 21 1 0
1 LineString LINESTRING (-76.3 42.9, -76.15 43.05, -75.95 43) 57 3 1
2 Polygon POLYGON ((-76.4 42.8, -75.9 42.8, -75.9 43.2, ... 177 10 2
3 MultiPoint MULTIPOINT ((-76.3 42.9), (-76 43.1), (-76.2 4... 72 3 0
4 MultiLineString MULTILINESTRING ((-76.4 42.9, -76.1 42.9), (-7... 91 4 1
5 MultiPolygon MULTIPOLYGON (((-76.2 42.8, -76.2 43, -76.4 43... 195 10 2
6 GeometryCollection GEOMETRYCOLLECTION (POINT (-76.15 43.05), LINE... 87 4 1
Code
fig, axes = plt.subplots(1, 7, figsize=(17, 2.8))  # one panel per type
for ax, (name, g) in zip(axes, examples.items()):  # every example
    gpd.GeoSeries([g]).plot(ax=ax, color="#9ecae1", edgecolor="#08519c", markersize=40, linewidth=2)  # draw it
    ax.set_title(name, fontsize=8); ax.set_xticks([]); ax.set_yticks([])  # title, no ticks
    ax.set_xlim(-76.45, -75.85); ax.set_ylim(42.75, 43.25)  # same window for all
plt.tight_layout(); plt.show()  # arrange and draw

WKB is compact: a point costs 21 bytes (1 byte order flag, 4 bytes type code, two 8-byte doubles). We can decode those bytes by hand to see that nothing is hidden:

Code
p = examples["POINT"]  # the example point
raw = shapely.to_wkb(p)  # standard WKB
order = "<" if raw[0] == 1 else ">"  # first byte: 1 = little endian, 0 = big endian
gtype = struct.unpack(order + "I", raw[1:5])[0]  # next 4 bytes: geometry type code (1 = Point)
x, y = struct.unpack(order + "dd", raw[5:21])  # then two 8-byte doubles
print("WKB hex :", raw.hex())  # the bytes
print(f"decoded : byte order={'little' if order == '<' else 'big'}, type={gtype}, x={x}, y={y}")

ewkb = shapely.to_wkb(shapely.set_srid(p, 4326), include_srid=True, hex=True)  # PostGIS-style EWKB
print("EWKB hex:", ewkb, " <- the SRID 4326 (0x10E6) travels with the geometry")  # SRID inside
print("EWKT    :", f"SRID=4326;{p.wkt}")  # extended WKT
WKB hex : 01010000009a999999990953c06666666666864540
decoded : byte order=little, type=1, x=-76.15, y=43.05
EWKB hex: 0101000020E61000009A999999990953C06666666666864540  <- the SRID 4326 (0x10E6) travels with the geometry
EWKT    : SRID=4326;POINT (-76.15 43.05)

A database also checks that geometries are valid: polygon rings must close and must not cross themselves. Invalid geometries give wrong areas and wrong overlay results, so they are repaired with ST_MakeValid (or shapely.make_valid). Notebook 06_02_04 covers validity in depth.

Code
bowtie = shapely.from_wkt("POLYGON ((0 0, 2 2, 2 0, 0 2, 0 0))")  # a ring that crosses itself
fixed = shapely.make_valid(bowtie)  # repair it
print("valid?", bowtie.is_valid, "| reason:", shapely.is_valid_reason(bowtie))  # diagnosis
print("area before repair:", bowtie.area, "| after:", fixed.area, "|", fixed.wkt)  # 0 vs the true area 2
valid? False | reason: Self-intersection[1 1]
area before repair: 0.0 | after: 2.0 | MULTIPOLYGON (((0 2, 1 1, 0 0, 0 2)), ((2 0, 1 1, 2 2, 2 0)))

SRIDs and the EPSG registry

Coordinates are only numbers until we know their coordinate reference system (CRS). Databases record the CRS of each geometry column as an integer SRID (spatial reference identifier). The SRIDs normally come from the EPSG registry, which assigns codes to datums, ellipsoids and projections. PostGIS copies the registry into its spatial_ref_sys table; DuckDB and Shapely use PROJ, which ships the same registry.

Code
codes = [4326, 4269, 3857, 5070, 32618, 2261]  # common SRIDs for US work
rows = []  # one row per CRS
for code in codes:  # every code
    crs = CRS.from_epsg(code)  # look it up in the EPSG registry (via PROJ)
    rows.append({"EPSG": code, "name": crs.name, "kind": "geographic" if crs.is_geographic else "projected",
                 "units": crs.axis_info[0].unit_name, "datum": crs.datum.name,
                 "area of use": crs.area_of_use.name[:45]})  # main facts
pd.DataFrame(rows)  # show the table
EPSG name kind units datum area of use
0 4326 WGS 84 geographic degree World Geodetic System 1984 ensemble World.
1 4269 NAD83 geographic degree North American Datum 1983 North America - onshore and offshore: Canada
2 3857 WGS 84 / Pseudo-Mercator projected metre World Geodetic System 1984 ensemble World between 85.06°S and 85.06°N.
3 5070 NAD83 / Conus Albers projected metre North American Datum 1983 United States (USA) - CONUS onshore - Alabama
4 32618 WGS 84 / UTM zone 18N projected metre World Geodetic System 1984 ensemble Between 78°W and 72°W, northern hemisphere be
5 2261 NAD83 / New York Central (ftUS) projected US survey foot North American Datum 1983 United States (USA) - New York - counties of

The SRID decides what ST_Area and ST_Distance return. We compute the area of Onondaga County, NY in several systems and compare with the Census land area (CENSUSAREA, square miles):

Code
ono = counties[counties.fips == "36067"]  # Onondaga County (EPSG:4326)
census_km2 = ono.census_sqmi.iloc[0] * 2.589988  # Census land area, square miles -> km²
geod = Geod(ellps="WGS84")  # the WGS84 ellipsoid
geodesic_km2 = abs(geod.geometry_area_perimeter(ono.geometry.iloc[0])[0]) / 1e6  # area on the ellipsoid
rows = {"EPSG:4326 (degrees², meaningless)": ono.geometry.area.iloc[0],
        "EPSG:3857 Web Mercator": ono.to_crs(3857).area.iloc[0] / 1e6,
        "EPSG:32618 UTM 18N": ono.to_crs(32618).area.iloc[0] / 1e6,
        "EPSG:5070 CONUS Albers (equal area)": ono.to_crs(5070).area.iloc[0] / 1e6,
        "geodesic (geography type)": geodesic_km2}  # area in each system
tab = pd.DataFrame({"area": rows}).round(3)  # as a table
tab["vs geodesic (%)"] = ((tab["area"] / geodesic_km2 - 1) * 100).round(2)  # relative difference
tab.loc["Census land area (no water)", "area"] = round(census_km2, 3)  # reference value
tab  # show the table
area vs geodesic (%)
EPSG:4326 (degrees², meaningless) 0.236 -99.99
EPSG:3857 Web Mercator 3993.047 87.13
EPSG:32618 UTM 18N 2132.636 -0.06
EPSG:5070 CONUS Albers (equal area) 2133.850 0.00
geodesic (geography type) 2133.833 0.00
Census land area (no water) 2016.021 NaN

Web Mercator inflates the area of Onondaga County by 87%, because its scale grows with latitude (about 1/cos²(43°) for areas). UTM and Albers stay within a fraction of a percent of the geodesic area. The Census land area is smaller still because it excludes Onondaga Lake and other water. The rule: store data in EPSG:4326 if you like, but measure in an equal-area projection (areas), a local conformal projection (short distances) or on the ellipsoid (geography).

Geometry vs. geography

PostGIS offers two column types:

  • geometry: coordinates on a flat plane. Calculations are fast and use Cartesian formulas in the units of the SRID.
  • geography: coordinates on the WGS84 ellipsoid (lon/lat). Distances, areas and buffers are computed along the curved surface and returned in metres.

Geography is the safe choice for global data and long distances; geometry with a suitable projection is faster and supports every function. We compare distances between county centroids (taken in Albers, then converted to lon/lat):

Code
cent = counties.set_index("fips").to_crs(5070).centroid.to_crs(4326)  # county centroids (lon/lat)
pairs = {"Onondaga - Erie (NY)": ("36067", "36029"),
         "Onondaga - Miami-Dade (FL)": ("36067", "12086"),
         "Onondaga - Los Angeles (CA)": ("36067", "06037")}  # short, medium and long pairs
rows = []  # one row per pair
for label, (a, b) in pairs.items():  # every pair
    pa, pb = cent[a], cent[b]  # the two centroids
    _, _, d_geo = geod.inv(pa.x, pa.y, pb.x, pb.y)  # geodesic distance (geography), metres
    two = gpd.GeoSeries([pa, pb], crs=4326)  # both points as a series
    d_deg = pa.distance(pb) * 111.32e3  # planar distance in degrees x 111 km (a common shortcut)
    d_merc = two.to_crs(3857).iloc[0].distance(two.to_crs(3857).iloc[1])  # Web Mercator
    d_alb = two.to_crs(5070).iloc[0].distance(two.to_crs(5070).iloc[1])  # CONUS Albers
    rows.append({"pair": label, "geodesic km": d_geo / 1e3, "degrees x 111 km": d_deg / 1e3,
                 "Web Mercator km": d_merc / 1e3, "Albers km": d_alb / 1e3})  # store
dist = pd.DataFrame(rows).set_index("pair")  # as a table
err = dist.drop(columns="geodesic km").div(dist["geodesic km"], axis=0).sub(1).mul(100)  # % error
dist.round(1).join(err.round(1).add_suffix(" err %"))  # distances and errors
geodesic km degrees x 111 km Web Mercator km Albers km degrees x 111 km err % Web Mercator km err % Albers km err %
pair
Onondaga - Erie (NY) 209.0 283.7 284.8 207.9 35.7 36.3 -0.6
Onondaga - Miami-Dade (FL) 1970.3 1996.5 2411.5 1978.4 1.3 22.4 0.4
Onondaga - Los Angeles (CA) 3741.1 4777.7 4840.7 3716.7 27.7 29.4 -0.7
Code
fig, ax = plt.subplots(figsize=(10, 5))  # one map
states = counties.dissolve("statefp")  # state outlines from the counties
states[~states.index.isin(["02", "15", "72"])].boundary.plot(ax=ax, color="0.7", lw=0.5)  # lower 48
a, b = cent["36067"], cent["06037"]  # Onondaga and Los Angeles
ax.plot([a.x, b.x], [a.y, b.y], "--", color="#d95f02", label="straight line in lon/lat")  # planar path
pts = geod.npts(a.x, a.y, b.x, b.y, 100)  # 100 points along the geodesic
ax.plot([p[0] for p in pts], [p[1] for p in pts], color="#1b9e77", lw=2, label="geodesic (geography)")
ax.legend(loc="lower left"); ax.set_title("Onondaga to Los Angeles: the shortest path is not straight in lon/lat")
ax.set_xlabel("longitude"); ax.set_ylabel("latitude"); plt.show()  # labels and draw

Treating degrees as a flat grid overstates the Onondaga to Erie distance by 36%. The pair runs almost east to west, and a degree of longitude spans only about 81 km at 43°N, not 111 km. For the mostly north-south Miami-Dade pair the same shortcut errs by only 1%, so the error depends on direction as well as distance. Web Mercator overstates all three distances by 22 to 36%. The Albers projection stays within 1% for these pairs but still distorts distances away from its standard parallels (29.5°N and 45.5°N). Geography gives the right answer everywhere without choosing a projection, at some cost in speed. The map shows why: the shortest path on the ellipsoid curves northward when drawn on a lon/lat grid.

Vector vs. raster storage

Spatial databases store two kinds of data:

Vector Raster
Model discrete features (points, lines, polygons) with attributes a regular grid of cells with values
PostGIS type geometry, geography raster (extension postgis_raster)
Typical data counties, hospitals, roads elevation, land cover, satellite images, PM2.5 surfaces
How it is stored one row per feature one row per tile (e.g. 100 x 100 cells)

Rasters are cut into tiles so that a query reads only the tiles it needs, through the same spatial index used for vectors. raster2pgsql does this tiling when loading. Rasters can also stay outside the database (out-db) with the table holding only tile footprints and file paths; notebook 06_03_01 compares both. Below we tile the Onondaga County DEM the way raster2pgsql -t 100x100 would:

Code
with rasterio.open(GEOLATTICE_DATA / "00_shared" / "raster_data" / "USA" / "Onondaga_DEM.tif") as src:  # the DEM
    dem = src.read(1, masked=True)  # first band, nodata masked
    tr, crs_dem, nodata = src.transform, src.crs, src.nodata  # georeferencing
print(f"DEM: {dem.shape[0]} rows x {dem.shape[1]} cols, cell {tr.a * 3600:.1f} arc-seconds, CRS {crs_dem}")

tile = 100  # tile size in cells
tiles = []  # one record per tile (what raster2pgsql writes as rows)
for r0 in range(0, dem.shape[0], tile):  # tile rows
    for c0 in range(0, dem.shape[1], tile):  # tile columns
        block = dem[r0:r0 + tile, c0:c0 + tile]  # the cells of this tile
        x0, y0 = tr * (c0, r0); x1, y1 = tr * (c0 + block.shape[1], r0 + block.shape[0])  # footprint
        tiles.append({"rid": len(tiles) + 1, "cells": block.size, "valid": int(block.count()),
                      "geometry": box(min(x0, x1), min(y0, y1), max(x0, x1), max(y0, y1))})
tiles = gpd.GeoDataFrame(tiles, crs=crs_dem)  # tile footprints
print(f"{len(tiles)} tiles; {int((tiles.valid == 0).sum())} contain only nodata and could be skipped")
DEM: 443 rows x 534 cols, cell 4.1 arc-seconds, CRS EPSG:4326
30 tiles; 2 contain only nodata and could be skipped
Code
fig, ax = plt.subplots(figsize=(7, 6))  # one map
ext = (tr.c, tr.c + tr.a * dem.shape[1], tr.f + tr.e * dem.shape[0], tr.f)  # image extent
im = ax.imshow(dem, extent=ext, cmap="terrain")  # the elevation grid
tiles.boundary.plot(ax=ax, color="k", lw=0.4)  # tile boundaries
for _, t in tiles.iloc[::7].iterrows():  # label every 7th tile with its row id
    ax.annotate(t.rid, t.geometry.centroid.coords[0], fontsize=6, ha="center")
plt.colorbar(im, ax=ax, label="elevation (m)"); ax.set_title("Raster stored as 100 x 100 cell tiles (one row each)")
ax.set_xticks([]); ax.set_yticks([]); plt.show()  # no ticks, draw

Spatial indexes: R-tree, GiST and quadtree

Testing whether each of 1,840 sites lies in each of 3,221 counties means about 5.9 million point-in-polygon tests. A spatial index avoids most of them in two steps:

  1. Filter: compare cheap bounding boxes using the index, and keep only candidate pairs.
  2. Refine: run the exact (expensive) geometric test on the candidates only.

The main index structures are:

  • R-tree: groups nearby bounding boxes into larger boxes, level by level. Used by SpatiaLite and GeoPackage (SQLite R*Tree), DuckDB spatial and Shapely (STRtree).
  • GiST (Generalized Search Tree): PostgreSQL’s framework for balanced search trees. PostGIS implements an R-tree on top of GiST, which is why spatial indexes in PostGIS are created USING GIST.
  • Quadtree / k-d tree: split space recursively into four (or two) parts. PostgreSQL offers them through SP-GiST (space-partitioned GiST).
  • BRIN (Block Range Index): stores one bounding box per block of table pages. Tiny, and fast for data already sorted in space. Notebook 06_02_05 benchmarks all three in PostGIS.
Code
geoms = np.asarray(counties.geometry)  # county polygons as a NumPy array
pts = np.asarray(sites.geometry)  # site points

t0 = time.perf_counter()  # brute force on a sample: test every site against every county
sample = pts[:200]  # 200 sites keep the brute-force run short
brute = shapely.contains(geoms[None, :], sample[:, None])  # (200 sites x 3,221 counties) exact tests
t_brute = (time.perf_counter() - t0) * len(pts) / len(sample)  # scale up to all sites

t0 = time.perf_counter()  # with an R-tree (Shapely STRtree)
tree = shapely.STRtree(geoms)  # build the index
cand = tree.query(pts)  # filter: bounding boxes only -> candidate (site, county) pairs
hit = tree.query(pts, predicate="within")  # filter + refine: exact test on candidates only
t_tree = time.perf_counter() - t0  # elapsed

print(f"brute force : {len(pts) * len(geoms):>10,} exact tests  ~{t_brute:6.2f} s (extrapolated)")
print(f"R-tree      : {cand.shape[1]:>10,} candidates   {t_tree:6.3f} s  -> {hit.shape[1]:,} matches")
print(f"the index removed {1 - cand.shape[1] / (len(pts) * len(geoms)):.4%} of the tests")
brute force :  5,926,640 exact tests  ~  0.33 s (extrapolated)
R-tree      :      2,755 candidates    0.003 s  -> 1,828 matches
the index removed 99.9535% of the tests

To see what an R-tree looks like, we build one by hand with the Sort-Tile-Recursive (STR) packing used by STRtree: sort the boxes by x, cut them into vertical slices, sort each slice by y, and group neighbours into nodes of at most M entries. Each node stores the box that encloses its children, so a search descends only into nodes whose box overlaps the query.

Code
def str_level(boxes, m=6):  # one level of Sort-Tile-Recursive packing
    """Group boxes (minx, miny, maxx, maxy) into parent nodes of at most m entries."""
    boxes = np.asarray(boxes)  # array of boxes
    n_nodes = int(np.ceil(len(boxes) / m))  # number of parent nodes
    n_slices = int(np.ceil(np.sqrt(n_nodes)))  # vertical slices
    cx = (boxes[:, 0] + boxes[:, 2]) / 2; cy = (boxes[:, 1] + boxes[:, 3]) / 2  # box centres
    parents = []  # enclosing boxes of the new nodes
    for sl in np.array_split(np.argsort(cx), n_slices):  # slices sorted by x
        sl = sl[np.argsort(cy[sl])]  # sort each slice by y
        for grp in np.array_split(sl, int(np.ceil(len(sl) / m))):  # groups of up to m boxes
            b = boxes[grp]  # the children
            parents.append([b[:, 0].min(), b[:, 1].min(), b[:, 2].max(), b[:, 3].max()])  # their MBR
    return np.array(parents)  # one box per parent

ny = counties[counties.statefp == "36"].to_crs(5070)  # New York counties (Albers)
leaf = ny.bounds.values  # level 0: one box per county
level1 = str_level(leaf); level2 = str_level(level1)  # two levels of parent nodes
fig, ax = plt.subplots(figsize=(9, 7))  # one map
ny.plot(ax=ax, color="#f0f0f0", edgecolor="0.6", lw=0.4)  # the counties
for boxes, col, lw in [(leaf, "#9ecae1", 0.6), (level1, "#3182bd", 1.3), (level2, "#d95f02", 2.4)]:  # three levels
    for x0, y0, x1, y1 in boxes:  # every box
        ax.add_patch(Rectangle((x0, y0), x1 - x0, y1 - y0, fill=False, ec=col, lw=lw))
ax.set_title(f"R-tree of New York counties: {len(leaf)} county boxes -> {len(level1)} nodes -> {len(level2)} nodes")
ax.set_xticks([]); ax.set_yticks([]); plt.show()  # no ticks, draw

A quadtree partitions space instead of grouping objects: each cell splits into four children whenever it holds more than a set number of points. Dense areas (the Northeast, New Jersey, the Great Lakes industrial belt) get deep, small cells, while empty areas stay as large cells.

Code
def quadtree(xy, x0, y0, x1, y1, cap=25, depth=0, out=None):  # recursive point quadtree
    """Return the leaf cells (x0, y0, x1, y1, n) of a point quadtree with capacity `cap`."""
    out = [] if out is None else out  # list of leaf cells
    inside = xy[(xy[:, 0] >= x0) & (xy[:, 0] < x1) & (xy[:, 1] >= y0) & (xy[:, 1] < y1)]  # points in the cell
    if len(inside) <= cap or depth >= 10:  # small enough: keep as a leaf
        out.append((x0, y0, x1, y1, len(inside))); return out
    xm, ym = (x0 + x1) / 2, (y0 + y1) / 2  # cell centre
    for a, b, c, d in [(x0, y0, xm, ym), (xm, y0, x1, ym), (x0, ym, xm, y1), (xm, ym, x1, y1)]:  # 4 children
        quadtree(inside, a, b, c, d, cap, depth + 1, out)  # recurse
    return out

conus = sites.cx[-125:-66, 24:50].to_crs(5070)  # sites in the lower 48 (lon/lat window), in Albers
xy = np.column_stack([conus.geometry.x, conus.geometry.y])  # coordinates
x0, y0, x1, y1 = xy[:, 0].min(), xy[:, 1].min(), xy[:, 0].max() + 1, xy[:, 1].max() + 1  # root cell
cells = quadtree(xy, x0, y0, x1, y1)  # build the tree
fig, ax = plt.subplots(figsize=(11, 6))  # one map
states.drop(["02", "15", "72"], errors="ignore").to_crs(5070).boundary.plot(ax=ax, color="0.75", lw=0.4)
ax.scatter(xy[:, 0], xy[:, 1], s=3, color="#d95f02")  # the sites
for a, b, c, d, n in cells:  # every leaf cell
    ax.add_patch(Rectangle((a, b), c - a, d - b, fill=False, ec="#3182bd", lw=0.5))
ax.set_title(f"Quadtree of {len(xy):,} Superfund sites: {len(cells)} leaf cells, at most 25 sites each")
ax.set_xticks([]); ax.set_yticks([]); plt.show()  # no ticks, draw

The main options

Engine Storage Best for Spatial index Limits
PostGIS (PostgreSQL) server shared, multi-user data; the most complete function set; rasters, routing (pgRouting), time series GiST (R-tree), SP-GiST, BRIN needs a server to run and administer
SpatiaLite (SQLite) one file single-user analysis, embedded apps, mobile R*Tree virtual tables one writer at a time
GeoPackage (OGC standard on SQLite) one file data exchange; replaces the shapefile R*Tree (rtree_ tables) a format first, a database second
DuckDB spatial file or memory, in-process fast analytics on large files (Parquet, GeoParquet, CSV) on a laptop R-tree (optional) single-machine, few concurrent writers
BigQuery GIS Google Cloud, serverless petabyte tables, GEOGRAPHY on the sphere clustering on geography (S2 cells) pay per data scanned
Snowflake cloud data warehouse enterprise analytics, GEOGRAPHY/GEOMETRY types, H3 functions search optimization pay per compute time
Apache Sedona Spark, Flink, Snowflake distributed processing of billions of geometries spatial partitioning (KDB-tree, quadtree) + local indexes needs a cluster for large data

The first four use the same SQL vocabulary (ST_Intersects, ST_Area, …) because they all follow Simple Features for SQL. geolattice.geolatticedb wraps the local engines behind one interface, so the same Python code runs on each. Here the Superfund question from above runs on SpatiaLite, GeoPackage and DuckDB, and on PostGIS if the server from notebook 06_01_02 is running:

Code
ny_c = counties[counties.statefp == "36"]  # New York counties
ny_s = sites[sites.state == "NY"]  # New York Superfund sites
targets = {"spatialite": dict(path=OUT / "demo.sqlite"), "geopackage": dict(path=OUT / "demo.gpkg"),
           "duckdb": dict(path=None), "postgis": dict(dsn=PG_DSN)}  # connection settings per backend
results, times = {}, {}  # per-backend output
for backend, kw in targets.items():  # every backend
    if "path" in kw and kw["path"] is not None:
        kw["path"].unlink(missing_ok=True)  # start each file fresh
    try:
        with pdb.connect(backend, **kw) as con:  # same call for every engine
            con.load(ny_c, "ny_counties"); con.load(ny_s, "ny_sites")  # same loading call
            t0 = time.perf_counter()  # time the join only
            j = con.spatial_join("ny_sites", "ny_counties", predicate="within", right_columns=["name"])  # same join
            times[backend] = time.perf_counter() - t0  # elapsed
            results[backend] = j.groupby("right_name").size()  # sites per county
    except Exception as exc:  # e.g. PostGIS server not running
        print(f"{backend:<11} skipped: {type(exc).__name__}: {str(exc).splitlines()[0][:90]}")
cmp = pd.DataFrame(results).fillna(0).astype(int).sort_values(list(results)[0], ascending=False)  # side by side
print("identical results on all engines:", bool((cmp.nunique(axis=1) == 1).all()))  # check agreement
print({k: f"{v * 1000:.0f} ms" for k, v in times.items()})  # join times
cmp.head(6)  # top counties
identical results on all engines: True
{'spatialite': '16 ms', 'geopackage': '12 ms', 'duckdb': '12 ms', 'postgis': '12 ms'}
spatialite geopackage duckdb postgis
right_name
Nassau 18 18 18 18
Suffolk 16 16 16 16
Broome 8 8 8 8
Niagara 7 7 7 7
Dutchess 6 6 6 6
Orange 4 4 4 4

All engines return the same counts because they implement the same predicate on the same data. Their timings differ by setup costs more than by algorithms at this size; notebook 06_02_05 benchmarks larger problems. Choosing an engine is mostly about the setting: who needs the data, how large it is, and where it lives.

Code
duck.close()  # close the DuckDB database

Summary and exercises

Main points

  • A spatial database adds geometry types, spatial SQL functions, spatial indexes and an SRID catalog to an ordinary DBMS, which brings transactions, concurrency and integrity to spatial data.
  • The OGC Simple Features model defines seven geometry types; WKT is for people, WKB (and EWKB with an SRID) for programs.
  • The SRID decides the meaning of every area and distance. Web Mercator inflated Onondaga County’s area by 87%; equal-area and geodesic calculations agree within a fraction of a percent.
  • geography calculates on the ellipsoid in metres; geometry on a plane in SRID units.
  • Rasters are stored as tiles, each a row, found through the same spatial index.
  • Spatial indexes (R-tree, GiST, quadtree/SP-GiST, BRIN) turn millions of exact tests into a few thousand.
  • PostGIS, SpatiaLite, GeoPackage and DuckDB share one SQL vocabulary; geolattice.geolatticedb runs the same code on all of them.

Functions used: pdb.connect, con.load, con.query, con.execute, con.spatial_join (geolattice.geolatticedb); shapely.to_wkb, shapely.make_valid, shapely.STRtree; pyproj.CRS, pyproj.Geod.

Exercises

  1. Repeat the area comparison for a county in Alaska (e.g. North Slope Borough, FIPS 02185). How large is the Web Mercator error there, and why?
  2. Add the pair Onondaga to Honolulu (FIPS 15003) to the distance table. Which planar method fails worst?
  3. Change the R-tree node size m from 6 to 3 and to 12. How do the number of levels and the overlap between nodes change?
  4. Build the quadtree with capacity 10 and with capacity 50. Which areas of the country change most?
  5. Write the SQL that counts Superfund sites per state and run it on the DuckDB database atlas.duckdb.
Back to top