Sub topic 7
Building a bronze, silver and gold flow
This chapter assumes you can write basic SQL and PySpark, know Unity Catalog catalogs and schemas, and have met streaming tables and materialized views in earlier chapters. You will build a three-layer flow for an orders feed and learn why each layer uses the dataset type it does.
The three layers
The medallion pattern splits a pipeline into layers of increasing quality.
- Bronze holds raw data as it arrived, with little or no change. It is the replayable record of the source.
- Silver holds cleaned and typed records: valid keys, correct data types, bad rows removed or flagged.
- Gold holds results shaped for a business question, such as daily revenue.
Each layer is a dataset in the pipeline. You declare what each one contains, and the pipeline works out the order in which to build them.
Bronze: ingest the raw files
Bronze is append-style data, so it is a streaming table. read_files uses Auto Loader, which processes only the files that are new since the last update.
CREATE OR REFRESH STREAMING TABLE orders_bronze
AS SELECT *
FROM STREAM read_files(
'/Volumes/main/demo/raw/orders/',
format => 'json'
);Silver: clean and validate
Silver reads bronze as a stream, so each update processes only the new bronze rows. It casts columns to proper types and applies expectations.
CREATE OR REFRESH STREAMING TABLE orders_silver (
CONSTRAINT valid_order_id EXPECT (order_id IS NOT NULL) ON VIOLATION DROP ROW,
CONSTRAINT positive_amount EXPECT (amount > 0)
)
AS SELECT
order_id,
customer_id,
CAST(amount AS DECIMAL(10,2)) AS amount,
CAST(order_ts AS TIMESTAMP) AS order_ts
FROM STREAM(orders_bronze);The first expectation drops rows with no order_id. The second keeps rows with a non-positive amount but counts them as violations in the event log.
Gold: aggregate
Gold results are recomputed from the full silver table, and an aggregation fits a materialized view. A plain FROM orders_silver is a batch read, so no STREAM() wrapper is needed.
CREATE OR REFRESH MATERIALIZED VIEW daily_revenue
AS SELECT
date(order_ts) AS order_date,
SUM(amount) AS revenue
FROM orders_silver
GROUP BY date(order_ts);The same flow in Python
In Python, each decorated function returns a DataFrame. The function name becomes the dataset name.
import dlt
from pyspark.sql.functions import col
@dlt.table(comment="Raw orders ingested with Auto Loader")
def orders_bronze():
return (
spark.readStream.format("cloudFiles")
.option("cloudFiles.format", "json")
.load("/Volumes/main/demo/raw/orders/")
)
@dlt.table(comment="Validated orders")
@dlt.expect_or_drop("valid_order_id", "order_id IS NOT NULL")
@dlt.expect("positive_amount", "amount > 0")
def orders_silver():
return (
dlt.read_stream("orders_bronze")
.select(
"order_id",
"customer_id",
col("amount").cast("decimal(10,2)").alias("amount"),
col("order_ts").cast("timestamp").alias("order_ts"),
)
)How the graph is built
You never state the order. The pipeline reads each query, finds the datasets it references, and builds the dependency graph. Here orders_silver reads orders_bronze, and daily_revenue reads orders_silver. The files can be in any order, and each update runs the datasets in dependency order.
Common errors
| Symptom | Likely cause |
|---|---|
| Silver reprocesses all of bronze after a change | The query changed and the table needed a full refresh |
| Aggregation fails on a streaming read | Gold was written as a streaming table instead of a materialized view |
| Rows vanish from silver | An `ON VIOLATION DROP ROW` expectation is dropping them. Check the event log counts |
| Unknown dataset name | Dataset referenced from the wrong catalog or schema, or misspelled |
Exercise
Why is orderssilver a streaming table while dailyrevenue is a materialized view?
Show answer
orderssilver takes append-style rows from bronze and handles each new row once, which suits a streaming table. dailyrevenue is an aggregation over all silver rows, so it is recomputed (incrementally where possible) as a materialized view.
Exercise
Which dataset does the pipeline build first, and how does it know?
Show answer
ordersbronze. The queries of orderssilver and dailyrevenue reference it, directly or through orderssilver, so the dependency graph places bronze first.