Python API

Import the public API from ogc_records_parquet. The reference below is generated from its exported objects, signatures, and Google-style docstrings.

For column types and metadata contracts, see the storage format. See errors and limitations for failure timing and migration for API changes.

Store PySTAC OGCRecord objects alongside Arrow and GeoParquet query projections.

Use records_to_arrow() and to_parquet() to write records, then read_parquet() to reconstruct them. arrow_to_records() reconstructs records from an in-memory table or stream. Readers use the preserved JSON payload, independently of query columns and storage-only collection membership.

Record parsing and serialization belong to pystac-ext-ogc-record. This package checks storage compatibility and projection safety; OGC profile validation and query execution remain the caller's responsibility.

records_to_arrow(records, *, schema=None, batch_size=1024, collections=None, collection_ids=None)

Project Records into a lazy Arrow stream with PySTAC-serialized payloads.

Record and membership iterables are consumed only when the reader is advanced. Records are serialized at that time, so changes made before consumption are visible. Collection descriptions are instead validated and serialized immediately. The input records and descriptions are not modified.

Each row retains the document produced by OGCRecord.to_dict(transform_hrefs=False), including self links and unmodified relative hrefs. PySTAC normalization applies before storage; original JSON bytes and pre-normalization timestamp precision are not preserved. Null geometry and records without STAC temporal fields are supported. Non-null geometry must already use CRS84 longitude/latitude.

Parameters:
  • records (Iterable[OGCRecord]) –

    One-pass iterable of OGCRecord objects in source order. Serialization and conversion happen during consumption; duplicate IDs are allowed.

  • schema (Schema | None, default: None ) –

    Query projection fields. Dot-separated names select nested object keys; this is not an OGC API validation schema. None selects default_schema(); an empty schema selects no query fields. Missing paths project as null, which is rejected for non-nullable fields. Paths cannot traverse lists or escape dots in keys. Reserved columns geometry, bbox, __record_json, and __collection_id are always added and cannot be named as projections. Unprojected members remain in the payload. Custom schema metadata is retained except for the library-owned geo and ogc-records-parquet keys.

  • batch_size (int, default: 1024 ) –

    Maximum number of records converted per batch, greater than zero. This is a row count, not a bound on memory use.

  • collections (Mapping[str, object] | None, default: None ) –

    Catalog JSON objects indexed by string collection IDs. Stored as a metadata snapshot before this function returns. None omits descriptions; an empty mapping stores an empty descriptions object. Catalog schemas, description IDs, and membership references are not semantically validated.

  • collection_ids (Iterable[str | None] | None, default: None ) –

    One-pass memberships aligned with Records, including nulls for unknown membership. Omission stores null for every row. Values must be non-empty strings or null, and the iterable must have exactly as many values as records. Membership is independent of original JSON fields and is not inferred from the supplied descriptions.

Returns:
  • RecordBatchReader –

    A single-pass reader with a fixed schema, even for empty input. Call

  • RecordBatchReader –

    read_all() to materialize a reusable table, or pass the reader directly

  • RecordBatchReader –

    to to_parquet(). New streams use storage format 1.1.0.

Raises:
  • ValueError –

    Immediately if the batch size, projection names, or collection JSON is invalid. During consumption if a record contains non-JSON or non-finite values, geometry cannot be encoded, a projection requires an unsafe cast or violates nullability, or memberships are invalid or differ in length. PySTAC may also reject malformed timestamps.

  • TypeError –

    During consumption if PySTAC cannot serialize a metadata timestamp of the supplied Python type.

Examples:

Create a stream and inspect a default query column:

