Skip to content

Build — geocatalog.build

Index raster, array and vector files — local or in a bucket — into a catalog, and append new files to a saved one.

Raster

geocatalog.build.build_raster_catalog(filepaths, *, filename_regex=None, date_format='%Y%m%d', crs=None, engine='memory', out_path=None, write_bbox=True, sort_by=('start_time', 'geometry_hilbert'), partition_by=None, batch_size=10000, n_workers=1, ordered=False, storage_options=None, concurrency='sequential', max_concurrent=8)

Build a raster catalog — in-memory (default) or streamed to GeoParquet.

For each input file, opens it with rasterio, extracts its bounds (optionally projected through a lazy WarpedVRT if crs is set so no pixels are read), and parses the time interval from the filename via filename_regex. The result is a catalog queryable in milliseconds even over tens of thousands of files — rasterio builds the spatial R-tree lazily on first access.

Files whose filenames don't match the regex are skipped with a warning, not raised — so a heterogeneous directory partially populated by one product still produces a usable catalog.

Two backends:

  • engine="memory" (default): collects rows into a gpd.GeoDataFrame and returns an InMemoryGeoCatalog. Peak RAM is O(n_rows). Good up to ~10⁵ files.
  • engine="duckdb": streams rows through a pyarrow.parquet.ParquetWriter directly to out_path, then sorts via DuckDB (start_time, ST_Hilbert(ST_Centroid(geometry))) for row-group pruning. Peak RAM is O(batch_size). Scales to 10⁶+ files. Returns a DuckDBGeoCatalog opened on the freshly written artifact. Requires the [duckdb] extra.

Parameters:

Name Type Description Default
filepaths Sequence[str | Path]

Files to index. Anything rasterio.open accepts — local paths, S3 URLs via /vsis3/, HTTP URLs via /vsicurl/, etc.

required
filename_regex str | None

A regex with a named group capturing the date: either (?P<date>...) for single-date captures (treated as covering the full UTC day) or (?P<start>...) + (?P<stop>...) for explicit ranges. None treats every file as time-invariant and writes a sentinel interval (1900-01-01 to 2100-01-01) instead.

None
date_format str

strptime format for the named date groups. Default "%Y%m%d".

'%Y%m%d'
crs Any | None

CRS to project each file's bounds into. None keeps each file's native CRS in the memory engine; for the duckdb engine None is upgraded to "EPSG:4326" — the canonical wire format the design prescribes for shared GeoParquet artifacts (§sharp-edges of the design plan).

None
engine StorageEngine

"memory" for the existing in-RAM path, "duckdb" for the streamed GeoParquet path.

'memory'
out_path str | Path | None

Destination GeoParquet path. Required when engine="duckdb". Ignored when engine="memory".

None
write_bbox bool

Emit the GeoParquet 1.1 per-row bbox covering struct (used for predicate pushdown). Default True. Only consulted when engine="duckdb".

True
sort_by tuple[str, ...] | None

Sort keys for the post-write DuckDB rewrite. Each plain column name passes through; the literal token "geometry_hilbert" expands to ST_Hilbert(ST_Centroid(geometry)). None skips the rewrite and leaves rows in extraction order. Only consulted when engine="duckdb".

('start_time', 'geometry_hilbert')
partition_by tuple[str, ...] | None

Optional Hive partition columns for directory output when engine="duckdb". "year", "month", and "day" are derived from start_time.

None
batch_size int

Rows per Arrow record batch in the streaming writer. Default 10 000. Only consulted when engine="duckdb".

10000
n_workers int

Process-pool size for per-file metadata extraction. 1 runs sequentially in-process. >1 spawns a ProcessPoolExecutor (spawn start method) feeding the single in-process writer.

1
ordered bool

With engine="duckdb" and n_workers>1, preserve input row order instead of completion order. Useful for reproducible artifacts when sort_by=None. A slow input earlier in the queue stalls every subsequent yield and can temporarily reduce parallelism (workers may sit idle waiting on the next-in-line future). Prefer ordered=False for skewed workloads and sort post-hoc if you need a stable byte layout.

False
concurrency _Concurrency

Extraction strategy for the engine="memory" branch. "sequential" (default) extracts rows one at a time on the calling thread — the historical behaviour, no changes for existing callers. "async" fans extraction out via asyncio.gather + asyncio.to_thread so I/O on independent files overlaps; meaningful win when reading from a remote bucket (a 30-file build over WAN typically drops from O(n_files * RTT) to O((n_files / max_concurrent) * RTT)). Ignored for engine="duckdb", which already has n_workers for the same purpose.

'sequential'
max_concurrent int

Maximum in-flight file extractions when concurrency="async". Default 8 — a sweet spot between connection-reuse benefits and saturating the ThreadPoolExecutor that asyncio.to_thread shares across the process.

8

Returns:

Type Description
InMemoryGeoCatalog | DuckDBGeoCatalog

InMemoryGeoCatalog for engine="memory", otherwise a

InMemoryGeoCatalog | DuckDBGeoCatalog

DuckDBGeoCatalog opened on out_path.

Raises:

Type Description
ValueError

No files matched (or out_path missing in the duckdb branch).

