|
| 1 | +import dataclasses |
| 2 | +import logging |
| 3 | + |
| 4 | +import polars as pl |
| 5 | +import pyarrow.parquet as pq |
| 6 | +import sqlalchemy as sa |
| 7 | +from boltons.urlutils import URL |
| 8 | +from pyiceberg.catalog import Catalog, load_catalog |
| 9 | +from sqlalchemy_cratedb import insert_bulk |
| 10 | + |
| 11 | +from cratedb_toolkit.model import DatabaseAddress |
| 12 | + |
| 13 | +logger = logging.getLogger(__name__) |
| 14 | + |
| 15 | + |
| 16 | +CHUNK_SIZE = 75_000 |
| 17 | + |
| 18 | + |
| 19 | +@dataclasses.dataclass |
| 20 | +class IcebergAddress: |
| 21 | + path: str |
| 22 | + catalog: str |
| 23 | + table: str |
| 24 | + |
| 25 | + @classmethod |
| 26 | + def from_url(cls, url: str): |
| 27 | + iceberg_url = URL(url) |
| 28 | + if iceberg_url.host == ".": |
| 29 | + iceberg_url.path = iceberg_url.path.lstrip("/") |
| 30 | + return cls( |
| 31 | + path=iceberg_url.path, |
| 32 | + catalog=iceberg_url.query_params.get("catalog"), |
| 33 | + table=iceberg_url.query_params.get("table"), |
| 34 | + ) |
| 35 | + |
| 36 | + def load_catalog(self) -> Catalog: |
| 37 | + return load_catalog( |
| 38 | + self.catalog, |
| 39 | + **{ |
| 40 | + "type": "sql", |
| 41 | + "uri": f"sqlite:///{self.path}/pyiceberg_catalog.db", |
| 42 | + "warehouse": f"file://{self.path}", |
| 43 | + }, |
| 44 | + ) |
| 45 | + |
| 46 | + @property |
| 47 | + def identifier(self): |
| 48 | + return (self.catalog, self.table) |
| 49 | + |
| 50 | + def load_table(self) -> pl.LazyFrame: |
| 51 | + if self.catalog is not None: |
| 52 | + catalog = self.load_catalog() |
| 53 | + return catalog.load_table(self.identifier).to_polars() |
| 54 | + else: |
| 55 | + return pl.scan_iceberg(self.path) |
| 56 | + |
| 57 | + |
| 58 | +def from_iceberg(source_url, cratedb_url, progress: bool = False): |
| 59 | + """ |
| 60 | + Scan an Iceberg table from local filesystem or object store, and load into CrateDB. |
| 61 | + https://docs.pola.rs/api/python/stable/reference/api/polars.scan_iceberg.html |
| 62 | +
|
| 63 | + Synopsis |
| 64 | + -------- |
| 65 | + export CRATEDB_CLUSTER_URL=crate://crate@localhost:4200/testdrive/demo |
| 66 | + ctk load table "file+iceberg:var/lib/iceberg/default.db/taxi_dataset/metadata/00001-dc8e5ed2-dc29-4e39-b2e4-019e466af4c3.metadata.json" |
| 67 | + ctk load table "iceberg://./var/lib/iceberg/?catalog=default&table=taxi_dataset" |
| 68 | + """ |
| 69 | + |
| 70 | + iceberg_address = IcebergAddress.from_url(source_url) |
| 71 | + |
| 72 | + # Parse parameters. |
| 73 | + logger.info( |
| 74 | + f"Iceberg address: Path: {iceberg_address.path}, catalog: {iceberg_address.catalog}, table: {iceberg_address.table}" |
| 75 | + ) |
| 76 | + |
| 77 | + cratedb_address = DatabaseAddress.from_string(cratedb_url) |
| 78 | + cratedb_url, cratedb_table = cratedb_address.decode() |
| 79 | + if cratedb_table.table is None: |
| 80 | + raise ValueError("Table name is missing. Please adjust CrateDB database URL.") |
| 81 | + logger.info(f"Target address: {cratedb_address}") |
| 82 | + |
| 83 | + # Invoke copy operation. |
| 84 | + logger.info("Running Iceberg copy") |
| 85 | + engine = sa.create_engine(str(cratedb_url)) |
| 86 | + |
| 87 | + pl.Config.set_streaming_chunk_size(CHUNK_SIZE) |
| 88 | + table = iceberg_address.load_table() |
| 89 | + |
| 90 | + # This conversion to pandas is zero-copy, |
| 91 | + # so we can utilize their SQL utils for free. |
| 92 | + # https://github.com/pola-rs/polars/issues/7852 |
| 93 | + # Note: This code also uses the most efficient `insert_bulk` method with CrateDB. |
| 94 | + # https://cratedb.com/docs/sqlalchemy-cratedb/dataframe.html#efficient-insert-operations-with-pandas |
| 95 | + table.collect(streaming=True).to_pandas().to_sql( |
| 96 | + name=cratedb_table.table, |
| 97 | + schema=cratedb_table.schema, |
| 98 | + con=engine, |
| 99 | + if_exists="replace", |
| 100 | + index=False, |
| 101 | + chunksize=CHUNK_SIZE, |
| 102 | + method=insert_bulk, |
| 103 | + ) |
| 104 | + |
| 105 | + # Note: This was much slower. |
| 106 | + # table.to_polars().collect(streaming=True).write_database(table_name=table_address.fullname, connection=engine, if_table_exists="replace") |
| 107 | + |
| 108 | + |
| 109 | +def to_iceberg(source_url, target_url, progress: bool = False): |
| 110 | + """ |
| 111 | + Synopsis |
| 112 | + -------- |
| 113 | + export CRATEDB_CLUSTER_URL=crate://crate@localhost:4200/testdrive/demo |
| 114 | + ctk load table "iceberg://./var/lib/iceberg/?catalog=default&table=taxi_dataset" |
| 115 | + ctk save table "file+iceberg:var/lib/iceberg/default.db/taxi_dataset/metadata/00001-dc8e5ed2-dc29-4e39-b2e4-019e466af4c3.metadata.json" |
| 116 | + """ |
| 117 | + |
| 118 | + iceberg_address = IcebergAddress.from_url(target_url) |
| 119 | + catalog = iceberg_address.load_catalog() |
| 120 | + print("catalog:", catalog) |
| 121 | + |
| 122 | + # https://py.iceberg.apache.org/#write-a-pyarrow-dataframe |
| 123 | + df = pq.read_table("tmp/yellow_tripdata_2023-01.parquet") |
| 124 | + |
| 125 | + # Create a new Iceberg table. |
| 126 | + catalog.create_namespace_if_not_exists("default") |
| 127 | + table = catalog.create_table_if_not_exists( |
| 128 | + "default.taxi_dataset", |
| 129 | + schema=df.schema, |
| 130 | + ) |
| 131 | + |
| 132 | + # Append the dataframe to the table. |
| 133 | + table.append(df) |
| 134 | + len(table.scan().to_arrow()) |
0 commit comments