>>> from pystac.extensions.ogc_record import OGCRecord
>>> from ogc_records_parquet import records_to_arrow
>>> record = OGCRecord(id="workflow", properties={"title": "Flood mapping"})
>>> table = records_to_arrow([record], batch_size=1).read_all()
>>> table["properties.title"].to_pylist()
['Flood mapping']
Source code in src/ogc_records_parquet/arrow.py
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def records_to_arrow(
    records: Iterable[OGCRecord],
    *,
    schema: pa.Schema | None = None,
    batch_size: int = 1024,
    collections: Mapping[str, object] | None = None,
    collection_ids: Iterable[str | None] | None = None,
) -> pa.RecordBatchReader:
    """Project Records into a lazy Arrow stream with PySTAC-serialized payloads.

    Record and membership iterables are consumed only when the reader is
    advanced. Records are serialized at that time, so changes made before
    consumption are visible. Collection descriptions are instead validated and
    serialized immediately. The input records and descriptions are not modified.

    Each row retains the document produced by
    `OGCRecord.to_dict(transform_hrefs=False)`, including self links and
    unmodified relative hrefs. PySTAC normalization applies before storage;
    original JSON bytes and pre-normalization timestamp precision are not
    preserved. Null geometry and records without STAC temporal fields are
    supported. Non-null geometry must already use CRS84 longitude/latitude.

    Args:
        records: One-pass iterable of OGCRecord objects in source order. Serialization
            and conversion happen during consumption; duplicate IDs are allowed.
        schema: Query projection fields. Dot-separated names select nested object
            keys; this is not an OGC API validation schema. `None` selects
            `default_schema()`; an empty schema selects no query fields. Missing
            paths project as null, which is rejected for non-nullable fields.
            Paths cannot traverse lists or escape dots in keys. Reserved columns
            `geometry`, `bbox`, `__record_json`, and `__collection_id` are always
            added and cannot be named as projections. Unprojected members remain
            in the payload. Custom schema metadata is retained except for the
            library-owned `geo` and `ogc-records-parquet` keys.
        batch_size: Maximum number of records converted per batch, greater than zero.
            This is a row count, not a bound on memory use.
        collections: Catalog JSON objects indexed by string collection IDs. Stored
            as a metadata snapshot before this function returns. `None` omits
            descriptions; an empty mapping stores an empty descriptions object.
            Catalog schemas, description IDs, and membership references are not
            semantically validated.
        collection_ids: One-pass memberships aligned with Records, including nulls
            for unknown membership. Omission stores null for every row. Values must
            be non-empty strings or null, and the iterable must have exactly as many
            values as records. Membership is independent of original JSON fields
            and is not inferred from the supplied descriptions.

    Returns:
        A single-pass reader with a fixed schema, even for empty input. Call
        `read_all()` to materialize a reusable table, or pass the reader directly
        to `to_parquet()`. New streams use storage format `1.1.0`.

    Raises:
        ValueError: Immediately if the batch size, projection names, or collection
            JSON is invalid. During consumption if a record contains non-JSON or
            non-finite values, geometry cannot be encoded, a projection requires
            an unsafe cast or violates nullability, or memberships are invalid
            or differ in length. PySTAC may also reject malformed timestamps.
        TypeError: During consumption if PySTAC cannot serialize a metadata
            timestamp of the supplied Python type.

    Examples:
        Create a stream and inspect a default query column:

        >>> from pystac.extensions.ogc_record import OGCRecord
        >>> from ogc_records_parquet import records_to_arrow
        >>> record = OGCRecord(id="workflow", properties={"title": "Flood mapping"})
        >>> table = records_to_arrow([record], batch_size=1).read_all()
        >>> table["properties.title"].to_pylist()
        ['Flood mapping']
    """
    if batch_size < 1:
        raise ValueError("batch_size must be greater than zero")
    projections = default_schema() if schema is None else schema
    validate_schema(projections)
    catalogs = None if collections is None else require_json_object(dict(collections))
    if catalogs is not None and any(not isinstance(catalog, dict) for catalog in catalogs.values()):
        raise ValueError("Collection metadata must map IDs to catalog JSON objects")
    output_schema = storage_schema(projections, catalogs)
    batches = record_batches(records, projections, output_schema, batch_size, collection_ids)
    return pa.RecordBatchReader.from_batches(output_schema, batches)

arrow_to_records(table)

Decode OGCRecord objects from a library-produced Arrow stream.

Stored payloads are authoritative: editing query or membership columns does not edit the exported records. Decoding follows OGCRecord.from_dict(), including its normalization rules for legacy payloads. No OGC profile validation is performed.

Validation and decoding begin on iteration, not when this function is called. A supplied reader is consumed from its current position. A table is not modified. Storage formats 1.0.0 and 1.1.0 are accepted.

