Raster Reader
Since: raster_gbx v0.4.0
Read rasters into the shared (source, tile) schema with raster_gbx. It is a pure-Python,
rasterio-backed reader. It needs no JAR and runs on Serverless and standard clusters. It reads
any raster that GDAL can open, such as GeoTIFF, COG and GRIB2. For NetCDF, use the
NetCDF Reader.
Call gbx_drivers() in SQL, or drivers() in Python, to list the raster drivers of the current environment. Each row says whether the driver reads, writes and is allowed by GeoBrix. It also says if the driver works as shipped, and what it still needs. raster_gbx detects the format from the file, so it takes no driver option. The tested column marks the drivers that GeoBrix's driver tests cover, and guidance points to a built-in reader where one exists. The result reflects the environment as it runs now, so adding or removing packages changes it. See the raster drivers in the env wheel for the shipped list.
SELECT driver, description, requires FROM gbx_drivers('raster') WHERE write AND allowed
GDAL drivers have had parser bugs, so load rasters only from sources you trust. GeoBrix refuses the drivers that run stored pipelines or fetch over the network. See Security § 7 for the list and the switch.
Options
The reader defaults to no splitting (splitStrategy=none):
one whole-image tile per file. Splitting is opt-in; COG creation is a
separate concern handled by the cog_gbx writer. See
COG Reader and COG Writer for the
prepare-then-read pipeline.
| Option | Default | Description |
|---|---|---|
virtualTiles | "true" | Default. Emit bytes-free virtual tiles — each row carries the source path + pixel window instead of raster bytes; pixels are read lazily when an operation needs them (the default, which keeps a large ingest within memory). Set "false" to materialize raster bytes into each row. See Virtual Tiles. |
splitStrategy | "none" | When to split large rasters: none (default — one whole-image tile per file), auto (resolve to serverless or classic by environment), serverless (opt-in, 64 MiB decoded budget per tile), classic (opt-in, 1 536 MiB decoded budget per tile). |
sizeInMB | "-1" | Power-user override: set a positive value to pin the per-tile decoded-memory budget in MiB. A positive value implies opt-in split regardless of splitStrategy. -1 = defer to splitStrategy. |
filterRegex | ".*" | When loading a directory, keep files whose full path matches this regex. |
clipPolygons | none | Area(s) of interest to clip to. One WKT/EWKT string for a single polygon, or a JSON-array string for a list, e.g. '["POLYGON((...))","POLYGON((...))"]' (raw WKB/EWKB bytes are accepted only from programmatic callers). One tile is emitted per polygon whose envelope intersects the raster; a polygon that misses the raster emits no tile. Materialized tiles are pre-clipped (pixels outside the polygon are NoData); virtual tiles carry the clip as a deferred instruction. Mutually exclusive with windows and tileSize. Pairs naturally with the COG Reader. |
windows | none | Pixel window(s) to read. A JSON 4-int array "[col,row,w,h]" for one, or a JSON array of them "[[..],[..]]" for a list. One tile per window; partial windows clip to the raster extent, fully-outside windows are skipped. Mutually exclusive with clipPolygons and tileSize. |
clipCrs | none | CRS for clipPolygons that lack an embedded SRID (e.g. "EPSG:27700"). Precedence: an EWKB/EWKT polygon's embedded SRID → clipCrs → the raster's CRS. |
tileSize | none | Cut the whole raster into a regular fixed-size pixel grid: "w,h" (e.g. "512,512") or a single "512" for square tiles. One tile per grid cell; edge cells are clamped to the extent. Mutually exclusive with clipPolygons and windows. Materialized tiles are guarded to the ~2 GB Spark-cell limit (a too-large tileSize raises a clear error); virtual tiles (virtualTiles=true) carry no bytes and are unguarded. |
overlapPercent | 0 | Overlap between adjacent tileSize cells, as a percentage of tile size (overlap_px = ceil(tile_dim · pct/100), step = tile_dim − overlap_px). Applies to tileSize only (an error otherwise). Default 0 = non-overlapping grid. |
tilesTable | none | Delta table to use as a tile index. spark.read cannot read the table (the read is planned in a worker that has no Spark session), so passing it there raises an error: read the index with read_tiles_table instead. |
versionAsOf | none | For a tile index: read this Delta version of the table (a non-negative integer, e.g. "3"), so a pipeline re-runs against the exact tile index it used. Mutually exclusive with timestampAsOf; an error without a tile index. See pin a tile index version. |
timestampAsOf | none | For a tile index: read the table as it was at this time (e.g. "2026-10-01 00:00:00"): the version current then. The time must fall between the table's first and latest commits, or Delta raises an error; use versionAsOf for an exact version. Mutually exclusive with versionAsOf; an error without a tile index. |
skipOrdering | "false" | Pass "true" to suppress the auto-sort-by-source-path that manifest and tile-index reads apply by default. See tile index auto-order below. |
A hard tiling grid can slice straight through a spatial feature (a field, a building, an airport)
that straddles a seam. No single tile then sees it whole. Set overlapPercent so adjacent tileSize
cells overlap — a feature near a boundary then appears complete in at least one tile, which per-tile
analysis needs. Overlap only makes sense for a reader-chosen grid (tileSize); windows and
clipPolygons are extents you specify explicitly, so they take no overlap.
The raster readers now emit virtual tiles by default (virtualTiles=true) — bytes-free
(path, window) references that read pixels lazily. Previously the reader materialized raster
bytes into every row. To restore materialized reads, pass .option("virtualTiles", "false").
A virtual tile that reaches the JVM level must be materialized first — see
Virtual Tiles.
With virtualTiles=false and no tileSize, windows, clipPolygons or sizeInMB, the reader plans
without opening any file. Each task reads up to 8 whole files and returns their tiles in batches of at
most 64 MiB. A file over the read cap fails the read. The cap is 64 MiB on Serverless and 256 MiB on classic
compute. To read such a file, set sizeInMB or retile it first.
A tile holds the bytes of one file, so a materialized read bakes in what the file's sidecars hold.
The tile holds the CRS and NoData from a GeoTIFF's .aux.xml.
It also holds those from the .hdr, .prj or .sgrd files of an ESRI, ENVI or SAGA raster.
The same holds for gbx_rst_fromfile and rst_fromfile(materialize=True).
auto to nonePrior to this release the reader defaulted to splitStrategy=auto, which
auto-split large rasters on a decoded-memory budget. The default is now
none — one tile per file. To opt back into splitting, pass
.option("splitStrategy", "serverless") or .option("splitStrategy", "classic").
When splitting is enabled, split tiles are emitted as plain GeoTIFF.
COG output is a cog_gbx writer concern, not a reader concern: the
tileFormat, cogBlockSize, and cogOverviewResampling reader options
are removed. For COG-encoded output, use the
COG Writer to prepare master COGs, then read them with
the COG Reader.
Striped GeoTIFFs (no internal tiling) split into full-width row-bands. Internally-tiled sources split on a block-snapped grid.
Directory reads
Reading a directory plans every file (fast, stat-free listing — ~1.5 s at 10k files). For pre-computed windows or very large tile counts, see Advanced: pre-computed tile inputs below.
Stock Spark file readers (spark.read.format("binaryFile"), text, parquet, …)
silently skip any file whose name starts with _ or . — Spark's hidden-file filter,
applied during directory listing. Some GeoBrix raster tiles are written with a leading
_ in their (hashed) name, so a stock reader can miss a large fraction of a directory.
Note that .option("pathGlobFilter", "*.tif") does not override this filter. The
filter runs before the glob, so _-prefixed files stay excluded. An explicit _* glob,
explicit _-file paths, and recursiveFileLookup do not help either.
To read every tile, enumerate the paths on the driver (which does not apply the filter) and build the DataFrame explicitly. This is ideal when you only need the file list, e.g. to feed a VRT builder:
from pathlib import Path
paths = [str(p) for p in Path(output_dir).rglob("*.tif")]
files_df = spark.createDataFrame([(p,) for p in paths], ["path"])
GeoBrix's own raster readers (raster_gbx / gtiff_gbx / cog_gbx) list files directly
and are not affected — this applies only to stock Spark file readers.
Opt-in split (serverless budget):
# Two-axis control: split strategy and output format.
df = (
spark.read.format("raster_gbx")
.option("splitStrategy", "serverless") # or: classic | none | auto
.option("tileFormat", "cog") # or: gtiff | auto
.option("cogBlockSize", "512") # tile size for COG internal grid (px)
.option("cogOverviewResampling", "AVERAGE") # overview resampling algorithm
.load("/Volumes/main/geobrix_samples/geobrix-examples/nyc/sentinel2")
)
READ_WITH_OPTIONS exampleThe sizeInMB option remains available as a power-user override:
# Options: sizeInMB (tile split threshold) + filterRegex (directory listing)
df = (spark.read.format("raster_gbx")
.option("sizeInMB", "16")
.option("filterRegex", r".*\.tif$")
.load("{SAMPLE_RASTER_PATH}"))
gtiff_gbx is raster_gbx with the GeoTIFF driver preset.
COG lane for large rasters
For large rasters, the recommended path is to prepare master COGs with the
cog_gbx writer and then clip windows with the cog_gbx reader. This
keeps the reader simple (no split, no re-encode) and lets GDAL's range-read
mechanism fetch only the bytes that intersect the AOI.
Who benefits from pre-built COG overviews:
rst_tilexyzandrst_xyzpyramid— the XYZ tile-serving pipeline uses rio-tiler, which automatically selects the appropriate COG overview level for the requested zoom.rst_resample*— the resample family triggers overview-level selection automatically when a COG source has pre-built overviews.
COG preparation + windowed read:
See COG Writer for the preparation step and COG Reader for the windowed read.
Force-writing COG output from a tile DataFrame. The gtiff_gbx writer
still accepts a cog=true option to re-encode any (source, tile) DataFrame
as COG when you already have tiles in memory:
# Force-convert to COG on write (any DataFrame with a tile column):
import tempfile
with tempfile.TemporaryDirectory() as out:
df.write.format("gtiff_gbx") \
.mode("overwrite") \
.option("cog", "true") \
.option("cogBlockSize", "512") \
.option("cogOverviewResampling", "AVERAGE") \
.option("cogCompression", "DEFLATE") \
.save(out)
cog_df = spark.read.format("raster_gbx").load(out)
print(cog_df.count(), "COG tiles written and read back")
Register
# Register the lightweight raster DataSources (once per session)
from databricks.labs.gbx import register
register(spark)
The *_gbx readers and writers are Python Data Source V2 sources. Python has no classpath
discovery, so register them before you use format("raster_gbx") or format("gtiff_gbx"), for
reads and for writes. Importing databricks.labs.gbx.ds registers nothing. databricks.labs.gbx.register(spark) registers them.
Read (catch-all)
# Catch-all lightweight reader (any rasterio-readable raster)
df = spark.read.format("raster_gbx").load("{SAMPLE_RASTER_PATH}")
df.show()
+--------------------------------------------------+-----+
|source |tile |
+--------------------------------------------------+-----+
|/Volumes/.../nyc_sentinel2_red.tif |{...}|
+--------------------------------------------------+-----+
gtiff_gbx is raster_gbx with the GeoTIFF driver preset. See the GeoTIFF Reader for the named-reader page. See Options for the reader options.
The reader has Python and SQL bindings.
GeoBrix's GDAL build
The env wheel carries GDAL 3.13.3, PROJ 9.9.0 and GEOS 3.15.0. Python and the JVM use this one stack. It includes:
- JPEG XL. The
JPEGXLdriver and the GeoTIFFJXLcodec read JPEG XL data. GeoBrix's writers do not offerJXLcompression. - Map algebra. GDAL's
raster calcalgorithm, run throughosgeo.gdal.Run, accepts themuparserdialect for band expressions. - Regular expressions.
REGEXPworks in GDAL's SQLite dialect. See Regular-expression filters. - HTTP. libcurl 8.23 with HTTP/2.
- PROJ grids. Three grids ship with the wheel. See Coordinate reference systems.
Two GDAL drivers are not what their names suggest:
- GDAL's PMTiles driver reads and writes vector tiles only. GeoBrix's own PMTiles reader and writers also handle raster tiles. See PMTiles.
- LIBERTIFF is an opt-in, read-only GeoTIFF reader in GDAL. GeoBrix does not enable it.
Remote reads over HTTPS
GDAL reads /vsicurl/ sources over HTTP/2 when the server offers it. Leave GDAL_HTTP_VERSION unset.
On Google Cloud Storage, GeoBrix tests found unset, 1.1 and 2TLS within the run-to-run noise of one another.
In the same tests, Amazon S3 negotiated only HTTP/1.1, so the setting changed nothing there.
Output Schema
root
|-- tile: struct (GeoBrix raster tile structure)
|-- cellid: bigint (grid cell ID, nullable)
|-- raster: binary (raster file content)
|-- metadata: map<string,string> (driver, extension, etc.)
The tile column contains the complete raster data structure. See Tile Structure for detailed field descriptions.
Common Raster Formats Explained
GeoTIFF - The Universal Choice
Best for: General-purpose geospatial rasters, aerial imagery, DEMs
GeoTIFF combines TIFF image format with embedded geospatial metadata (coordinate system, geotransform). It's the de facto standard because it's simple, widely supported, and works everywhere. Cloud-Optimized GeoTIFF (COG) adds internal tiling and overviews for efficient cloud storage access.
# Standard GeoTIFF
df = spark.read.format("gtiff_gbx").load("/path/to/elevation.tif")
# Works with COG too
df = spark.read.format("gtiff_gbx").load("s3://bucket/cog-file.tif")
NetCDF - Multi-Dimensional Science Data
Best for: Climate models, oceanographic data, time-series rasters
NetCDF excels at storing multi-dimensional arrays with labeled dimensions (time, latitude, longitude, elevation). Common in scientific computing for weather forecasts, climate projections, and oceanographic measurements.
Read NetCDF with netcdf_gbx. It returns one row per grid variable.
df = spark.read.format("netcdf_gbx").load("/path/to/climate_model.nc")
HDF5 - Massive Hierarchical Data
Best for: Large scientific datasets, satellite products (MODIS, Sentinel)
HDF5 (Hierarchical Data Format) handles extremely large datasets with complex internal structures. NASA and ESA use it for satellite products. Like NetCDF, it often contains multiple subdatasets.
GRIB/GRIB2 - Weather Models
Best for: Numerical weather prediction, meteorological data
GRIB (GRIdded Binary) is the standard format for weather model outputs from agencies like NOAA, ECMWF. Highly compressed and optimized for meteorological variables. Example uses NOAA HRRR weather data from sample-data (nyc/hrrr-weather).
The hrrr-weather dataset is included in the complete sample-data bundle, not the essential bundle. See Sample data for download options.
sample_path = "/Volumes/main/default/geobrix_samples/geobrix-examples"
hrrr = spark.read.format("raster_gbx").load(f"{sample_path}/nyc/hrrr-weather/hrrr_*.grib2")
Which format to use
See Choosing a Format for the selection guide: how raster, array, vector and tile formats compare, and the reader, writer and functions for each. In short, start with GeoTIFF (COG for cloud storage). Use NetCDF, HDF5 or GRIB2 when a data provider publishes them. Use Zarr for large cubes that you read in slices and write back to.
Common functions: used vs excluded
See GBX Common Functions for the full catalog of shared file-access primitives. The table below shows which are active in this reader and which are not, and why.
| Common capability | Used here? | How / why |
|---|---|---|
list_local_files (session-free enumeration) | Used | All directory reads — recursive, include_hidden, extensions, path_glob_filter options are routed through this shared predicate. |
enumerate_files (FILE-tier enumeration) | Not in the DataSource | The DataSource is session-less on Connect and does not call enumerate_files; FILE-tier enumeration is only available through gbx_file_read at the function layer. |
gbx_file_read / gbx_file_write (FILE tier) | Not in the DataSource | The DataSource is FUSE-only (session-less on Connect); FILE reads go through gbx_file_read → rst_fromfile at the function layer. |
Advanced: pre-computed tile inputs (manifest / tile index)
The default directory read is fast — a stat-free listing plans ~10k files in ~1.5 s — so most reads need nothing special. A manifest and a tile index (tilesTable) are an optional optimization for two specific cases:
- Pre-computed windows you already maintain — a manifest or tile index lets the reader use your saved file listing directly, skipping the directory walk entirely.
- Very large tile counts where even a fast listing accumulates across many repeated job runs.
Both reduce plan time from the directory walk (~1.5 s at 10k files) to a single file or table read. See Benchmarking → Reader plan-time listing for the measured numbers.
manifestoption — supply a JSON or Parquet file listingpath+windowfor each tile; the reader skips the directory walk and header opens entirely.spark.read.format("raster_gbx") \.option("manifest", "/Volumes/catalog/schema/vol/tiles.json") \.option("virtualTiles", "true") \.load("/Volumes/catalog/schema/vol/rasters")- Tile index (
tilesTable) — a Delta table that serves as a tile index: one row per tile with apathcolumn (+ optionalwindow/ dimension columns). It is a catalog of file references, not the tile pixels. The reader still opens each referenced file and extracts its window. It only skips discovering the files by walking the directory. Read it withread_tiles_table, notspark.read:from databricks.labs.gbx.ds.raster import read_tiles_tabledf = read_tiles_table(spark, "geospatial.myschema.tile_index", {"virtualTiles": "true"}) - Fewer, larger COGs — consolidate small files into Cloud-Optimized GeoTIFFs using the COG Writer. The reader then opens a small number of large files whose headers are comparatively cheap.
Remote paths in a manifest or a tile index are refused. A row's path, and each source of a .vrt you load, is data that anyone who can write the file or the table controls. The reader therefore opens it only when it names one of three things. These are a local or Volume path (/Volumes/…, /Workspace/…), a cloud object store (s3://, s3a://, abfss://, gs://, wasbs://, /vsis3/, /vsiaz/, /vsiadls/, /vsigs/, and /vsizip/ or /vsitar/ around one of these) or /vsimem/. A row that names /vsicurl/, http://, https://, ftp:// or another GDAL virtual file system is refused. This holds directly or inside a wrapper. The read fails with an error that names it, before anything is opened. The reader reads each row's file from a local or Volume path. Keep the files a manifest or a tile index lists there. See Security § 7.
A tile index is not a materialized-tile table. manifest / tilesTable catalog where the rasters are (paths, plus optional windows), essentially a saved file listing. The raster bytes stay in files and are read lazily (especially with virtualTiles=true). The index only lets the reader skip re-walking the directory. That is different from an ingest that has already decoded rasters into a Delta table with a tile-struct/bytes column. If you have that, read it directly with spark.table(...). You don't need a reader at all.
Read a tile index: read_tiles_table
spark.read.format("raster_gbx").option("tilesTable", ...) cannot read the table. Spark plans
the read in a worker that has no Spark session to open the table with. The read therefore fails with an
error that points here. read_tiles_table reads the table with your session and returns the
DataFrame the reader would return. It has the same (source, tile) columns and one row per tile.
Tiles are planned and read in tasks, and the table is never collected to the driver. It needs no JAR, and it uses
only spark.read and DataFrame operations, with no sparkContext, RDD or JVM access, so it works
over Spark Connect.
read_tiles_table(spark, table, options=None, *, format="raster_gbx", num_partitions=None)
| Parameter | Default | Description |
|---|---|---|
spark | required | The session that reads the table. |
table | required | The Delta tile index: a path column, and either a window struct or flat col_off, row_off, width and height columns for one tile per row. A row with only a path is a whole file (cut by tileSize or sizeInMB when you set them). |
options | None | Dict of the reader options on this page, for example virtualTiles, versionAsOf, timestampAsOf, skipOrdering, tileSize, sizeInMB. |
format | "raster_gbx" | "raster_gbx", "gtiff_gbx" or "cog_gbx". |
num_partitions | None | The number of tasks that read the tiles. By default two tasks per index row, up to 256, so the tiles of one source file are read in parallel and fewer of them share a task (a row cut into several tiles by tileSize or sizeInMB counts once). Tiles are spread by tile, not by source file. |
A tile whose file is missing fails the read.
Tile index auto-order and skipOrdering
A manifest read auto-orders tiles by source path before planning partitions. This groups all
tiles from the same source GeoTIFF into adjacent partitions. A worker that opens a large raster
once can then decode all its windows without reopening it. For a manifest with many tiles per source
file (a common windowed-GeoTIFF ingest), this amortization meaningfully reduces open overhead.
read_tiles_table spreads the tiles across tasks by tile, so that a source with many tiles is read
in parallel. It also orders the tiles by source path inside each task. The tiles of one source that
share a task are read one after another and reuse the opened file. Pass skipOrdering="true" to
leave that ordering out, for example when you order the tiles downstream:
read_tiles_table(
spark,
"geospatial.myschema.tile_index",
{"skipOrdering": "true", "virtualTiles": "true"},
)
Durable co-location: CLUSTER BY + OPTIMIZE
layout="order" (the default write layout) sorts rows by path at insert time, which groups
tiles per source for the lifetime of that write. New inserts and compaction can scatter them.
For a stable layout that survives compaction, use layout="cluster" at write time and run
OPTIMIZE afterward:
from databricks.labs.gbx.ds.file_gbx import gbx_file_write
gbx_file_write(
tiles_df,
target="geospatial.myschema.tile_index",
layout="cluster", # CLUSTER BY path in the DDL
file_mode="auto",
)
-- After initial write (or after bulk inserts), materialize clustering:
OPTIMIZE geospatial.myschema.tile_index;
With layout="cluster", OPTIMIZE physically co-locates tiles from the same source into the
same data files, so a scan of the index touches fewer files per source. read_tiles_table spreads
the tiles across tasks by tile whatever the layout of the table, so the layout does not change
which task reads a tile.
layout="order" (insert-time ORDER BY path) is the simpler default: no DDL change, no
OPTIMIZE required. It works well for tables that are built once. Use layout="cluster" when
the table is updated incrementally and you run periodic OPTIMIZE as part of maintenance.
Raster readers extract the CRS from each file's spatial reference metadata and store it as a canonical string in tile.metadata and the tile.crs field (e.g. "EPSG:4326", "ESRI:54008"). ESRI and OGC authorities are preserved. The clipCrs option declares the CRS of a plain WKT/WKB clip polygon; an embedded SRID in an EWKT/EWKB polygon always takes precedence. See Coordinate reference systems for the full CRS model.
Pin a tile index version: versionAsOf and timestampAsOf
A tile index is a Delta table, so its contents change as files are added to it. To plan a read
from the table as it was, pass one of two options to read_tiles_table:
versionAsOfreads that Delta version of the table (a non-negative integer, such as"3").timestampAsOfreads the version that was current at that time (such as"2026-10-01 00:00:00"). Delta accepts only a time between the table's first and latest commits. A time after the latest commit fails the read, even when the table has not changed since.
df = read_tiles_table(
spark, "geospatial.myschema.tile_index", {"virtualTiles": "true", "versionAsOf": "3"}
)
To re-run against exactly the tile index an earlier run used, pass the version that run read
as versionAsOf. The table's DESCRIBE HISTORY lists the versions. A timestamp
depends on commit times and is easy to place outside the table's history. Set at most one of the
two, and only for a tile index. A manifest or a directory walk has no version, so either option
there is an error. The table must be a Delta table. A version that does not exist
(or that VACUUM has removed), or a time outside the table's history, fails the read. The options
pin the tile index only. The index lists files, and the pixels are whatever those files hold when
the tiles are read.
Next Steps
- GeoTIFF Reader - Named reader for GeoTIFF format
- Raster Functions - Raster processing operations
- Quick Start - Get started with GeoBrix
- Ingestion Pipelines - ingest new and changed files incrementally
The *_gbx readers use the shared file_gbx file-access base for FILE / FUSE routing and enumeration — capability tiers, the no-gating rule, and layout options are described there.