Source code in packages/geotoolz-catalog/src/geocatalog/_src/formats/raster.py
@renamed_kwargs(backend="engine", target_crs="crs")
def build_raster_catalog(
    filepaths: Sequence[str | Path],
    *,
    filename_regex: str | None = None,
    date_format: str = "%Y%m%d",
    crs: Any | None = None,
    engine: StorageEngine = "memory",
    out_path: str | Path | None = None,
    write_bbox: bool = True,
    sort_by: tuple[str, ...] | None = ("start_time", "geometry_hilbert"),
    partition_by: tuple[str, ...] | None = None,
    batch_size: int = 10_000,
    n_workers: int = 1,
    ordered: bool = False,
    storage_options: dict[str, Any] | None = None,
    concurrency: _Concurrency = "sequential",
    max_concurrent: int = 8,
) -> InMemoryGeoCatalog | DuckDBGeoCatalog:
    """Build a raster catalog — in-memory (default) or streamed to GeoParquet.

    For each input file, opens it with `rasterio`, extracts its bounds
    (optionally projected through a lazy `WarpedVRT` if ``crs``
    is set so no pixels are read), and parses the time interval from
    the filename via ``filename_regex``. The result is a catalog
    queryable in milliseconds even over tens of thousands of files —
    `rasterio` builds the spatial R-tree lazily on first access.

    Files whose filenames don't match the regex are *skipped with a
    warning*, not raised — so a heterogeneous directory partially
    populated by one product still produces a usable catalog.

    Two backends:

    - ``engine="memory"`` (default): collects rows into a
      `gpd.GeoDataFrame` and returns an `InMemoryGeoCatalog`. Peak RAM is
      ``O(n_rows)``. Good up to ~10⁵ files.
    - ``engine="duckdb"``: streams rows through a `pyarrow.parquet.ParquetWriter`
      directly to ``out_path``, then sorts via DuckDB ``(start_time,
      ST_Hilbert(ST_Centroid(geometry)))`` for row-group pruning. Peak RAM
      is ``O(batch_size)``. Scales to 10⁶+ files. Returns a
      `DuckDBGeoCatalog` opened on the freshly written artifact. Requires
      the ``[duckdb]`` extra.

    Args:
        filepaths: Files to index. Anything `rasterio.open` accepts —
            local paths, S3 URLs via `/vsis3/`, HTTP URLs via
            `/vsicurl/`, etc.
        filename_regex: A regex with a named group capturing the date:
            either ``(?P<date>...)`` for single-date captures (treated
            as covering the full UTC day) or ``(?P<start>...)`` +
            ``(?P<stop>...)`` for explicit ranges. ``None`` treats every
            file as time-invariant and writes a sentinel interval
            (``1900-01-01`` to ``2100-01-01``) instead.
        date_format: ``strptime`` format for the named date groups.
            Default ``"%Y%m%d"``.
        crs: CRS to project each file's bounds into. ``None``
            keeps each file's native CRS in the memory engine; for the
            duckdb engine ``None`` is upgraded to ``"EPSG:4326"`` —
            the canonical wire format the design prescribes for shared
            GeoParquet artifacts (§sharp-edges of the design plan).
        engine: ``"memory"`` for the existing in-RAM path,
            ``"duckdb"`` for the streamed GeoParquet path.
        out_path: Destination GeoParquet path. Required when
            ``engine="duckdb"``. Ignored when ``engine="memory"``.
        write_bbox: Emit the GeoParquet 1.1 per-row ``bbox`` covering
            struct (used for predicate pushdown). Default True. Only
            consulted when ``engine="duckdb"``.
        sort_by: Sort keys for the post-write DuckDB rewrite. Each
            plain column name passes through; the literal token
            ``"geometry_hilbert"`` expands to
            ``ST_Hilbert(ST_Centroid(geometry))``. ``None`` skips the
            rewrite and leaves rows in extraction order. Only consulted
            when ``engine="duckdb"``.
        partition_by: Optional Hive partition columns for directory
            output when ``engine="duckdb"``. ``"year"``, ``"month"``,
            and ``"day"`` are derived from ``start_time``.
        batch_size: Rows per Arrow record batch in the streaming
            writer. Default 10 000. Only consulted when
            ``engine="duckdb"``.
        n_workers: Process-pool size for per-file metadata extraction.
            ``1`` runs sequentially in-process. ``>1`` spawns a
            ``ProcessPoolExecutor`` (``spawn`` start method) feeding
            the single in-process writer.
        ordered: With ``engine="duckdb"`` and ``n_workers>1``, preserve
            input row order instead of completion order. Useful for
            reproducible artifacts when ``sort_by=None``. A slow input
            earlier in the queue stalls every subsequent yield and can
            temporarily reduce parallelism (workers may sit idle waiting
            on the next-in-line future). Prefer ``ordered=False`` for
            skewed workloads and sort post-hoc if you need a stable byte
            layout.
        concurrency: Extraction strategy for the ``engine="memory"``
            branch. ``"sequential"`` (default) extracts rows one at a
            time on the calling thread — the historical behaviour, no
            changes for existing callers. ``"async"`` fans extraction
            out via ``asyncio.gather`` + ``asyncio.to_thread`` so I/O
            on independent files overlaps; meaningful win when reading
            from a remote bucket (a 30-file build over WAN typically
            drops from O(n_files * RTT) to O((n_files / max_concurrent)
            * RTT)). Ignored for ``engine="duckdb"``, which already
            has ``n_workers`` for the same purpose.
        max_concurrent: Maximum in-flight file extractions when
            ``concurrency="async"``. Default 8 — a sweet spot between
            connection-reuse benefits and saturating the
            ``ThreadPoolExecutor`` that ``asyncio.to_thread`` shares
            across the process.

    Returns:
        ``InMemoryGeoCatalog`` for ``engine="memory"``, otherwise a
        ``DuckDBGeoCatalog`` opened on ``out_path``.

    Raises:
        ValueError: No files matched (or `out_path` missing in the
            duckdb branch).
    """
    if engine not in ("memory", "duckdb"):
        raise ValueError(
            f"build_raster_catalog: engine must be 'memory' or 'duckdb'; got {engine!r}"
        )
    if engine == "duckdb":
        if out_path is None:
            raise ValueError("build_raster_catalog(engine='duckdb') requires out_path")
        return _build_raster_catalog_duckdb(
            filepaths,
            filename_regex=filename_regex,
            date_format=date_format,
            target_crs=crs,
            out_path=out_path,
            write_bbox=write_bbox,
            sort_by=sort_by,
            partition_by=partition_by,
            batch_size=batch_size,
            n_workers=n_workers,
            ordered=ordered,
            storage_options=storage_options,
        )

    if concurrency not in ("sequential", "async"):
        raise ValueError(
            f"build_raster_catalog: concurrency must be 'sequential' or 'async'; "
            f"got {concurrency!r}"
        )
    if max_concurrent < 1:
        raise ValueError(
            f"build_raster_catalog: max_concurrent must be >= 1; got {max_concurrent}"
        )

    pattern = re.compile(filename_regex) if filename_regex is not None else None
    rows: list[dict[str, Any]]
    if concurrency == "async":
        rows = _run_coroutine_safely(
            _extract_rows_async(
                filepaths,
                filename_regex=pattern,
                date_format=date_format,
                target_crs=crs,
                storage_options=storage_options,
                max_concurrent=max_concurrent,
            )
        )
    else:
        rows = []
        for fp in filepaths:
            row = _filepath_to_row(
                fp,
                filename_regex=pattern,
                date_format=date_format,
                target_crs=crs,
                storage_options=storage_options,
            )
            if row is not None:
                rows.append(row)
    if not rows:
        raise ValueError("build_raster_catalog: no files matched the regex")

    crs_value = crs if crs is not None else rows[0]["crs"]
    if crs is None:
        # Without a target CRS each footprint is in its file's own CRS.
        # Latch the first row's CRS and reproject the others into it, as
        # `build_vector_catalog` does, so the catalog never mixes CRSs
        # under one label (#217).
        rows = [_reproject_row(row, crs_value) for row in rows]
    gdf = gpd.GeoDataFrame(rows, geometry="geometry", crs=crs_value)
    return InMemoryGeoCatalog(gdf, kind="raster")

