Spatial Databases

Rasters in PostGIS

The postgis_raster extension stores gridded data, such as elevation models, satellite indices and modelled pollution surfaces, in a raster column, cut into tiles that are found through a spatial index. Raster and vector data then meet in one SQL query: sample a raster at monitoring sites, clip it to a county, or summarize it within zones. This notebook builds a Sentinel-2 NDVI image of Syracuse, NY with geolattice.rsense (the PyRSense tools in GeoLattice), stores it in the database in two ways (in-db and out-db), and links it to Atlas health and environment layers.

Learning objectives

  1. Load rasters in-db and out-db, and write and check cloud-optimized GeoTIFFs (COGs).
  2. Inspect rasters with ST_MetaData, ST_BandMetaData and raster_columns.
  3. Sample, clip and summarize with ST_Value, ST_Clip, ST_SummaryStats and ST_Histogram.
  4. Compute zonal statistics in SQL and with geolatticedb, and check them against NumPy.
  5. Run map algebra in the database (ST_MapAlgebra) and turn raster classes into polygons (ST_DumpAsPolygons).

Data

Data Source Use
Sentinel-2 L2A, tile 18TVN, 2 Aug 2025 (red, NIR, scene classification), Syracuse AOI GeoLattice Data/00_shared/data_web_cloud_gis/s2_syracuse_2025 (Element 84 Earth Search) NDVI with geolattice.rsense
Onondaga County DEM (~100 m) GeoLattice Data/00_shared/raster_data/USA/Onondaga_DEM.tif Elevation
US county boundaries, EPA PM2.5 monitors, Superfund sites USA Health Data Atlas Zones and points

Contents

  1. Setup
  2. A PyRSense output: Sentinel-2 NDVI as a COG
  3. In-db vs. out-db rasters
  4. Raster metadata
  5. ST_Value, ST_Clip and ST_SummaryStats
  6. Zonal statistics and raster/vector integration
  7. Map algebra and raster to polygons
  8. Exporting rasters
  9. Summary and exercises

Setup

Installation. This notebook needs installation option 6 (every GeoLattice module): pip install "geolattice[all]". See “Installation options” in the GeoLattice README.

Code
import warnings  # warning control
warnings.filterwarnings("ignore", category=UserWarning)  # hide routine library warnings
warnings.filterwarnings("ignore", category=RuntimeWarning)  # all-NaN windows

import shutil  # find programs
import subprocess  # run raster2pgsql
import time  # timing
import numpy as np  # arrays
import pandas as pd  # tables
import geopandas as gpd  # vector data
import xarray as xr  # labelled rasters
import rasterio  # raster I/O
from rasterio.mask import mask as rio_mask  # zonal check in NumPy
import psycopg  # PostgreSQL driver
import matplotlib.pyplot as plt  # figures

import geolattice.rsense as rs  # GeoLattice remote sensing tools (PyRSense)
from geolattice import geolatticedb as pdb  # GeoLattice spatial database tools

rasterio.Env(CPL_LOG="/dev/null").__enter__()  # quiet GDAL messages
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_03_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

# Folder of DATA as the database server sees it (out-db rasters are read by the server).
# Local server: the same path. Docker (06_01_02 compose file): the Data folder is mounted at /data.
SERVER_DATA = Path(os.environ.get("GEOLATTICE_SERVER_DATA", str(DATA)))
Repository: /home/zia207/Github/GeoLattice
Code
pg = pdb.connect("postgis", dsn=PG_DSN)  # PostGIS through geolatticedb
q = pg.query  # SQL -> GeoDataFrame / DataFrame
pg.execute("CREATE EXTENSION IF NOT EXISTS postgis_raster")  # raster type and functions
# out-db rasters and COG access must be switched on (per database; new connections pick it up)
pg.execute("ALTER DATABASE " + psycopg.conninfo.conninfo_to_dict(PG_DSN)["dbname"] +
           " SET postgis.enable_outdb_rasters = true")
pg.execute("ALTER DATABASE " + psycopg.conninfo.conninfo_to_dict(PG_DSN)["dbname"] +
           " SET postgis.gdal_enabled_drivers = 'GTiff'")
