File size: 2,951 Bytes
1cd137c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 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 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 120 121 122 123 124 125 126 127 128 129 130 131 132 | import dlt
import duckdb
from reference_db.adapters.base import RetailerAdapter
DB_PATH = "compliments_reference_db.duckdb"
def get_existing_product_ids() -> set[tuple[str, str]]:
"""Return product identities already stored in the raw layer."""
connection = duckdb.connect(DB_PATH)
try:
rows = connection.sql(
"""
SELECT retailer, retailer_product_id
FROM raw.raw_products
"""
).fetchall()
return set(rows)
except duckdb.CatalogException:
return set()
finally:
connection.close()
def get_existing_nutrition_ids() -> set[str]:
"""Return nutrition product IDs already stored."""
connection = duckdb.connect(DB_PATH)
try:
rows = connection.sql(
"""
SELECT retailer_product_id
FROM raw.raw_nutrition
"""
).fetchall()
return {row[0] for row in rows}
except duckdb.CatalogException:
return set()
finally:
connection.close()
def create_products_resource(adapter: RetailerAdapter):
@dlt.resource(
name="raw_products",
write_disposition="append",
primary_key=["retailer", "retailer_product_id"],
)
def products():
existing_ids = get_existing_product_ids()
new_count = 0
for row in adapter.products():
product_id = (
row["retailer"],
row["retailer_product_id"],
)
if product_id in existing_ids:
continue
new_count += 1
yield row
print(
f"[{adapter.retailer}] New products found: {new_count}"
)
return products
def create_nutrition_resource(adapter: RetailerAdapter):
@dlt.resource(
name="raw_nutrition",
write_disposition="append",
primary_key="retailer_product_id",
)
def nutrition():
existing_ids = get_existing_nutrition_ids()
new_count = 0
for row in adapter.nutrition():
product_id = row["retailer_product_id"]
if product_id in existing_ids:
continue
new_count += 1
yield row
print(
f"[{adapter.retailer}] New nutrition records found: {new_count}"
)
return nutrition
def run_ingestion(adapter: RetailerAdapter):
"""Run the shared ingestion pipeline for any retailer adapter."""
pipeline = dlt.pipeline(
pipeline_name=f"{adapter.retailer}_reference_db",
destination="duckdb",
dataset_name="raw",
)
load_info = pipeline.run(
[
create_products_resource(adapter)(),
create_nutrition_resource(adapter)(),
]
)
print(load_info)
if __name__ == "__main__":
from reference_db.adapters.compliments import ComplimentsAdapter
run_ingestion(ComplimentsAdapter()) |