Xarray (extras: [xarray-raster])

geocatalog.build.build_xarray_catalog(filepaths, *, crs=None, data_vars=None, time_var='time', engine='memory', out_path=None, write_bbox=True, sort_by=('start_time', 'geometry_hilbert'), partition_by=None, batch_size=10000, n_workers=1, ordered=False, storage_options=None)

Build an xarray-shaped catalog — in-memory (default) or streamed.

For each input file, opens it with xr.open_dataset, derives the spatial footprint from the min/max of its (x, y) / (lon, lat) / (longitude, latitude) coordinates, and reads the time interval from the time_var coordinate. If rioxarray is loaded and the dataset carries a CRS through its rio accessor, that wins; otherwise the catalog falls back to crs.

Backends mirror build_raster_catalog. The streaming branch (engine="duckdb") requires the [duckdb] extra and an explicit crs — unlike the raster builder, xarray coordinate bounds are not reprojected, so the CRS metadata must match the dataset's native coords. Passing crs=None in the duckdb branch raises ValueError.

Parameters:

Name Type Description Default
filepaths Sequence[str | Path]

Files to index. .zarr paths (and directories) are opened with the zarr engine; everything else falls back to netcdf4 / h5netcdf.

required
crs Any | None

CRS to tag the catalog with when files don't carry their own. Coordinate bounds are not reprojected — there's no WarpedVRT analogue for xarray — so this should match the files' native CRS.

None
data_vars Sequence[str] | None

Subset of data variables recorded per row. Loaders consult this to pick which arrays to materialise. None leaves it open-ended; downstream load_xarray can still override.

None
time_var str

Coordinate name for the time axis. Default "time". Files where this coordinate is missing get the sentinel interval [1900-01-01, 2100-01-01].

'time'
engine StorageEngine

"memory" for the existing in-RAM path, "duckdb" for the streamed GeoParquet path.

'memory'
out_path str | Path | None

Destination GeoParquet path. Required when engine="duckdb".

None
write_bbox bool

Emit the GeoParquet 1.1 covering bbox struct. Only consulted when engine="duckdb".

True
sort_by tuple[str, ...] | None

Sort keys for the post-write DuckDB rewrite; literal "geometry_hilbert" expands to ST_Hilbert(ST_Centroid(geometry)). None skips the rewrite. Only consulted when engine="duckdb".

('start_time', 'geometry_hilbert')
partition_by tuple[str, ...] | None

Optional Hive partition columns for directory output when engine="duckdb". "year", "month", and "day" are derived from start_time.

None
batch_size int

Rows per Arrow record batch. Default 10 000.

10000
n_workers int

Process-pool size for per-file extraction.

1
ordered bool

With engine="duckdb" and n_workers>1, preserve input row order instead of completion order. Useful for reproducible artifacts when sort_by=None. A slow input earlier in the queue stalls every subsequent yield and can temporarily reduce parallelism (workers may sit idle waiting on the next-in-line future). Prefer ordered=False for skewed workloads and sort post-hoc if you need a stable byte layout.

False

Returns:

Type Description
InMemoryGeoCatalog | DuckDBGeoCatalog

InMemoryGeoCatalog for engine="memory", otherwise a

InMemoryGeoCatalog | DuckDBGeoCatalog

DuckDBGeoCatalog.

Raises:

Type Description
ImportError

If the [xarray-raster] extra is not installed.

ValueError