pg.close(); pg = pdb.connect("postgis", dsn=PG_DSN); q = pg.query  # reconnect with the new settings
print(q("SHOW postgis.enable_outdb_rasters").iloc[0, 0], q("SHOW postgis.gdal_enabled_drivers").iloc[0, 0])

def tool(*args):  # run raster2pgsql and return its SQL
    if shutil.which(args[0]) is None:
        raise FileNotFoundError(f"{args[0]} not found: install PostGIS client tools or use docker exec")
    return subprocess.run([str(a) for a in args], capture_output=True, text=True, check=True).stdout

counties = atlas_counties()  # Atlas counties
sites = superfund_sites()  # Superfund sites
aq = pd.DataFrame(atlas_js("assets/air_quality_data.js")["sites"])  # EPA monitors (all pollutants)
aq = aq.dropna(subset=["lat", "lon"]).drop_duplicates("id")  # one row per monitoring site
monitors = gpd.GeoDataFrame(aq[["id", "n", "st", "p"]].set_axis(["site_id", "name", "state", "pollutant"], axis=1),
                            geometry=gpd.points_from_xy(aq.lon, aq.lat), crs=4326)  # points
pg.load(counties[counties.statefp == "36"], "ny_counties"); pg.load(sites, "superfund"); pg.load(monitors, "aq_sites")
true GTiff
'aq_sites'

A GeoLattice output: Sentinel-2 NDVI as a COG

The red (B04) and near-infrared (B08) bands are 10 m Sentinel-2 L2A surface reflectance stored as integers. The STAC item gives the conversion (raster:bands scale 0.0001 and offset -0.1 for processing baseline 05.11), but also records earthsearch:boa_offset_applied = true: Earth Search already removed the offset, so applying it again would push dark surfaces below zero. The code reads both fields. The scene classification layer (SCL, 20 m) flags clouds, cloud shadows and water. We compute the Normalized Difference Vegetation Index, NDVI = (NIR - red) / (NIR + red), with geolattice.rsense, mask clouds, shadows and water (so that greenness is compared over land only), and write the result as a cloud-optimized GeoTIFF: tiled, compressed and with overviews, so that programs can read just the part and resolution they need.

Code
S2 = GEOLATTICE_DATA / "00_shared" / "data_web_cloud_gis" / "s2_syracuse_2025" / "S2C_18TVN_20250802_0_L2A"  # one scene
item = json.load(open(S2 / "item.json"))  # STAC item of the scene
rb = item["assets"]["red"]["raster:bands"][0]  # scale and offset of the band
offset = 0.0 if item["properties"].get("earthsearch:boa_offset_applied") else rb.get("offset", 0.0)  # avoid double offset
print(f"scale {rb['scale']}, offset {rb['offset']} (already applied: {offset == 0.0})")
ds = xr.Dataset({b: rs.read(S2 / f"{b}.tif").squeeze("band", drop=True) for b in ["red", "nir"]})  # 10 m bands
ds = (ds.where(ds > 0) * rb["scale"] + offset).clip(min=0)  # DN -> surface reflectance (0 = nodata)
ds = ds.rio.write_crs(32618)  # UTM zone 18N
scl = rs.read(S2 / "scl.tif").squeeze("band", drop=True).rio.reproject_match(ds["red"], resampling=0)  # 20 m -> 10 m
bad = scl.isin([0, 1, 3, 6, 8, 9, 10])  # no data, saturated, cloud shadow, water, clouds, cirrus
ndvi = rs.optical.index(ds, "NDVI").where(~bad).astype("float32")  # NDVI with clouds masked
ndvi = ndvi.rio.write_crs(32618).rio.write_nodata(np.nan)
cog = OUT / "ndvi_syracuse_20250802_cog.tif"  # the COG file
rs.write(ndvi, cog, cog=True)  # cloud-optimized GeoTIFF (geolattice.rsense)
print(f"NDVI {ndvi.shape[0]} x {ndvi.shape[1]} cells at 10 m; masked (cloud, shadow, water) {float(bad.mean()):.1%}; "
      f"mean {float(ndvi.mean()):.2f}; file {cog.stat().st_size / 1e6:.1f} MB")
with rasterio.open(cog) as src:  # check the COG structure
    print("tiled:", src.profile.get("tiled"), "| block:", src.block_shapes[0], "| overviews:", src.overviews(1),
          "| compression:", src.compression)