Parameters:
  • table (Table | RecordBatchReader) –

    Table or stream retaining valid ogc-records-parquet schema metadata and __record_json. Payload columns may have Arrow string or large-string type, but every row must contain non-null JSON text. Geometry, membership, and query columns may be omitted.

Yields:
  • OGCRecord –

    Independently decoded OGCRecord objects in row order. Changes to a yielded

  • OGCRecord –

    record do not modify the input or other yielded records. Empty input

  • OGCRecord –

    with valid metadata and payload schema yields no records.

Raises:
  • ValueError –

    During iteration if format metadata or payload columns are missing or incompatible, a payload is null or is not a JSON object, JSON contains duplicate keys or non-finite numbers, or PySTAC rejects the Record document. JSON syntax errors are json.JSONDecodeError, a subclass of ValueError.

  • TypeError –

    If PySTAC cannot parse a metadata timestamp's Python type.

Examples:

Reconstruct from only the payload column, retaining schema metadata:

>>> from pystac.extensions.ogc_record import OGCRecord
>>> from ogc_records_parquet import arrow_to_records, records_to_arrow
>>> table = records_to_arrow([OGCRecord(id="workflow")]).read_all()
>>> restored = next(arrow_to_records(table.select(["__record_json"])))
>>> restored.id
'workflow'
Source code in src/ogc_records_parquet/arrow.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def arrow_to_records(table: pa.Table | pa.RecordBatchReader) -> Iterator[OGCRecord]:
    """Decode OGCRecord objects from a library-produced Arrow stream.

    Stored payloads are authoritative: editing query or membership columns does
    not edit the exported records. Decoding follows `OGCRecord.from_dict()`,
    including its normalization rules for legacy payloads. No OGC profile
    validation is performed.

    Validation and decoding begin on iteration, not when this function is called.
    A supplied reader is consumed from its current position. A table is not
    modified. Storage formats `1.0.0` and `1.1.0` are accepted.

    Args:
        table: Table or stream retaining valid `ogc-records-parquet` schema
            metadata and `__record_json`. Payload columns may have Arrow string
            or large-string type, but every row must contain non-null JSON text.
            Geometry, membership, and query columns may be omitted.

    Yields:
        Independently decoded OGCRecord objects in row order. Changes to a yielded
        record do not modify the input or other yielded records. Empty input
        with valid metadata and payload schema yields no records.

    Raises:
        ValueError: During iteration if format metadata or payload columns are
            missing or incompatible, a payload is null or is not a JSON object,
            JSON contains duplicate keys or non-finite numbers, or PySTAC rejects
            the Record document. JSON syntax errors are `json.JSONDecodeError`,
            a subclass of `ValueError`.
        TypeError: If PySTAC cannot parse a metadata timestamp's Python type.

    Examples:
        Reconstruct from only the payload column, retaining schema metadata:

        >>> from pystac.extensions.ogc_record import OGCRecord
        >>> from ogc_records_parquet import arrow_to_records, records_to_arrow
        >>> table = records_to_arrow([OGCRecord(id="workflow")]).read_all()
        >>> restored = next(arrow_to_records(table.select(["__record_json"])))
        >>> restored.id
        'workflow'
    """
    read_format_metadata(table.schema)
    if PAYLOAD_COLUMN not in table.schema.names:
        raise ValueError("Missing original Record JSON payload column")
    payload_type = table.schema.field(PAYLOAD_COLUMN).type
    if not (pa.types.is_string(payload_type) or pa.types.is_large_string(payload_type)):
        raise ValueError("Original Record JSON payload column must contain strings")
    batches = table.to_batches() if isinstance(table, pa.Table) else table
    for batch in batches:
        for payload in batch.column(PAYLOAD_COLUMN):
            encoded = payload.as_py()
            if not isinstance(encoded, str):
                raise ValueError("Original Record JSON payload must be non-null")
            yield OGCRecord.from_dict(loads_object(encoded))

to_parquet(table, path, *, compression='zstd')

Write a library-produced Arrow stream to a local GeoParquet file.

Consumes batches in source order and replaces an existing destination only after successful conversion and writing. A failed conversion leaves the destination unchanged. Temporary data is created in the destination directory. Remote/object-storage paths are not supported.