If no files yielded a row or out_path missing in the duckdb branch.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/formats/xarray_backend.py
@renamed_kwargs(backend="engine", target_crs="crs")
def build_xarray_catalog(
    filepaths: Sequence[str | Path],
    *,
    crs: Any | None = None,
    data_vars: Sequence[str] | None = None,
    time_var: str = "time",
    engine: StorageEngine = "memory",
    out_path: str | Path | None = None,
    write_bbox: bool = True,
    sort_by: tuple[str, ...] | None = ("start_time", "geometry_hilbert"),
    partition_by: tuple[str, ...] | None = None,
    batch_size: int = 10_000,
    n_workers: int = 1,
    ordered: bool = False,
    storage_options: dict[str, Any] | None = None,
) -> InMemoryGeoCatalog | DuckDBGeoCatalog:
    """Build an xarray-shaped catalog — in-memory (default) or streamed.

    For each input file, opens it with ``xr.open_dataset``, derives the
    spatial footprint from the min/max of its (x, y) / (lon, lat) /
    (longitude, latitude) coordinates, and reads the time interval from
    the ``time_var`` coordinate. If `rioxarray` is loaded and the
    dataset carries a CRS through its ``rio`` accessor, that wins;
    otherwise the catalog falls back to ``crs``.

    Backends mirror `build_raster_catalog`. The streaming branch
    (`engine="duckdb"`) requires the ``[duckdb]`` extra and an
    *explicit* ``crs`` — unlike the raster builder, xarray
    coordinate bounds are *not* reprojected, so the CRS metadata must
    match the dataset's native coords. Passing ``crs=None`` in
    the duckdb branch raises `ValueError`.

    Args:
        filepaths: Files to index. ``.zarr`` paths (and directories)
            are opened with the zarr engine; everything else falls
            back to netcdf4 / h5netcdf.
        crs: CRS to tag the catalog with when files don't carry
            their own. Coordinate bounds are *not* reprojected — there's
            no `WarpedVRT` analogue for xarray — so this should match
            the files' native CRS.
        data_vars: Subset of data variables recorded per row. Loaders
            consult this to pick which arrays to materialise. ``None``
            leaves it open-ended; downstream `load_xarray` can still
            override.
        time_var: Coordinate name for the time axis. Default ``"time"``.
            Files where this coordinate is missing get the sentinel
            interval ``[1900-01-01, 2100-01-01]``.
        engine: ``"memory"`` for the existing in-RAM path,
            ``"duckdb"`` for the streamed GeoParquet path.
        out_path: Destination GeoParquet path. Required when
            ``engine="duckdb"``.
        write_bbox: Emit the GeoParquet 1.1 covering ``bbox`` struct.
            Only consulted when ``engine="duckdb"``.
        sort_by: Sort keys for the post-write DuckDB rewrite; literal
            ``"geometry_hilbert"`` expands to
            ``ST_Hilbert(ST_Centroid(geometry))``. ``None`` skips the
            rewrite. Only consulted when ``engine="duckdb"``.
        partition_by: Optional Hive partition columns for directory
            output when ``engine="duckdb"``. ``"year"``, ``"month"``,
            and ``"day"`` are derived from ``start_time``.
        batch_size: Rows per Arrow record batch. Default 10 000.
        n_workers: Process-pool size for per-file extraction.
        ordered: With ``engine="duckdb"`` and ``n_workers>1``, preserve
            input row order instead of completion order. Useful for
            reproducible artifacts when ``sort_by=None``. A slow input
            earlier in the queue stalls every subsequent yield and can
            temporarily reduce parallelism (workers may sit idle waiting
            on the next-in-line future). Prefer ``ordered=False`` for
            skewed workloads and sort post-hoc if you need a stable byte
            layout.

    Returns:
        `InMemoryGeoCatalog` for ``engine="memory"``, otherwise a
        `DuckDBGeoCatalog`.

    Raises:
        ImportError: If the ``[xarray-raster]`` extra is not installed.
        ValueError: If no files yielded a row or ``out_path`` missing
            in the duckdb branch.
    """
    if engine not in ("memory", "duckdb"):
        raise ValueError(
            f"build_xarray_catalog: engine must be 'memory' or 'duckdb'; got {engine!r}"
        )
    if engine == "duckdb":
        if out_path is None:
            raise ValueError("build_xarray_catalog(engine='duckdb') requires out_path")
        return _build_xarray_catalog_duckdb(
            filepaths,
            target_crs=crs,
            data_vars=data_vars,
            time_var=time_var,
            out_path=out_path,
            write_bbox=write_bbox,
            sort_by=sort_by,
            partition_by=partition_by,
            batch_size=batch_size,
            n_workers=n_workers,
            ordered=ordered,
            storage_options=storage_options,
        )

    rows: list[dict[str, Any]] = [
        _xarray_row(
            fp,
            data_vars=data_vars,
            time_var=time_var,
            target_crs=crs,
            storage_options=storage_options,
        )
        for fp in filepaths
    ]
    if not rows:
        raise ValueError("build_xarray_catalog: no files yielded a row")
    crs_value = crs if crs is not None else rows[0]["crs"]
    if crs_value is None:
        raise ValueError(
            "build_xarray_catalog: cannot determine catalog CRS — pass "
            "`crs=...` explicitly, or load `rioxarray` so the "
            "dataset's `.rio.crs` accessor reports a CRS."
        )
    gdf = gpd.GeoDataFrame(rows, geometry="geometry", crs=crs_value)
    return InMemoryGeoCatalog(gdf, kind="xarray")

Model states (extras: [xarray-raster])

geocatalog.build.build_state_catalog(filepaths, *, crs=None, names=CF_NAMES, data_vars=None, engine='memory', out_path=None, write_bbox=True, sort_by=('start_time', 'geometry_hilbert'), batch_size=10000, n_workers=1, storage_options=None)

Index model-state files: one row per file, with the state columns filled.

Each file is indexed like build_xarray_catalog does (footprint from the coordinates, valid-time interval from the time axis), and the reserved state columns are read from its metadata through names: kind, run_time, member, producer and parents. A field that is not found is null. Lead time is not stored: a row's leads are its valid times minus run_time.

Parameters:

Name Type Description Default
filepaths Sequence[str | Path]

NetCDF / Zarr files, one run and member each.

required
crs Any | None

CRS of the files' coordinates, when they don't carry one (coordinates are not reprojected).

None
names StateNames

Where each field lives: a mapping from valid_time, run_time, member, kind, producer and parents to a name (a coordinate or variable, else a global attribute), a callable on the file path, or a tuple of them tried in order: CF_NAMES (the default) for CF files, CFGRIB_NAMES for cfgrib-decoded GRIB, or your own map ({**CF_NAMES, "kind": lambda p: "forecast"}).

CF_NAMES
data_vars Sequence[str] | None

Data variables recorded per row (as in build_xarray_catalog).

None
engine StorageEngine

"memory" for an InMemoryGeoCatalog, "duckdb" to stream the rows to GeoParquet at out_path and open them lazily ([duckdb] extra; needs crs).

'memory'
out_path str | Path | None

Destination GeoParquet path for engine="duckdb".

None
write_bbox bool

Emit the GeoParquet 1.1 bbox covering struct (engine="duckdb" only).

