Table of Contents
- Scenario
- Prerequisites
- Exercise 1: Ingest raw retail data (Bronze)
- Exercise 2: Partitioned Parquet with schema enforcement (Silver)
- Exercise 3: Curated Delta table with Z-Ordering (Gold)
- Exercise 4: Orchestrate with LA-07 classes
- Exercise 5: Schedule with a Lakeflow job
- Fix or extend challenge
- Assessment checklist
- Clean up
Scenario
A retail company drops daily sales files as CSV. You will build the production-grade version of the labs from LA-01-Explore-Azure-Databricks to LA-06-Build-workflow:
- Bronze — raw CSV landed in a Unity Catalog volume.
- Silver — cleaned, schema-enforced Parquet, partitioned by
Yearto avoid the small-file problem. - Gold — Delta table with Z-Ordering and compaction for fast analytical queries.
- Orchestration — transformations driven by the metaclass-registered ETL steps from LS-01-Python-Classes-Metaclasses-Spark.
- Scheduling — a Lakeflow job running the notebook on a daily trigger.
Prerequisites
- Azure Databricks workspace with Unity Catalog and serverless compute.
- Completed LS-01-Python-Classes-Metaclasses-Spark — you will reuse
SparkSessionWrapper,DataFrameOps, andStepMeta. - Retail dataset: download
retail-sales.csv(or reuse thesalesCSVs from LA-02-Explore-data) to your machine.
Use a dedicated catalog/schema such as
main.capstoneto isolate capstone objects from the earlier labs.
Exercise 1: Ingest raw retail data (Bronze)
- Create notebook LA-08-capstone on Serverless compute.
- Recreate the LA-07 wrapper classes (cell 1) and set the working context:
wrapper = SparkSessionWrapper(catalog="main", schema="capstone")
# Upload retail-sales.csv via Catalog Explorer → Add data,
# then reference the staged path:
RAW = f"/Volumes/{wrapper.catalog}/default/raw_files/retail-sales.csv"
raw = wrapper.read_csv(RAW, header="true", inferSchema="true")
print(raw.count(), "rows")
display(raw.limit(5))- Verify: the row count matches the source file’s data rows and the inferred schema shows
OrderID,ProductID,Category,Quantity,Price,OrderDate.
Exercise 2: Partitioned Parquet with schema enforcement (Silver)
- Define an explicit schema (never trust
inferSchemain production) and clean the data:
from pyspark.sql import types as T, functions as F
sales_schema = T.StructType([
T.StructField("OrderID", T.StringType(), False),
T.StructField("ProductID", T.StringType(), True),
T.StructField("Category", T.StringType(), True),
T.StructField("Quantity", T.IntegerType(), True),
T.StructField("Price", T.DoubleType(), True),
T.StructField("OrderDate", T.DateType(), True),
])
raw = wrapper.read_csv(RAW, schema=sales_schema, header="true")
silver = (DataFrameOps(raw)
.dedupe(["OrderID"])
.df
.withColumn("Year", F.year("OrderDate")))
SILVER = f"/Volumes/{wrapper.catalog}/default/raw_files/silver_sales"
(silver.write
.mode("overwrite")
.partitionBy("Year") # hash-style folder partitioning
.option("maxRecordsPerFile", 500000) # guards against small-file drift
.parquet(SILVER))- Read back and inspect the physical layout:
check = wrapper.spark.read.parquet(SILVER)
print(check.count(), "rows")
wrapper.spark.sql(f"LIST '{SILVER}'").show(truncate=False)Expected output — one folder per year, each containing Parquet files:
/Volumes/main/default/raw_files/silver_sales/Year=2024/part-00000....snappy.parquet
/Volumes/main/default/raw_files/silver_sales/Year=2025/part-00000....snappy.parquet- Verify partition pruning:
pruned = check.where("Year = 2025")
pruned.explain()Expected: PartitionFilters: [isnotnull(Year), (Year = 2025)] in the physical plan — proving predicate pushdown to the partition folders.
mode("overwrite")on a partitioned Parquet path replaces existing folders. For incremental loads useinsertIntowithspark.conf.set("spark.sql.sources.partitionOverwriteMode", "dynamic")— the pattern covered in the course's partitioning topic.
Exercise 3: Curated Delta table with Z-Ordering (Gold)
- Register the silver data as a managed Delta table:
gold_table = wrapper.table("sales_gold")
(silver.write
.format("delta")
.mode("overwrite")
.option("overwriteSchema", "true")
.saveAsTable(gold_table))- Optimize layout with Z-Ordering and compaction:
wrapper.spark.sql(f"OPTIMIZE {gold_table} ZORDER BY (Category, OrderDate)")
wrapper.spark.sql(f"VACUUM {gold_table} RETAIN 168 HOURS")- Verify the query benefits from the sorted layout:
wrapper.spark.sql(f"""
SELECT Category, SUM(Quantity * Price) AS revenue
FROM {gold_table}
WHERE OrderDate >= '2025-01-01'
GROUP BY Category
""").show()Expected: revenue per category; run EXPLAIN and confirm Delta scans a reduced number of files.
VACUUMphysically deletes old files. With the default 168-hour retention it is safe for time travel (as seen in LA-04-Explore-Delta-Lake); never runVACUUM RETAIN 0 HOURSon a table you may need to roll back.
Exercise 4: Orchestrate with LA-07 classes
- Refactor the cleaning/aggregation into metaclass-registered steps so new steps plug in without touching the driver code:
class GoldRevenue(ETLStep):
name = "gold_revenue"
params = {"group": "Category"}
def run(self, df):
return df.groupBy(self.params["group"]).agg(
F.sum(F.col("Quantity") * F.col("Price")).alias("revenue"))
df = wrapper.spark.table(wrapper.table("sales_gold"))
report = StepMeta.registry["gold_revenue"]().run(df)
display(report)- Verify:
print(StepMeta.registry)listsgold_revenuealongside the LA-07 steps, and the report matches the SQL result from Exercise 3.
Exercise 5: Schedule with a Lakeflow job
- In the sidebar, select Jobs & Pipelines → Create Job.
- Name the job LA-08 Retail Capstone.
- Select Add task, configure:
- Task name:
run_capstone - Type: Notebook
- Source: Workspace → browse to LA-08-capstone
- Compute: Serverless
- Task name:
- Select Add trigger → Schedule → repeat Every 1 day.
- Select Create, then Run now.
- Verify: in the job run view, the
run_capstonetask shows Succeeded and the run start/finish times match the schedule configuration.
Fix or extend challenge
This incremental load has two bugs: it overwrites the whole table, and it re-partitions by Category (low cardinality is fine, but it conflicts with the Year layout built in Exercise 2). Fix both:
(silver.write
.mode("overwrite")
.partitionBy("Category") # bug 2
.parquet(SILVER)) # bug 1: should append dynamically, not overwriteExtend: add a data-quality step class (registered via
StepMeta) that fails the job whenQuantity <= 0, mimicking the expectations pattern from LA-05-Build-data-pipeline.
Assessment checklist
- Bronze CSV ingested with an explicit schema.
- Silver Parquet is partitioned by
Yearand partition pruning is visible inEXPLAIN. - Gold Delta table is Z-Ordered and compacted with
OPTIMIZE/VACUUM. - Transformations are driven by
StepMeta.registry, not hard-coded classes. - Lakeflow job runs the notebook on a daily trigger and succeeds.
- Challenge bugs identified and corrected.
Clean up
The following deletes billable storage (managed tables, volumes) and the scheduled job. Run only when the capstone is reviewed.
DROP TABLE IF EXISTS main.capstone.sales_gold;- Remove the uploaded files under
/Volumes/main/default/raw_files/via Catalog Explorer. - In Jobs & Pipelines, select LA-08 Retail Capstone → … → Delete job.
- In Compute, confirm no idle clusters remain running.