Schema metadata and the supplied storage format version are retained; writing a valid legacy stream does not upgrade it. Storage structure is checked, but arbitrary input tables do not receive per-payload Record or OGC schema validation.

Parameters:
  • table (Table | RecordBatchReader) –

    A table or unconsumed reader produced by records_to_arrow(), or an equivalent table retaining the required storage columns and metadata. A reader is consumed from its current position; a table can be reused. Empty input still creates a file with its schema.

  • path (str | Path) –

    Local destination file. Its parent directory must already exist. An existing file is replaced on success.

  • compression (Literal['gzip', 'brotli', 'lz4', 'zstd', 'snappy', 'none'], default: 'zstd' ) –

    Parquet codec, defaulting to "zstd". Use "none" for uncompressed output. Codec availability depends on the PyArrow build.

Raises:
  • ValueError –

    If format metadata or required storage columns are invalid, or if lazy record conversion raises a validation error.

  • OSError –

    If the destination directory is absent, inaccessible, or a file operation fails.

Examples:

Write a local file and read its records:

>>> from pathlib import Path
>>> from tempfile import TemporaryDirectory
>>> from pystac.extensions.ogc_record import OGCRecord
>>> from ogc_records_parquet import read_parquet, records_to_arrow, to_parquet
>>> with TemporaryDirectory() as directory:
...     path = Path(directory) / "records.parquet"
...     to_parquet(records_to_arrow([OGCRecord(id="workflow")]), path)
...     identifiers = [record.id for record in read_parquet(path)]
>>> identifiers
['workflow']
Source code in src/ogc_records_parquet/parquet.py
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def to_parquet(
    table: pa.Table | pa.RecordBatchReader,
    path: str | Path,
    *,
    compression: Literal["gzip", "brotli", "lz4", "zstd", "snappy", "none"] = "zstd",
) -> None:
    """Write a library-produced Arrow stream to a local GeoParquet file.

    Consumes batches in source order and replaces an existing destination only
    after successful conversion and writing. A failed conversion leaves the
    destination unchanged. Temporary data is created in the destination directory.
    Remote/object-storage paths are not supported.

    Schema metadata and the supplied storage format version are retained;
    writing a valid legacy stream does not upgrade it. Storage structure is
    checked, but arbitrary input tables do not receive per-payload Record or
    OGC schema validation.

    Args:
        table: A table or unconsumed reader produced by `records_to_arrow()`,
            or an equivalent table retaining the required storage columns and
            metadata. A reader is consumed from its current position; a table
            can be reused. Empty input still creates a file with its schema.
        path: Local destination file. Its parent directory must already exist.
            An existing file is replaced on success.
        compression: Parquet codec, defaulting to `"zstd"`. Use `"none"` for
            uncompressed output. Codec availability depends on the PyArrow build.

    Raises:
        ValueError: If format metadata or required storage columns are invalid,
            or if lazy record conversion raises a validation error.
        OSError: If the destination directory is absent, inaccessible, or a file
            operation fails.

    Examples:
        Write a local file and read its records:

        >>> from pathlib import Path
        >>> from tempfile import TemporaryDirectory
        >>> from pystac.extensions.ogc_record import OGCRecord
        >>> from ogc_records_parquet import read_parquet, records_to_arrow, to_parquet
        >>> with TemporaryDirectory() as directory:
        ...     path = Path(directory) / "records.parquet"
        ...     to_parquet(records_to_arrow([OGCRecord(id="workflow")]), path)
        ...     identifiers = [record.id for record in read_parquet(path)]
        >>> identifiers
        ['workflow']
    """
    validate_storage_schema(table.schema)
    destination = Path(path)
    with tempfile.TemporaryDirectory(
        prefix=".records-parquet-", dir=destination.parent
    ) as directory:
        staging = Path(directory) / "records.parquet"
        batches = table.to_batches() if isinstance(table, pa.Table) else table
        with pq.ParquetWriter(staging, table.schema, compression=compression) as writer:
            for batch in batches:
                writer.write_batch(batch)
        staging.replace(destination)

read_parquet(path, *, batch_size=1024)

Read OGCRecord objects in file order from GeoParquet.