scale 0.0001, offset -0.1 (already applied: True)
NDVI 1354 x 1485 cells at 10 m; masked (cloud, shadow, water) 4.0%; mean 0.57; file 8.9 MB
tiled: True | block: (512, 512) | overviews: [2, 4] | compression: Compression.deflate
Code
fig, ax = plt.subplots(figsize=(8, 7))  # one map
ndvi.plot(ax=ax, cmap="RdYlGn", vmin=-0.2, vmax=0.9, cbar_kwargs={"label": "NDVI"})  # the index
ax.set_title("Sentinel-2 NDVI, Syracuse NY, 2 Aug 2025 (geolattice.rsense)"); ax.set_axis_off(); plt.show()

Downtown Syracuse, the highway corridors and the commercial and industrial land along the shore of Onondaga Lake and in the south-east have low NDVI (orange), while parks, cemeteries and the wooded hills in the south are green. Onondaga Lake (north-west corner) is masked as water. The scene has almost no cloud, so 4% of the cells are masked, nearly all of them water.

In-db vs. out-db rasters

In-db Out-db (raster2pgsql -R)
Pixels stored inside the table (TOAST pages) in the original file; the table holds tile footprints, metadata and the file path
Load time and table size slower, larger fast, tiny
Backups (pg_dump) include the pixels include only the paths; the files must be backed up separately
Requirements none the server must be able to read the file path; postgis.enable_outdb_rasters = true
Best for data edited or analyzed often in SQL large archives (satellite scenes, COGs) read occasionally

Out-db works well with COGs, because each tile reads just its block of the file, and GDAL can read COGs from object storage (/vsis3/, /vsicurl/) when the server is allowed to. We load the NDVI COG both ways:

Code
rows = []  # one row per storage mode
for mode in ["in-db", "out-db"]:
    table = "ndvi_indb" if mode == "in-db" else "ndvi_outdb"
    pg.execute(f"DROP TABLE IF EXISTS {table}")
    path = cog if mode == "in-db" else SERVER_DATA / cog.relative_to(DATA)  # out-db: path as the server sees it
    args = ["raster2pgsql", "-s", "32618", "-t", "256x256", "-I", "-C", "-F"] + (["-R"] if mode == "out-db" else [])
    t0 = time.perf_counter()
    pg.execute(tool(*args, path, f"public.{table}"))  # generate and run the SQL
    t_load = time.perf_counter() - t0
    size = q(f"SELECT pg_total_relation_size('{table}') / 1e6 AS mb").mb.iloc[0]  # table + TOAST + index
    t0 = time.perf_counter()
    stats = q(f"SELECT (ST_SummaryStatsAgg(rast, 1, true)).* FROM {table}")  # read every pixel once
    rows.append({"storage": mode, "tiles": q(f"SELECT count(*) FROM {table}").iloc[0, 0], "load s": t_load,
                 "table MB": float(size), "full scan s": time.perf_counter() - t0,
                 "mean NDVI": float(stats["mean"].iloc[0])})
pd.DataFrame(rows).set_index("storage").round(3)  # compare
tiles load s table MB full scan s mean NDVI
storage
in-db 36 0.416 8.290 0.068 0.574
out-db 36 0.138 0.074 0.158 0.574

The out-db table is a small fraction of the in-db size, because it holds only tile footprints and the path, and both return the same statistics. A full scan of the out-db raster is slower because each tile is read from the file through GDAL. For repeated pixel-level analysis keep rasters in-db; for large archives keep the COGs as files (or in object storage) and register them out-db. In a Docker setup the path written by -R must be the path inside the container, which is why the notebook uses SERVER_DATA (/data with the compose file from 06_01_02).

The Onondaga County DEM goes in-db with geolatticedb, which calls raster2pgsql with tiling, constraints and an index:

Code
pg.raster.load(GEOLATTICE_DATA / "00_shared" / "raster_data" / "USA" / "Onondaga_DEM.tif", "ono_dem", srid=4326, tile_size=100)
pg.raster.info("ono_dem")  # metadata from raster_columns
r_raster_column srid scale_x scale_y blocksize_x blocksize_y num_bands pixel_types nodata_values out_db
0 rast 4326 0.001133 -0.001133 100 100 1 [32BF] [-3.4028230607371e+38] [False]