True
sort_by tuple[str, ...] | None

Sort keys for the DuckDB rewrite (engine="duckdb" only); None keeps the input order.

('start_time', 'geometry_hilbert')
batch_size int

Rows per Arrow record batch (engine="duckdb").

10000
n_workers int

Process-pool size for per-file extraction (engine="duckdb"; names must then be picklable, so no lambdas).

1
storage_options dict[str, Any] | None

obstore options for remote files (geocloud.fs).

None

Returns:

Type Description
InMemoryGeoCatalog | DuckDBGeoCatalog

A catalog of kind "xarray" with the five state columns.

Raises:

Type Description
ImportError

If the [xarray-raster] extra is missing.

ValueError

If no file was given, the CRS is unknown, a file's kind is not analysis / forecast / reanalysis, or a run-time / member source holds more than one value.

Example

from geocatalog.build import build_state_catalog from geocatalog.states import CF_NAMES catalog = build_state_catalog(paths, crs="EPSG:4326", names=CF_NAMES) catalog.gdf[["kind", "run_time", "member"]].iloc[0].tolist() ['forecast', Timestamp('2026-01-01 00:00:00'), '0']

Source code in packages/geotoolz-catalog/src/geocatalog/_src/formats/states.py
def build_state_catalog(
    filepaths: Sequence[str | Path],
    *,
    crs: Any | None = None,
    names: StateNames = CF_NAMES,
    data_vars: Sequence[str] | None = None,
    engine: StorageEngine = "memory",
    out_path: str | Path | None = None,
    write_bbox: bool = True,
    sort_by: tuple[str, ...] | None = ("start_time", "geometry_hilbert"),
    batch_size: int = 10_000,
    n_workers: int = 1,
    storage_options: dict[str, Any] | None = None,
) -> InMemoryGeoCatalog | DuckDBGeoCatalog:
    """Index model-state files: one row per file, with the state columns filled.

    Each file is indexed like `build_xarray_catalog` does (footprint from
    the coordinates, valid-time interval from the time axis), and the
    reserved state columns are read from its metadata through ``names``:
    ``kind``, ``run_time``, ``member``, ``producer`` and ``parents``. A
    field that is not found is null. Lead time is not stored: a row's
    leads are its valid times minus ``run_time``.

    Args:
        filepaths: NetCDF / Zarr files, one run and member each.
        crs: CRS of the files' coordinates, when they don't carry one
            (coordinates are not reprojected).
        names: Where each field lives: a mapping from ``valid_time``,
            ``run_time``, ``member``, ``kind``, ``producer`` and
            ``parents`` to a name (a coordinate or variable, else a
            global attribute), a callable on the file path, or a tuple of
            them tried in order: `CF_NAMES` (the default) for CF files,
            `CFGRIB_NAMES` for cfgrib-decoded GRIB, or your own map
            (``{**CF_NAMES, "kind": lambda p: "forecast"}``).
        data_vars: Data variables recorded per row (as in
            `build_xarray_catalog`).
        engine: ``"memory"`` for an `InMemoryGeoCatalog`, ``"duckdb"``
            to stream the rows to GeoParquet at ``out_path`` and open
            them lazily (``[duckdb]`` extra; needs ``crs``).
        out_path: Destination GeoParquet path for ``engine="duckdb"``.
        write_bbox: Emit the GeoParquet 1.1 ``bbox`` covering struct
            (``engine="duckdb"`` only).
        sort_by: Sort keys for the DuckDB rewrite (``engine="duckdb"``
            only); ``None`` keeps the input order.
        batch_size: Rows per Arrow record batch (``engine="duckdb"``).
        n_workers: Process-pool size for per-file extraction
            (``engine="duckdb"``; ``names`` must then be picklable, so no
            lambdas).
        storage_options: obstore options for remote files (`geocloud.fs`).

    Returns:
        A catalog of kind ``"xarray"`` with the five state columns.

    Raises:
        ImportError: If the ``[xarray-raster]`` extra is missing.
        ValueError: If no file was given, the CRS is unknown, a file's
            ``kind`` is not ``analysis`` / ``forecast`` / ``reanalysis``,
            or a run-time / member source holds more than one value.

    Example:
        >>> from geocatalog.build import build_state_catalog
        >>> from geocatalog.states import CF_NAMES
        >>> catalog = build_state_catalog(paths, crs="EPSG:4326", names=CF_NAMES)
        >>> catalog.gdf[["kind", "run_time", "member"]].iloc[0].tolist()
        ['forecast', Timestamp('2026-01-01 00:00:00'), '0']
    """
    if xr is None:
        raise missing_extra("`build_state_catalog`", "xarray-raster")
    if engine not in ("memory", "duckdb"):
        raise ValueError(
            f"build_state_catalog: engine must be 'memory' or 'duckdb'; got {engine!r}"
        )
    unknown = set(names) - set(_FIELDS)
    if unknown:
        raise ValueError(
            f"build_state_catalog: unknown field(s) {sorted(unknown)} in names; "
            f"expected some of {list(_FIELDS)}."
        )
    extract: Callable[[str | Path], dict[str, Any]] = functools.partial(
        _state_row,
        names=names,
        data_vars=tuple(data_vars) if data_vars is not None else None,
        target_crs=crs,
        storage_options=storage_options,
    )
    if engine == "duckdb":
        from geocatalog._src.storage.streaming import stream_build_duckdb

        if out_path is None:
            raise ValueError("build_state_catalog(engine='duckdb') requires out_path")
        if crs is None:
            raise ValueError(
                "build_state_catalog(engine='duckdb') requires crs (coordinate "
                "bounds are not reprojected)."
            )
        return stream_build_duckdb(
            filepaths,
            extract,
            out_path=out_path,
            crs=crs,
            kind="xarray",
            write_bbox=write_bbox,
            sort_by=sort_by,
            batch_size=batch_size,
            n_workers=n_workers,
        )

    rows = [extract(fp) for fp in filepaths]
    if not rows:
        raise ValueError("build_state_catalog: no files given")
    crs_value = crs if crs is not None else rows[0]["crs"]
    if crs_value is None:
        raise ValueError(
            "build_state_catalog: cannot determine the catalog CRS; pass crs=..."
        )
    gdf = gpd.GeoDataFrame(rows, geometry="geometry", crs=crs_value)
    return InMemoryGeoCatalog(coerce_state_columns(gdf), kind="xarray")