Opens the file and validates its format when iteration begins. Records are reconstructed from their stored JSON payloads, not from query projections. Storage formats 1.0.0 and 1.1.0 are accepted; current PySTAC parsing and normalization apply to both.

The file remains open while the iterator is active. Exhaust the iterator or call its close() method when abandoning iteration early.

Parameters:
  • path (str | Path) –

    Parquet file produced by this library, retaining format metadata, payloads, and the membership schema required by its format version.

  • batch_size (int, default: 1024 ) –

    Maximum rows per decoded batch, greater than zero. It does not limit the total number of yielded records or their size.

Yields:
  • OGCRecord –

    Independent OGCRecord objects in file order. Empty files yield no records.

  • OGCRecord –

    Storage-only memberships are available separately through

  • OGCRecord –

    read_collection_ids(); they are not injected into the records.

Raises:
  • ValueError –

    During iteration if the batch size is invalid, format metadata or membership schema is missing or incompatible, or a stored payload fails JSON or Record validation.

  • TypeError –

    If PySTAC cannot parse a metadata timestamp's Python type.

  • OSError –

    If the file cannot be opened or read.

Source code in src/ogc_records_parquet/parquet.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
def read_parquet(path: str | Path, *, batch_size: int = 1024) -> Iterator[OGCRecord]:
    """Read OGCRecord objects in file order from GeoParquet.

    Opens the file and validates its format when iteration begins. Records are
    reconstructed from their stored JSON payloads, not from query projections.
    Storage formats `1.0.0` and `1.1.0` are accepted; current PySTAC parsing
    and normalization apply to both.

    The file remains open while the iterator is active. Exhaust the iterator or
    call its `close()` method when abandoning iteration early.

    Args:
        path: Parquet file produced by this library, retaining format metadata,
            payloads, and the membership schema required by its format version.
        batch_size: Maximum rows per decoded batch, greater than zero. It does
            not limit the total number of yielded records or their size.

    Yields:
        Independent OGCRecord objects in file order. Empty files yield no records.
        Storage-only memberships are available separately through
        `read_collection_ids()`; they are not injected into the records.

    Raises:
        ValueError: During iteration if the batch size is invalid, format metadata
            or membership schema is missing or incompatible, or a stored payload
            fails JSON or Record validation.
        TypeError: If PySTAC cannot parse a metadata timestamp's Python type.
        OSError: If the file cannot be opened or read.
    """
    if batch_size < 1:
        raise ValueError("batch_size must be greater than zero")
    with pq.ParquetFile(path) as parquet_file:
        schema = parquet_file.schema_arrow
        validate_membership_schema(schema)
        reader = pa.RecordBatchReader.from_batches(
            schema, parquet_file.iter_batches(batch_size=batch_size)
        )
        yield from arrow_to_records(reader)

read_metadata(path)

Read the library's format metadata without decoding Record payloads.

Reads the Parquet schema and returns its ogc-records-parquet metadata. It does not return the complete Arrow or GeoParquet metadata, validate storage column types, or inspect row membership values.

Parameters:
  • path (str | Path) –

    Parquet file containing supported library format metadata.

Returns:
  • JSONObject –

    A newly decoded object containing version, payload_column, and,

  • JSONObject –

    for format 1.1.0, membership_column. Library-created metadata also

  • JSONObject –

    includes writer_version, projections, and optional collections.

  • JSONObject –

    Modifying this object does not change the file.

Raises:
  • ValueError –

    If metadata is missing, malformed JSON, uses an unsupported version, or declares unsupported payload or membership column names.

  • OSError –

    If the file cannot be opened or its schema cannot be read.

Source code in src/ogc_records_parquet/parquet.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
def read_metadata(path: str | Path) -> JSONObject:
    """Read the library's format metadata without decoding Record payloads.

    Reads the Parquet schema and returns its `ogc-records-parquet` metadata.
    It does not return the complete Arrow or GeoParquet metadata, validate
    storage column types, or inspect row membership values.

    Args:
        path: Parquet file containing supported library format metadata.

    Returns:
        A newly decoded object containing `version`, `payload_column`, and,
        for format `1.1.0`, `membership_column`. Library-created metadata also
        includes `writer_version`, `projections`, and optional `collections`.
        Modifying this object does not change the file.

    Raises:
        ValueError: If metadata is missing, malformed JSON, uses an unsupported
            version, or declares unsupported payload or membership column names.
        OSError: If the file cannot be opened or its schema cannot be read.
    """
    return read_format_metadata(pq.read_schema(path))