Raster metadata

ST_MetaData returns the georeference of a tile (upper-left corner, size, scale, skew, SRID, number of bands) and ST_BandMetaData the pixel type, nodata value and, for out-db bands, the file path. ST_Envelope and ST_ConvexHull give the footprint as a geometry.

Code
q("""
SELECT 'in-db' AS storage, (md).upperleftx, (md).upperlefty, (md).width, (md).height, (md).scalex, (md).srid,
       (bm).pixeltype, (bm).nodatavalue, (bm).isoutdb, right((bm).path, 45) AS path
FROM (SELECT ST_MetaData(rast) AS md, ST_BandMetaData(rast, 1) AS bm FROM ndvi_indb LIMIT 1) t
UNION ALL
SELECT 'out-db', (md).upperleftx, (md).upperlefty, (md).width, (md).height, (md).scalex, (md).srid,
       (bm).pixeltype, (bm).nodatavalue, (bm).isoutdb, right((bm).path, 45)
FROM (SELECT ST_MetaData(rast) AS md, ST_BandMetaData(rast, 1) AS bm FROM ndvi_outdb LIMIT 1) t
""")
storage upperleftx upperlefty width height scalex srid pixeltype nodatavalue isoutdb path
0 in-db 400520.0 4772650.0 256 256 10.0 32618 32BF NaN False NaN
1 out-db 400520.0 4772650.0 256 256 10.0 32618 32BF NaN True tputs/06_03_01/ndvi_syracuse_20250802_cog.tif
Code
tiles = q("SELECT rid, ST_Envelope(rast) AS geom, (ST_SummaryStats(rast)).mean AS mean_ndvi FROM ndvi_indb")
ax = tiles.plot("mean_ndvi", cmap="RdYlGn", edgecolor="k", lw=0.4, figsize=(7, 6), legend=True, vmin=0, vmax=0.8,
                legend_kwds={"label": "tile mean NDVI"})  # tile footprints coloured by their mean
ax.set_title(f"{len(tiles)} tiles of 256 x 256 cells (one row each)"); ax.set_axis_off(); plt.show()

ST_Value, ST_Clip and ST_SummaryStats

Function Returns
ST_Value(rast, band, point) the cell value under a point (resample => 'bilinear' for interpolation)
ST_Clip(rast, band, geom, crop) the part of a raster inside a geometry, as a raster
ST_SummaryStats(rast) / ST_SummaryStatsAgg count, sum, mean, stddev, min, max of a tile / of many tiles
ST_Histogram, ST_Quantile, ST_ValueCount distributions and class counts

NDVI and elevation at the EPA air quality monitoring sites and Superfund sites that fall inside the scene (one of each: the East Syracuse PM2.5 site and the Onondaga Lake site). The points are in EPSG:4326 and the NDVI in UTM 18N, so the points are transformed to the raster SRID; the spatial join ST_Intersects(rast, geom) finds the tile under each point through the GiST index:

Code
pts = q("""
WITH p AS (
    SELECT 'EPA monitor (' || pollutant || ')' AS kind, name, geom FROM aq_sites
    UNION ALL SELECT 'Superfund site', name, geom FROM superfund
)
SELECT p.kind, p.name,
       round(ST_Value(n.rast, 1, ST_Transform(p.geom, 32618))::numeric, 3)  AS ndvi,
       round(ST_Value(d.rast, 1, p.geom)::numeric)                         AS elevation_m, p.geom
FROM p
JOIN ndvi_indb n ON ST_Intersects(n.rast, ST_Transform(p.geom, 32618))   -- tile under the point
LEFT JOIN ono_dem d ON ST_Intersects(d.rast, p.geom)
""")
pts.drop(columns="geom")  # sites inside the NDVI scene
kind name ndvi elevation_m
0 Superfund site Onondaga Lake 0.424 114
1 EPA monitor (PM25) EAST SYRACUSE 0.646 128

Point values are noisy: a monitor on a rooftop or beside a parking lot reads the NDVI of one 10 m cell. Exposure studies therefore summarize the raster in a buffer around each site. ST_Clip cuts the raster to a 500 m circle and ST_SummaryStats summarizes it:

Code
buf = q("""
WITH p AS (SELECT name, ST_Buffer(ST_Transform(geom, 32618), 500) AS zone FROM aq_sites
           WHERE ST_Intersects(ST_Transform(geom, 32618), (SELECT ST_Union(ST_Envelope(rast)) FROM ndvi_indb)))
SELECT p.name, (ST_SummaryStatsAgg(ST_Clip(n.rast, 1, p.zone, true), 1, true)).*,
       (SELECT count(*) FROM ndvi_indb) AS tiles_total
FROM p JOIN ndvi_indb n ON ST_Intersects(n.rast, p.zone) GROUP BY p.name
""")
buf[["name", "count", "mean", "stddev", "min", "max"]].round(3)  # NDVI within 500 m of each monitoring site
name count mean stddev min max
0 EAST SYRACUSE 7805 0.49 0.229 0.001 0.842
Code
hist = q("""SELECT (h).min, (h).max, (h).count FROM (
    SELECT ST_Histogram(ST_Union(rast), 1, true, 20, false) AS h FROM ndvi_indb) t""")  # 20 bins, whole scene
fig, ax = plt.subplots(figsize=(8, 3.2))  # one histogram
ax.bar((hist["min"] + hist["max"]) / 2, hist["count"], width=hist["max"] - hist["min"], color="#41ab5d", edgecolor="w")
ax.set(xlabel="NDVI", ylabel="cells", title="ST_Histogram of the Syracuse NDVI"); plt.show()

Zonal statistics and raster/vector integration

Zonal statistics summarize a raster within each polygon of a vector layer. In SQL the pattern is: join tiles to zones with ST_Intersects, clip each tile to its zone with ST_Clip, and aggregate with ST_SummaryStatsAgg per zone. geolatticedb.raster.zonal_stats writes that query (and reprojects the zones to the raster SRID). We use 250 m hexagons over the Syracuse scene as zones, then check the result against a NumPy calculation with rasterio.mask.

Code
pg.execute("""DROP TABLE IF EXISTS syr_hex;
CREATE TABLE syr_hex AS
SELECT row_number() OVER () AS hex_id, ST_Transform(h.geom, 4326) AS geom
FROM ST_HexagonGrid(250, (SELECT ST_Union(ST_Envelope(rast)) FROM ndvi_indb)) h
WHERE ST_Within(h.geom, (SELECT ST_Union(ST_Envelope(rast)) FROM ndvi_indb));
CREATE INDEX ON syr_hex USING GIST (geom)""")  # hexagons inside the scene
t0 = time.perf_counter()
zs = pg.raster.zonal_stats("ndvi_indb", "syr_hex", stats=["count", "mean", "min", "max"])  # geolatticedb
print(f"{len(zs):,} hexagons, zonal statistics in {time.perf_counter() - t0:.1f} s")

check = zs.sample(25, random_state=1)  # verify 25 hexagons with rasterio + NumPy
with rasterio.open(cog) as src:
    np_mean = [float(np.nanmean(rio_mask(src, [g], crop=True, nodata=np.nan, all_touched=False)[0]))
               for g in check.to_crs(32618).geometry]
print("max |PostGIS - NumPy| mean NDVI:", round(float(np.nanmax(np.abs(np.array(np_mean) - check["mean"]))), 6))
1,140 hexagons, zonal statistics in 0.4 s
max |PostGIS - NumPy| mean NDVI: 0.0

Both methods count the cells whose centre falls inside each hexagon, so they agree to floating-point precision. A second integration step joins the raster summary to vector layers. Here we flag hexagons that contain an EPA monitoring site or lie within 2 km of a Superfund site, and compare their greenness:

Code
pg.load(zs, "syr_hex_ndvi")  # the zonal result as a table
cmp = q("""
SELECT CASE WHEN EXISTS (SELECT 1 FROM superfund s WHERE ST_DWithin(h.geom::geography, s.geom::geography, 2000))
            THEN 'within 2 km of a Superfund site' ELSE 'farther' END AS zone,
       count(*) AS hexagons, round(avg(mean)::numeric, 3) AS mean_ndvi,
       round(avg((mean < 0.3)::int)::numeric, 3) AS share_low_green
FROM syr_hex_ndvi h WHERE count > 400 GROUP BY 1
""")
fig, ax = plt.subplots(figsize=(8, 7))  # map of the hexagons
zs.plot("mean", ax=ax, cmap="RdYlGn", vmin=0, vmax=0.8, legend=True, legend_kwds={"label": "mean NDVI per hexagon"})
q("SELECT geom FROM superfund").clip(zs.total_bounds).plot(ax=ax, color="k", marker="X", markersize=60, label="Superfund")
q("SELECT geom FROM aq_sites").clip(zs.total_bounds).plot(ax=ax, color="blue", markersize=30, label="EPA monitor")
ax.legend(loc="lower left"); ax.set_title("Mean NDVI in 250 m hexagons, Syracuse"); ax.set_axis_off(); plt.show()
cmp  # greenness near and far from Superfund sites

zone hexagons mean_ndvi share_low_green
0 farther 1054 0.572 0.055
1 within 2 km of a Superfund site 46 0.484 0.196

The only Superfund site in this scene is Onondaga Lake, recorded at a point on its south-western shore. With the lake masked, the land hexagons within 2 km of that point have a lower mean NDVI (0.48 against 0.57 elsewhere) and are about four times as often below NDVI 0.3 (20% against 6%). That shore is mostly industrial and highway land. This describes land cover, not exposure or health; it shows how a raster summary becomes an ordinary attribute that joins to sites, monitors, tracts or health outcomes.

Map algebra and raster to polygons

ST_MapAlgebra computes new pixel values from one or more bands with an expression, inside the database. We load the red and NIR bands as a two-band raster, compute NDVI in SQL and compare it with the geolattice.rsense result. ST_Reclass and ST_DumpAsPolygons then turn a class of the raster into vector polygons, here green space with NDVI of at least 0.6.

Code
two_band = OUT / "red_nir_reflectance.tif"  # red and NIR reflectance as one 2-band GeoTIFF
rs.write(ds[["red", "nir"]].to_array("band").astype("float32").rio.write_nodata(np.nan), two_band, cog=False)
pg.execute("DROP TABLE IF EXISTS s2_rednir")
pg.execute(tool("raster2pgsql", "-s", "32618", "-t", "256x256", "-I", "-C", two_band, "public.s2_rednir"))
t0 = time.perf_counter()
pg.execute("""DROP TABLE IF EXISTS ndvi_sql;
CREATE TABLE ndvi_sql AS
SELECT rid, ST_MapAlgebra(rast, 1, rast, 2,                                   -- band 1 = red, band 2 = NIR
         'CASE WHEN [rast1] + [rast2] > 0 THEN ([rast2] - [rast1]) / ([rast2] + [rast1]) END', '32BF') AS rast
FROM s2_rednir""")
print(f"ST_MapAlgebra NDVI in {time.perf_counter() - t0:.1f} s")
sql_vs_py = q("""SELECT (ST_SummaryStatsAgg(rast, 1, true)).mean AS sql_mean FROM ndvi_sql""").iloc[0, 0]
print(f"mean NDVI, SQL map algebra (no cloud mask): {sql_vs_py:.4f} | geolattice.rsense without mask: "
      f"{float(rs.optical.index(ds, 'NDVI').mean()):.4f}")
ST_MapAlgebra NDVI in 3.0 s
mean NDVI, SQL map algebra (no cloud mask): 0.5545 | geolattice.rsense without mask: 0.5545
Code
green = q("""
SELECT (dp).val AS class, ST_Transform((dp).geom, 4326) AS geom, ST_Area((dp).geom) AS area_m2
FROM (SELECT ST_DumpAsPolygons(ST_Reclass(rast, 1, '[-1-0.6):0, [0.6-1]:1', '8BUI', 0)) AS dp FROM ndvi_indb) t
WHERE (dp).val = 1                                                            -- green space only
""")
green_union = q("""SELECT ST_Transform(ST_Union((dp).geom), 4326) AS geom FROM (
    SELECT ST_DumpAsPolygons(ST_Reclass(rast, 1, '[-1-0.6):0, [0.6-1]:1', '8BUI', 0)) AS dp FROM ndvi_indb) t
WHERE (dp).val = 1""")  # merged across tile edges
print(f"{len(green):,} polygon pieces from {len(tiles)} tiles; green space (NDVI >= 0.6): "
      f"{green.area_m2.sum() / 1e6:.1f} km² of {ndvi.count().item() * 100 / 1e6:.1f} km² observed")