Vector

geocatalog.build.build_vector_catalog(filepaths, *, filename_regex=None, date_format='%Y%m%d', crs=None, layer=None, engine='memory', out_path=None, write_bbox=True, sort_by=('start_time', 'geometry_hilbert'), partition_by=None, batch_size=10000, n_workers=1, ordered=False, storage_options=None)

Build a vector catalog — in-memory (default) or streamed to GeoParquet.

For each input file, opens it with geopandas.read_file, optionally reprojects to crs, and records the file's total_bounds polygon as the catalog footprint. Time is parsed from the filename via filename_regex, mirroring build_raster_catalog. Empty files and non-matching filenames are skipped with a warning.

Backends mirror build_raster_catalog:

  • engine="memory" (default): collects rows into a gdf and returns an InMemoryGeoCatalog. First-non-empty file's native CRS latches the catalog CRS when crs=None.
  • engine="duckdb": streams rows to a GeoParquet at out_path and returns a DuckDBGeoCatalog. CRS-latching is disabled — every file is reprojected to crs (EPSG:4326 by default). Requires the [duckdb] extra.

Parameters:

Name Type Description Default
filepaths Sequence[str | Path]

Files to index. Anything geopandas.read_file accepts (Shapefile, GeoPackage, GeoJSON, FlatGeobuf, …).

required
filename_regex str | None

A regex with a (?P<date>...) group, or (?P<start>...) + (?P<stop>...) groups, used to parse the time interval out of each filename. None treats every file as time-invariant (sentinel interval).

None
date_format str

strptime format for the named date groups. Default "%Y%m%d".

'%Y%m%d'
crs Any | None

CRS for footprint + storage. For engine="memory", None latches onto the first non-empty file's native CRS and reprojects every subsequent file to match. For engine="duckdb", None is upgraded to "EPSG:4326".

None
layer str | int | None

Layer name or index for multi-layer files (GeoPackage, GDB). None opens the file's default layer.

None
engine StorageEngine

"memory" for the existing in-RAM path, "duckdb" for the streamed GeoParquet path.

'memory'
out_path str | Path | None

Destination GeoParquet path. Required when engine="duckdb".

None
write_bbox bool

Emit the GeoParquet 1.1 covering bbox struct. Only consulted when engine="duckdb".

True
sort_by tuple[str, ...] | None

Sort keys for the post-write DuckDB rewrite; literal "geometry_hilbert" expands to ST_Hilbert(ST_Centroid(geometry)). None skips the rewrite. Only consulted when engine="duckdb".

('start_time', 'geometry_hilbert')
partition_by tuple[str, ...] | None

Optional Hive partition columns for directory output when engine="duckdb". "year", "month", and "day" are derived from start_time.

None
batch_size int

Rows per Arrow record batch. Default 10 000.

10000
n_workers int

Process-pool size for per-file extraction. 1 runs sequentially.

1
ordered bool

With engine="duckdb" and n_workers>1, preserve input row order instead of completion order. Useful for reproducible artifacts when sort_by=None. A slow input earlier in the queue stalls every subsequent yield and can temporarily reduce parallelism (workers may sit idle waiting on the next-in-line future). Prefer ordered=False for skewed workloads and sort post-hoc if you need a stable byte layout.

False

Returns:

Type Description
InMemoryGeoCatalog | DuckDBGeoCatalog

InMemoryGeoCatalog for engine="memory", otherwise a

InMemoryGeoCatalog | DuckDBGeoCatalog

DuckDBGeoCatalog.

Raises:

Type Description
ValueError