read_collections(path)

Read stored collection descriptions independently of row membership.

Only schema metadata is read; Record payloads are not decoded. Descriptions neither assign membership nor validate the IDs in __collection_id.

Parameters:
  • path (str | Path) –

    Parquet file containing supported library format metadata.

Returns:
  • JSONObject –

    A newly decoded mapping of catalog descriptions keyed by collection ID.

  • JSONObject –

    Returns an empty mapping when descriptions are absent or explicitly

  • JSONObject –

    empty. Catalog contents and the relationship between mapping keys and

  • JSONObject –

    catalog IDs are not semantically validated. Changes do not alter the file.

Raises:
  • ValueError –

    If format metadata is missing or invalid, or the stored collections value is not a JSON object.

  • OSError –

    If the file cannot be opened or its schema cannot be read.

Source code in src/ogc_records_parquet/parquet.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
def read_collections(path: str | Path) -> JSONObject:
    """Read stored collection descriptions independently of row membership.

    Only schema metadata is read; Record payloads are not decoded. Descriptions
    neither assign membership nor validate the IDs in `__collection_id`.

    Args:
        path: Parquet file containing supported library format metadata.

    Returns:
        A newly decoded mapping of catalog descriptions keyed by collection ID.
        Returns an empty mapping when descriptions are absent or explicitly
        empty. Catalog contents and the relationship between mapping keys and
        catalog IDs are not semantically validated. Changes do not alter the file.

    Raises:
        ValueError: If format metadata is missing or invalid, or the stored
            `collections` value is not a JSON object.
        OSError: If the file cannot be opened or its schema cannot be read.
    """
    collections = read_metadata(path).get("collections", {})
    if not isinstance(collections, dict):
        raise ValueError("Stored collections metadata must be an object")
    return collections

read_collection_ids(path, *, batch_size=1024)

Read storage-only memberships in file row order, independently of Record JSON.

File access and validation begin on iteration. Format 1.1.0 reads only the membership column; Record payloads are not decoded or validated. Format 1.0.0 returns unknown membership for every row, even if descriptions or a similarly named column exist.

The file remains open until the iterator is exhausted or closed. Pair its results with records only when reading identical rows in identical order. Duplicate record IDs do not affect membership.

Parameters:
  • path (str | Path) –

    A library-produced Parquet file in format 1.0.0 or 1.1.0.

  • batch_size (int, default: 1024 ) –

    Maximum membership rows read per batch, greater than zero. It does not limit the total number of yielded memberships.

Yields:
  • str | None –

    One non-empty collection ID or None per row. IDs need not have a

  • str | None –

    corresponding stored description. Empty files yield no values.

Raises:
  • ValueError –

    During iteration if batch size or format metadata is invalid, format 1.1.0 lacks a single nullable string membership column, or a stored membership is neither a non-empty string nor null.

  • OSError –

    If the file cannot be opened or read.

Source code in src/ogc_records_parquet/parquet.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
def read_collection_ids(path: str | Path, *, batch_size: int = 1024) -> Iterator[str | None]:
    """Read storage-only memberships in file row order, independently of Record JSON.

    File access and validation begin on iteration. Format `1.1.0` reads only
    the membership column; Record payloads are not decoded or validated. Format
    `1.0.0` returns unknown membership for every row, even if descriptions or
    a similarly named column exist.

    The file remains open until the iterator is exhausted or closed. Pair its
    results with records only when reading identical rows in identical order.
    Duplicate record IDs do not affect membership.

    Args:
        path: A library-produced Parquet file in format 1.0.0 or 1.1.0.
        batch_size: Maximum membership rows read per batch, greater than zero.
            It does not limit the total number of yielded memberships.

    Yields:
        One non-empty collection ID or `None` per row. IDs need not have a
        corresponding stored description. Empty files yield no values.

    Raises:
        ValueError: During iteration if batch size or format metadata is invalid,
            format `1.1.0` lacks a single nullable string membership column, or
            a stored membership is neither a non-empty string nor null.
        OSError: If the file cannot be opened or read.
    """
    if batch_size < 1:
        raise ValueError("batch_size must be greater than zero")
    with pq.ParquetFile(path) as parquet_file:
        validate_membership_schema(parquet_file.schema_arrow)
        metadata = read_format_metadata(parquet_file.schema_arrow)
        if metadata["version"] == "1.0.0":
            yield from (None for _ in range(parquet_file.metadata.num_rows))
            return
        for batch in parquet_file.iter_batches(batch_size=batch_size, columns=[MEMBERSHIP_COLUMN]):
            for value in batch.column(MEMBERSHIP_COLUMN):
                membership = value.as_py()
                if membership is not None and (not isinstance(membership, str) or membership == ""):
                    raise ValueError("Collection membership must be a non-empty string or null")
                yield membership

