@@ -1334,6 +1334,67 @@ with table.manage_snapshots() as ms:
13341334 ms.create_branch(snapshot_id1, " Branch_A" ).create_tag(snapshot_id2, " tag789" )
13351335```
13361336
1337+ ## Table Maintenance
1338+
1339+ PyIceberg provides table maintenance operations through the ` table.maintenance ` API. This provides a clean interface for performing maintenance tasks like snapshot expiration.
1340+
1341+ ### Snapshot Expiration
1342+
1343+ Expire old snapshots to clean up table metadata and reduce storage costs:
1344+
1345+ ``` python
1346+ # Basic usage - expire a specific snapshot by ID
1347+ table.maintenance.expire_snapshots().expire_snapshot_by_id(12345 ).commit()
1348+
1349+ # Context manager usage (recommended for multiple operations)
1350+ with table.maintenance.expire_snapshots() as expire:
1351+ expire.expire_snapshot_by_id(12345 )
1352+ expire.expire_snapshot_by_id(67890 )
1353+ # Automatically commits when exiting the context
1354+
1355+ # Method chaining
1356+ table.maintenance.expire_snapshots().expire_snapshot_by_id(12345 ).commit()
1357+ ```
1358+
1359+ #### Real-world Example
1360+
1361+ ``` python
1362+ def cleanup_old_snapshots (table_name : str , snapshot_ids : list[int ]):
1363+ """ Remove specific snapshots from a table."""
1364+ catalog = load_catalog(" production" )
1365+ table = catalog.load_table(table_name)
1366+
1367+ # Use context manager for safe transaction handling
1368+ with table.maintenance.expire_snapshots() as expire:
1369+ for snapshot_id in snapshot_ids:
1370+ expire.expire_snapshot_by_id(snapshot_id)
1371+
1372+ print (f " Expired { len (snapshot_ids)} snapshots from { table_name} " )
1373+
1374+ # Usage
1375+ cleanup_old_snapshots(" analytics.user_events" , [12345 , 67890 , 11111 ])
1376+ ```
1377+
1378+ #### Transaction Semantics
1379+
1380+ The maintenance API leverages Iceberg's transaction system:
1381+
1382+ - ** Context Manager** : Automatically commits changes when exiting the ` with ` block
1383+ - ** Manual Commit** : Call ` .commit() ` explicitly to apply changes
1384+ - ** Rollback** : If an error occurs in a context manager, changes are automatically rolled back
1385+ - ** Atomic Operations** : All operations within a single transaction are applied atomically
1386+
1387+ <!-- prettier-ignore-start -->
1388+
1389+ !!! note "Future Maintenance Operations"
1390+ The maintenance API is designed to be extensible. Future versions may include additional maintenance operations such as:
1391+
1392+ * ` table.maintenance.compact_data() ` - Data file compaction
1393+ * ` table.maintenance.optimize_metadata() ` - Metadata optimization
1394+ * ` table.maintenance.rewrite_manifests() ` - Manifest rewriting
1395+
1396+ <!-- prettier-ignore-end -->
1397+
13371398## Views
13381399
13391400PyIceberg supports view operations.
0 commit comments