If no files yielded a row, or out_path missing in the duckdb branch.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/formats/vector.py
@renamed_kwargs(backend="engine", target_crs="crs")
def build_vector_catalog(
    filepaths: Sequence[str | Path],
    *,
    filename_regex: str | None = None,
    date_format: str = "%Y%m%d",
    crs: Any | None = None,
    layer: str | int | None = None,
    engine: StorageEngine = "memory",
    out_path: str | Path | None = None,
    write_bbox: bool = True,
    sort_by: tuple[str, ...] | None = ("start_time", "geometry_hilbert"),
    partition_by: tuple[str, ...] | None = None,
    batch_size: int = 10_000,
    n_workers: int = 1,
    ordered: bool = False,
    storage_options: dict[str, Any] | None = None,
) -> InMemoryGeoCatalog | DuckDBGeoCatalog:
    """Build a vector catalog — in-memory (default) or streamed to GeoParquet.

    For each input file, opens it with `geopandas.read_file`, optionally
    reprojects to ``crs``, and records the file's
    ``total_bounds`` polygon as the catalog footprint. Time is parsed
    from the filename via ``filename_regex``, mirroring
    `build_raster_catalog`. Empty files and non-matching filenames are
    skipped with a warning.

    Backends mirror `build_raster_catalog`:

    - ``engine="memory"`` (default): collects rows into a gdf and
      returns an `InMemoryGeoCatalog`. First-non-empty file's native CRS
      latches the catalog CRS when ``crs=None``.
    - ``engine="duckdb"``: streams rows to a GeoParquet at ``out_path``
      and returns a `DuckDBGeoCatalog`. CRS-latching is disabled — every
      file is reprojected to ``crs`` (EPSG:4326 by default).
      Requires the ``[duckdb]`` extra.

    Args:
        filepaths: Files to index. Anything `geopandas.read_file`
            accepts (Shapefile, GeoPackage, GeoJSON, FlatGeobuf, …).
        filename_regex: A regex with a ``(?P<date>...)`` group, or
            ``(?P<start>...)`` + ``(?P<stop>...)`` groups, used to parse
            the time interval out of each filename. ``None`` treats
            every file as time-invariant (sentinel interval).
        date_format: ``strptime`` format for the named date groups.
            Default ``"%Y%m%d"``.
        crs: CRS for footprint + storage. For ``engine="memory"``,
            ``None`` latches onto the first non-empty file's native CRS
            and reprojects every subsequent file to match. For
            ``engine="duckdb"``, ``None`` is upgraded to ``"EPSG:4326"``.
        layer: Layer name or index for multi-layer files (GeoPackage,
            GDB). ``None`` opens the file's default layer.
        engine: ``"memory"`` for the existing in-RAM path,
            ``"duckdb"`` for the streamed GeoParquet path.
        out_path: Destination GeoParquet path. Required when
            ``engine="duckdb"``.
        write_bbox: Emit the GeoParquet 1.1 covering ``bbox`` struct.
            Only consulted when ``engine="duckdb"``.
        sort_by: Sort keys for the post-write DuckDB rewrite; literal
            ``"geometry_hilbert"`` expands to
            ``ST_Hilbert(ST_Centroid(geometry))``. ``None`` skips the
            rewrite. Only consulted when ``engine="duckdb"``.
        partition_by: Optional Hive partition columns for directory
            output when ``engine="duckdb"``. ``"year"``, ``"month"``,
            and ``"day"`` are derived from ``start_time``.
        batch_size: Rows per Arrow record batch. Default 10 000.
        n_workers: Process-pool size for per-file extraction. ``1``
            runs sequentially.
        ordered: With ``engine="duckdb"`` and ``n_workers>1``, preserve
            input row order instead of completion order. Useful for
            reproducible artifacts when ``sort_by=None``. A slow input
            earlier in the queue stalls every subsequent yield and can
            temporarily reduce parallelism (workers may sit idle waiting
            on the next-in-line future). Prefer ``ordered=False`` for
            skewed workloads and sort post-hoc if you need a stable byte
            layout.

    Returns:
        `InMemoryGeoCatalog` for ``engine="memory"``, otherwise a
        `DuckDBGeoCatalog`.

    Raises:
        ValueError: If no files yielded a row, or ``out_path`` missing
            in the duckdb branch.
    """
    if engine not in ("memory", "duckdb"):
        raise ValueError(
            f"build_vector_catalog: engine must be 'memory' or 'duckdb'; got {engine!r}"
        )
    if engine == "duckdb":
        if out_path is None:
            raise ValueError("build_vector_catalog(engine='duckdb') requires out_path")
        return _build_vector_catalog_duckdb(
            filepaths,
            filename_regex=filename_regex,
            date_format=date_format,
            target_crs=crs,
            layer=layer,
            out_path=out_path,
            write_bbox=write_bbox,
            sort_by=sort_by,
            partition_by=partition_by,
            batch_size=batch_size,
            n_workers=n_workers,
            ordered=ordered,
            storage_options=storage_options,
        )

    pattern = re.compile(filename_regex) if filename_regex is not None else None
    rows: list[dict[str, Any]] = []
    # `effective_crs` starts as the user-supplied `crs` (possibly
    # None). On the first non-empty file we latch onto its native CRS,
    # then pass that down to subsequent calls so every later file's
    # footprint is reprojected into the catalog's uniform CRS. This is
    # what keeps mixed-CRS archives honest.
    # Latching precedence: an empty file returns `(None, None)` and
    # contributes nothing; a non-matching filename with a non-empty file
    # returns `(None, observed_crs)` and we skip it but DO NOT latch
    # (we have no row to anchor). Only matched rows seed `effective_crs`.
    # This keeps the catalog's CRS aligned with the rows it actually
    # contains, even when leading files are empty or unmatched.
    effective_crs = crs
    for fp in filepaths:
        row, observed_crs = _vector_row(
            fp,
            filename_regex=pattern,
            date_format=date_format,
            target_crs=effective_crs,
            layer=layer,
            storage_options=storage_options,
        )
        if row is None:
            continue
        rows.append(row)
        if effective_crs is None and observed_crs is not None:
            effective_crs = observed_crs
    if not rows:
        raise ValueError("build_vector_catalog: no files yielded a row")
    gdf = gpd.GeoDataFrame(rows, geometry="geometry", crs=effective_crs)
    return InMemoryGeoCatalog(gdf, kind="vector")

Appending to a saved catalog

geocatalog.build.append_files(archive, filepaths, extract_fn, *, crs, kind, partition_by, write_bbox=True, batch_size=10000, n_workers=1, max_open_writers=_DEFAULT_MAX_OPEN_WRITERS)

Append new files to a Hive-partitioned GeoParquet archive.