default_schema()

Return stable query projections of common Records members.

All fields are nullable. The projection names are literal Arrow column names and dot-separated lookup paths in serialized Record objects.

Field Arrow type
id string
type string
properties.type string
properties.title string
properties.description string
properties.created string
properties.updated string
properties.keywords list of string

Integer identifiers are converted to strings only in the query column. Timestamp columns contain PySTAC's serialized strings, including its normalization. Original serialized values remain authoritative in the payload. This schema does not validate OGC conformance.

Returns:
  • Schema –

    A new query schema without storage columns or format metadata.

  • Schema –

    records_to_arrow() adds those when creating a stream. Pass a different

  • Schema –

    schema to that function to select other fields or Arrow types.

Examples:

>>> from ogc_records_parquet import default_schema
>>> schema = default_schema()
>>> schema.field("properties.title").nullable
True
>>> "__record_json" in schema.names
False
Source code in src/ogc_records_parquet/_schema.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
def default_schema() -> pa.Schema:
    """Return stable query projections of common Records members.

    All fields are nullable. The projection names are literal Arrow column names
    and dot-separated lookup paths in serialized Record objects.

    | Field | Arrow type |
    | --- | --- |
    | `id` | string |
    | `type` | string |
    | `properties.type` | string |
    | `properties.title` | string |
    | `properties.description` | string |
    | `properties.created` | string |
    | `properties.updated` | string |
    | `properties.keywords` | list of string |

    Integer identifiers are converted to strings only in the query column.
    Timestamp columns contain PySTAC's serialized strings, including its
    normalization. Original serialized values remain authoritative in the
    payload. This schema does not validate OGC conformance.

    Returns:
        A new query schema without storage columns or format metadata.
        `records_to_arrow()` adds those when creating a stream. Pass a different
        schema to that function to select other fields or Arrow types.

    Examples:
        >>> from ogc_records_parquet import default_schema
        >>> schema = default_schema()
        >>> schema.field("properties.title").nullable
        True
        >>> "__record_json" in schema.names
        False
    """
    return pa.schema(
        [
            pa.field("id", pa.string()),
            pa.field("type", pa.string()),
            pa.field("properties.type", pa.string()),
            pa.field("properties.title", pa.string()),
            pa.field("properties.description", pa.string()),
            pa.field("properties.created", pa.string()),
            pa.field("properties.updated", pa.string()),
            pa.field("properties.keywords", pa.list_(pa.string())),
        ]
    )

JSONValue = bool | int | float | str | list['JSONValue'] | dict[str, 'JSONValue'] | None module-attribute

Recursive type alias for JSON scalars, lists, objects, and null.

This alias describes generic JSON values, not an OGC Record schema. Storage validation additionally rejects non-finite floats; annotations alone cannot express that constraint. Tuples and non-string object keys are not accepted.

JSONObject = dict[str, JSONValue] module-attribute

Type alias for a JSON object with string keys and recursively JSON-compatible values.

Used for decoded file metadata and catalog descriptions. It is not a Record model or a validation function; use OGCRecord for record manipulation.

__version__ = '0.1.0' module-attribute

Package version recorded as writer_version when a storage schema is created.

This version is independent of the OGC Records storage format and GeoParquet metadata versions. Rewriting an existing Arrow schema preserves its metadata.