Table of Contents

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:

  1. Bronze — raw CSV landed in a Unity Catalog volume.
  2. Silver — cleaned, schema-enforced Parquet, partitioned by Year to avoid the small-file problem.
  3. Gold — Delta table with Z-Ordering and compaction for fast analytical queries.
  4. Orchestration — transformations driven by the metaclass-registered ETL steps from LS-01-Python-Classes-Metaclasses-Spark.
  5. 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, and StepMeta.
  • Retail dataset: download retail-sales.csv (or reuse the sales CSVs from LA-02-Explore-data) to your machine.

Use a dedicated catalog/schema such as main.capstone to isolate capstone objects from the earlier labs.

Exercise 1: Ingest raw retail data (Bronze)

  1. Create notebook LA-08-capstone on Serverless compute.
  2. 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))
  1. 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)

  1. Define an explicit schema (never trust inferSchema in 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))
  1. 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
  1. 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 use insertInto with spark.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)

  1. 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))
  1. 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")
  1. 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.

VACUUM physically deletes old files. With the default 168-hour retention it is safe for time travel (as seen in LA-04-Explore-Delta-Lake); never run VACUUM RETAIN 0 HOURS on a table you may need to roll back.

Exercise 4: Orchestrate with LA-07 classes

  1. 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)
  1. Verify: print(StepMeta.registry) lists gold_revenue alongside the LA-07 steps, and the report matches the SQL result from Exercise 3.

Exercise 5: Schedule with a Lakeflow job

  1. In the sidebar, select Jobs & Pipelines → Create Job.
  2. Name the job LA-08 Retail Capstone.
  3. Select Add task, configure:
    • Task name: run_capstone
    • Type: Notebook
    • Source: Workspace → browse to LA-08-capstone
    • Compute: Serverless
  4. Select Add trigger → Schedule → repeat Every 1 day.
  5. Select Create, then Run now.
  6. Verify: in the job run view, the run_capstone task 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 overwrite

Extend: add a data-quality step class (registered via StepMeta) that fails the job when Quantity <= 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 Year and partition pruning is visible in EXPLAIN.
  • 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;
  1. Remove the uploaded files under /Volumes/main/default/raw_files/ via Catalog Explorer.
  2. In Jobs & Pipelines, select LA-08 Retail Capstone → … → Delete job.
  3. In Compute, confirm no idle clusters remain running.