ax = green_union.plot(color="#238b45", figsize=(8, 7))  # green space polygons
ax.set_title("Green space (NDVI >= 0.6) as polygons from ST_DumpAsPolygons"); ax.set_axis_off(); plt.show()
11,668 polygon pieces from 36 tiles; green space (NDVI >= 0.6): 103.1 km² of 193.0 km² observed

The SQL map algebra reproduces the geolattice.rsense NDVI (both without the cloud mask). The reclassified raster became vector polygons; because each tile is vectorized separately, the pieces are merged with ST_Union to remove tile seams. The polygons can now be buffered, overlaid with parcels or tracts, or used in distance calculations like any vector layer.

Exporting rasters

ST_AsGDALRaster(rast, format) (or ST_AsTIFF, ST_AsPNG) returns a file’s bytes. Union the tiles first to export one image. The result opens in rasterio or xarray directly from memory:

Code
clip_tif = q("""
SELECT ST_AsGDALRaster(ST_Clip(ST_Union(d.rast), 1, c.geom, true), 'GTiff') AS tif
FROM ono_dem d, ny_counties c WHERE c.fips = '36067' AND ST_Intersects(d.rast, c.geom) GROUP BY c.geom
""").tif.iloc[0]  # Onondaga County DEM, clipped to the county, as GeoTIFF bytes
out_tif = OUT / "onondaga_dem_clip.tif"; out_tif.write_bytes(bytes.fromhex(clip_tif) if isinstance(clip_tif, str) else bytes(clip_tif))
dem = rs.read(out_tif).squeeze("band", drop=True)  # back into xarray
fig, ax = plt.subplots(figsize=(7, 6))
dem.plot(ax=ax, cmap="terrain", cbar_kwargs={"label": "elevation (m)"})  # the clipped DEM
counties[counties.fips == "36067"].boundary.plot(ax=ax, color="k", lw=0.8)  # county outline
ax.set_title(f"Onondaga County DEM exported from PostGIS (mean {float(dem.mean()):.0f} m)"); ax.set_axis_off(); plt.show()
pg.close()  # close the connection

Summary and exercises

Main points

  • postgis_raster stores rasters as tiles in a raster column with a GiST index on the tile footprints; raster2pgsql -t -I -C loads them.
  • In-db rasters are self-contained and fast to scan; out-db rasters (-R) keep pixels in the file, typically a COG, and need postgis.enable_outdb_rasters and a path the server can read.
  • ST_Value, ST_Clip and ST_SummaryStats(Agg) sample, cut and summarize rasters inside SQL, so raster values join to points and polygons like attributes.
  • Zonal statistics (geolatticedb.raster.zonal_stats, or ST_Clip + ST_SummaryStatsAgg) matched a NumPy calculation exactly.
  • ST_MapAlgebra computes new rasters in the database; ST_Reclass + ST_DumpAsPolygons turn raster classes into vector polygons.
  • ST_AsGDALRaster exports results to GeoTIFF for geolattice.rsense, rasterio or xarray.

Functions used: raster2pgsql, ST_MetaData, ST_BandMetaData, ST_Envelope, ST_Value, ST_Clip, ST_SummaryStats, ST_SummaryStatsAgg, ST_Histogram, ST_MapAlgebra, ST_Reclass, ST_DumpAsPolygons, ST_Union, ST_AsGDALRaster, ST_HexagonGrid; rs.read, rs.write, rs.optical.index (geolattice.rsense); pdb.connect, con.raster.load, con.raster.info, con.raster.zonal_stats, con.load (geolattice.geolatticedb).

Exercises

  1. Load the 23 July and 19 September 2025 scenes as well and compute NDVI change per hexagon in SQL.
  2. Compare ST_Value with resample => 'bilinear' and nearest-neighbour values at the monitoring sites.
  3. Compute the share of each hexagon covered by green space using the green_union polygons and ST_Intersection. Does it agree with the share of cells with NDVI >= 0.6?
  4. Register a remote COG out-db with raster2pgsql -R /vsicurl/https://... and query it. Which server settings are needed?
  5. Summarize the Onondaga DEM within 2 km hexagons and find the steepest hexagon with ST_Slope.
Back to top