Only the new rows are extracted and written; existing shards are left untouched, so append work is O(N_new) plus the number of new partitions touched (and one read of the archive's filepath column). The archive is created if it does not exist.

Appending is idempotent: files whose filepath is already indexed in the archive (or repeated within filepaths) are skipped, so re-running the same call — including after an interruption that left only some of the new shards moved in — never duplicates rows; it completes the append instead.

Before any rows are written, the caller-supplied partition_by is validated against the archive's existing layout (the directory tree of key=value dirs). A mismatch raises ValueError rather than silently producing a mixed-layout archive that downstream readers can't reconstruct cleanly. A fresh archive (no existing shards) accepts the caller's partition_by as the source of truth.

New shards are written at the archive's _schema_version, so a pre-upgrade (v0) archive stays at a single version after an append and keeps opening: an archive is upgraded as a whole, never shard by shard.

Parameters:

Name Type Description Default
archive str | Path

Hive-partitioned GeoParquet directory.

required
filepaths Sequence[str | Path]

New source files to index.

required
extract_fn Callable[[str | Path], dict[str, Any] | None]

Picklable per-file extractor, same contract as stream_build_duckdb.

required
crs Any

CRS to encode in the new shard metadata.

required
kind CatalogKind

Catalog kind (loader dispatch).

required
partition_by Sequence[str]

Hive partition columns. "year", "month", and "day" are derived from each row's start_time. Must match the existing archive's layout, if any.

required
write_bbox bool

Emit the GeoParquet 1.1 bbox covering struct.

True
batch_size int

Rows per Arrow record batch.

10000
n_workers int

Process-pool size for extraction.

1
max_open_writers int

Cap on concurrently open shard writers; see write_partitioned_rows.

_DEFAULT_MAX_OPEN_WRITERS

Returns:

Type Description
DuckDBGeoCatalog

A DuckDBGeoCatalog opened on the updated archive.

Raises:

Type Description
ValueError

partition_by differs from the archive's existing layout, or no input files yielded a row (and none were skipped as already indexed).

CatalogSchemaError

The archive's shards are newer than the reader, or already at mixed versions.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/storage/streaming.py
@renamed_kwargs(backend="kind")
def append_files(
    archive: str | Path,
    filepaths: Sequence[str | Path],
    extract_fn: Callable[[str | Path], dict[str, Any] | None],
    *,
    crs: Any,
    kind: CatalogKind,
    partition_by: Sequence[str],
    write_bbox: bool = True,
    batch_size: int = 10_000,
    n_workers: int = 1,
    max_open_writers: int = _DEFAULT_MAX_OPEN_WRITERS,
) -> DuckDBGeoCatalog:
    """Append new files to a Hive-partitioned GeoParquet archive.

    Only the new rows are extracted and written; existing shards are left
    untouched, so append work is ``O(N_new)`` plus the number of new
    partitions touched (and one read of the archive's ``filepath``
    column). The archive is created if it does not exist.

    Appending is idempotent: files whose ``filepath`` is already indexed
    in the archive (or repeated within ``filepaths``) are skipped, so
    re-running the same call — including after an interruption that left
    only some of the new shards moved in — never duplicates rows; it
    completes the append instead.

    Before any rows are written, the caller-supplied ``partition_by`` is
    validated against the archive's existing layout (the directory tree
    of ``key=value`` dirs). A mismatch raises `ValueError` rather than
    silently producing a mixed-layout archive that downstream readers
    can't reconstruct cleanly. A fresh archive (no existing shards)
    accepts the caller's ``partition_by`` as the source of truth.

    New shards are written at the archive's ``_schema_version``, so a
    pre-upgrade (v0) archive stays at a single version after an append
    and keeps opening: an archive is upgraded as a whole, never shard by
    shard.

    Args:
        archive: Hive-partitioned GeoParquet directory.
        filepaths: New source files to index.
        extract_fn: Picklable per-file extractor, same contract as
            `stream_build_duckdb`.
        crs: CRS to encode in the new shard metadata.
        kind: Catalog kind (loader dispatch).
        partition_by: Hive partition columns. ``"year"``, ``"month"``,
            and ``"day"`` are derived from each row's ``start_time``.
            Must match the existing archive's layout, if any.
        write_bbox: Emit the GeoParquet 1.1 ``bbox`` covering struct.
        batch_size: Rows per Arrow record batch.
        n_workers: Process-pool size for extraction.
        max_open_writers: Cap on concurrently open shard writers; see
            `write_partitioned_rows`.

    Returns:
        A `DuckDBGeoCatalog` opened on the updated archive.

    Raises:
        ValueError: ``partition_by`` differs from the archive's existing
            layout, or no input files yielded a row (and none were
            skipped as already indexed).
        CatalogSchemaError: The archive's shards are newer than the
            reader, or already at mixed versions.

    """
    from geocatalog._src.backends.duckdb_backend import (
        DuckDBGeoCatalog,
        _require_duckdb,
    )

    _require_duckdb()
    archive = Path(archive)
    if archive.exists() and not archive.is_dir():
        raise ValueError(f"append_files requires a partitioned directory: {archive}")
    if archive.parent != Path() and not archive.parent.exists():
        raise FileNotFoundError(
            f"append_files: parent dir does not exist: {archive.parent}"
        )
    requested = tuple(partition_by)
    existing = _detect_partition_layout(archive)
    if existing is not None and existing != requested:
        raise ValueError(
            f"append_files: partition_by={requested} does not match the "
            f"archive's existing layout {existing} at {archive}. Mixed "
            "Hive layouts produce shards that downstream readers cannot "
            "join cleanly — rebuild the archive at the new layout, or "
            "pass partition_by matching the existing one."
        )
    indexed = _indexed_filepaths(archive)
    # New shards take the archive's version, not the reader's: stamping
    # them newer would leave a mixed-version archive that no reader opens.
    schema_version = _archive_schema_version(archive)
    seen = set(indexed)
    skipped = 0

    def _new_inputs() -> Iterator[str | Path]:
        nonlocal skipped
        for fp in filepaths:
            key = str(fp)
            if key in seen:
                skipped += 1
                continue
            seen.add(key)
            yield fp

    def _new_rows() -> Iterator[dict[str, Any]]:
        # Dedup again on the extracted `filepath`: an extractor may
        # normalise the path it records (resolve it, add a scheme).
        nonlocal skipped
        recorded = set(indexed)
        for row in _iter_rows_parallel(_new_inputs(), extract_fn, n_workers=n_workers):
            fp = row.get("filepath")
            if fp is not None and fp in recorded:
                skipped += 1
                continue
            if fp is not None:
                recorded.add(fp)
            yield row

    rows_written = _write_partitioned_rows(
        _new_rows(),
        out_path=archive,
        crs=crs,
        kind=kind,
        partition_by=requested,
        schema_version=schema_version,
        write_bbox=write_bbox,
        batch_size=batch_size,
        replace=False,
        max_open_writers=max_open_writers,
    )
    if rows_written == 0:
        if skipped and indexed:
            log.info(
                "append_files: all {} input file(s) already indexed in {}",
                skipped,
                archive,
            )
            return DuckDBGeoCatalog.open(archive, kind=kind, crs=crs)
        raise ValueError("append_files: no files yielded a row")
    if skipped:
        log.info("append_files: skipped {} already-indexed file(s)", skipped)
    return DuckDBGeoCatalog.open(archive, kind=kind, crs=crs)