PyIceberg Documentation
repository·main·Indexed 22 days ago
https://github.com/apache/iceberg-pythonPyIceberg is a Python implementation of the Apache Iceberg table specification (version 0.11.0), providing programmatic access to Iceberg table metadata and underlying data. The library enables developers to manage namespaces, create and load tables, and perform data operations such as append, overwrite, upsert, and delete using Apache Arrow. It supports catalog-centric operations, time travel via snapshot IDs, and detailed table inspection of snapshots, partitions, and manifest entries.
What's inside pyiceberg
- PyIceberg is a Python library designed for programmatic access to Apache Iceberg table metadata and data. It provides a Python implementation of the Iceberg table spec, allowing developers to interact with Iceberg tables directly within Python environments.
What is the Expression DSL and how to use it
mainThe PyIceberg Expression DSL is a type-safe Domain Specific Language used to build complex row filter expressions. These expressions are passed to the
row_filterargument during a scan to filter data at the source. The DSL is composed of three main building blocks:- Terms: References to specific fields in your data (e.g.,
Reference("field_name")). - Predicates: Expressions that evaluate to a boolean value (e.g.,
EqualTo,In,IsNull). - Logical Operators: Operators used to combine predicates (e.g.,
And,Or,Not).
from pyiceberg.expressions import Reference # Create a reference to a field named "age" age_field = Reference("age")- Terms: References to specific fields in your data (e.g.,
Authenticate with the REST Catalog
mainPyIceberg provides a pluggable
authmechanism for REST catalogs. You select the method viaauth.typeand provide the corresponding configuration block.Supported types:
noop: No authentication.basic: Usesauth.basicwithusernameandpassword.oauth2: Usesauth.oauth2withclient_id,client_secret,token_url, etc.custom: Uses a customAuthManagerdefined byauth.impl.google: Uses Google service account credentials viaauth.google.credentials_path.entra: Uses Microsoft Entra ID (Azure AD) viaauth.entra(requirespip install pyiceberg[entra-auth]).
catalog: default: type: rest uri: http://rest-catalog/ws/ auth: type: oauth2 oauth2: client_id: my-client-id client_secret: my-client-secret token_url: https://auth.example.com/oauth/token scope: readUse SimpleLocationProvider for standard file paths
mainThe
SimpleLocationProvideris the default provider in PyIceberg. It generates paths prefixed by{location}/data/, where{location}is retrieved from the table metadata.- Non-partitioned tables: Files are placed directly under the data prefix (e.g.,
s3://bucket/ns/table/data/file.parquet). - Partitioned tables: Uses Hive-style partition paths, where partition keys and values are included as subdirectories (e.g.,
s3://bucket/ns/table/data/category=orders/file.parquet).
- Non-partitioned tables: Files are placed directly under the data prefix (e.g.,
Understand and configure FileIO in PyIceberg
mainPyIceberg uses a pluggable
FileIOmodule to handle reading, writing, and deleting files. By default, PyIceberg automatically selects aFileIOimplementation based on the URI scheme (e.g.,s3://,gs://).Default Mappings:
s3://,s3a://,s3n://:PyArrowFileIOorFsspecFileIO(whichever is installed first)gs://:PyArrowFileIOfile://:PyArrowFileIOhdfs://:PyArrowFileIOabfs://,abfss://:FsspecFileIOoss://:PyArrowFileIOhf://:FsspecFileIO
You can explicitly set the implementation using the
py-io-implconfiguration key. If the specified implementation cannot be loaded, PyIceberg will raise an error.py-io-impl: pyiceberg.io.fsspec.FsspecFileIOLoad an Iceberg table
mainThere are two primary ways to load a table:
1. Catalog Table (Recommended)
Loading via the catalog allows for both read and write operations. Use the identifier string or a tuple (useful if the namespace contains dots).
table = catalog.load_table("docs_example.bids") # Or using tuple syntax: table = catalog.load_table(("docs_example", "bids"))2. Static Table (Read-Only)
If you do not have access to a catalog, you can load a table directly from its
metadata.jsonfile. This method is read-only.from pyiceberg.table import StaticTable # From specific metadata file static_table = StaticTable.from_metadata("s3://path/to/metadata.json") # From table root (resolves latest metadata.json via version-hint.text) static_table = StaticTable.from_metadata("s3://path/to/table_root")# Catalog loading (Read/Write) table = catalog.load_table("docs_example.bids") # Static loading (Read-Only) from pyiceberg.table import StaticTable static_table = StaticTable.from_metadata("s3://warehouse/wh/nyc.db/taxis")Comparison and Logical Operations in row filters
mainYou can perform various comparisons and combine them using logical operators in your row filter strings.
Comparison Operators
- Basic:
=,!=,>,>=,<,<=. - Aliases:
==is an alias for=, and<>is an alias for!=. - NULL Checks:
IS NULLandIS NOT NULL. - NaN Checks (for floating-point):
IS NANandIS NOT NAN. - Set Membership:
IN (...)andNOT IN (...). - Range:
BETWEEN <val1> AND <val2>(inclusive). - Pattern Matching:
LIKE 'pattern%'andNOT LIKE 'pattern%'.
Logical Operators
ANDORNOT- Use parentheses
()to group operations and ensure correct precedence.
Note on Precedence: The order of operations is
NOT>AND>OR.-- Combining multiple conditions (status = 'pending' OR status = 'processing') AND NOT (priority = 'low')- Basic:
How LocationProviders manage file paths
mainApache Iceberg uses a
LocationProviderto manage file paths for a table's data files and metadata files. PyIceberg'sLocationProvideris pluggable, allowing you to customize how file paths are generated for specific use cases.Key concepts:
- Default Behavior: PyIceberg uses
SimpleLocationProviderby default. - Customization via Properties: You can customize data and metadata locations using the
write.data.pathandwrite.metadata.pathtable properties. - Granular Control: You can override the
new_data_locationandnew_metadata_locationmethods of aLocationProviderto implement custom path generation logic.
- Default Behavior: PyIceberg uses
Manage PyIceberg dependencies and lock files
mainPyIceberg uses
uv.lockto ensure cross-platform dependency consistency.- Automatic updates: The
uv-pre-commithook automatically updatesuv.lockwhenpyproject.tomlchanges. If the lockfile is updated, you must add the newuv.lockto your commit. - Manual updates: To manually synchronize the lockfile after editing
pyproject.toml, runuv lock. - CI Enforcement: The CI system validates that
uv.lockis in sync withpyproject.toml. Mismatches will cause CI builds to fail.
uv lock- Automatic updates: The
Configure your IDE for PyIceberg development
mainAfter running
make install, you must point your IDE to the Python interpreter located at.venv/bin/python.VS Code:
- Press
Cmd/Ctrl+Shift+P. - Select
Python: Select Interpreter. - Choose
.venv/bin/python.
IntelliJ IDEA:
- Go to
File->Project Structure(⌘;). - Navigate to
Platform Settings->SDKs. - Select
Add Python SDK->Virtualenv Environment->Existing environment. - Point to
.venv/bin/python.
- Press
Create and push a signed release tag
mainOnce on the correct branch (
mainfor major/minor, or the version-specific branch for patches), create a signed GPG tag for the Release Candidate (RC). ReplaceVERSIONandRCwith your target values.export VERSION=0.7.0 export RC=1 export VERSION_WITH_RC=${VERSION}rc${RC} export GIT_TAG=pyiceberg-${VERSION_WITH_RC} git tag -s ${GIT_TAG} -m "PyIceberg ${VERSION_WITH_RC}" git push git@github.com:apache/iceberg-python.git ${GIT_TAG}Stream large datasets using RecordBatchReader
mainTo avoid loading entire datasets into memory,
tbl.append()andtbl.overwrite()accept apyarrow.RecordBatchReader. PyIceberg will consume the reader and microbatch it into Parquet files of approximatelywrite.target-file-size-bytes(default 512 MiB).Note: Streaming writes are currently only supported on unpartitioned tables. For partitioned tables, you must materialize the reader as a
pa.Tablefirst.# reader is a pyarrow.RecordBatchReader reader = pa.RecordBatchReader.from_batches(schema, batch_iter) tbl.append(reader)