Sub topic 11
Building all three layers as a declarative pipeline
This chapter assumes you have read the earlier chapters on bronze ingestion with Auto Loader, the silver MERGE step, and the gold aggregate. You should be comfortable with PySpark DataFrames and Delta tables.
From steps to a pipeline
So far each layer was a separate piece of code. You wrote a streaming job for bronze, a MERGE for silver, and a CREATE TABLE for gold. You also had to run them in the right order and manage checkpoints yourself.
A declarative pipeline, built with Delta Live Tables (now part of Lakeflow), flips this. You describe what each table should contain. Databricks works out the dependency order, manages checkpoints, and updates each table incrementally.
The three layers in one file
Each function decorated with @dlt.table defines one table. The function body returns a DataFrame. Dependencies come from the reads: dlt.read_stream("orders_bronze") tells the pipeline that silver depends on bronze.
import dlt
from pyspark.sql import functions as F
@dlt.table(comment="Raw orders as ingested")
def orders_bronze():
return (
spark.readStream.format("cloudFiles")
.option("cloudFiles.format", "json")
.load("/Volumes/main/sales/landing/orders/")
.withColumn("_ingested_at", F.current_timestamp())
)
@dlt.table(comment="Typed orders with valid keys")
@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",
F.col("order_ts").cast("timestamp").alias("order_ts"),
F.col("amount").cast("decimal(12,2)").alias("amount"),
"status",
)
)
@dlt.table(comment="Daily revenue for completed orders")
def daily_revenue_gold():
return (
dlt.read("orders_silver")
.where("status = 'completed'")
.groupBy(F.to_date("order_ts").alias("order_date"))
.agg(F.count("*").alias("orders"), F.sum("amount").alias("revenue"))
)Notice what is missing compared with the earlier chapters. There is no checkpointLocation, no writeStream, and no trigger. The pipeline supplies these.
How the pipeline reads the code
The pipeline builds this graph from your reads. It runs each table after the ones it depends on. If you add a second gold table that reads orders_silver, it joins the graph without any ordering code.
Two read styles appear in the example:
dlt.read_streamprocesses only new rows from the upstream table. Bronze and silver use this because they are append-style flows.dlt.readreads the full upstream table. Gold uses it because an aggregate over all days must be recomputed as new orders arrive.
Expectations: warn, drop, or fail
Expectations are data quality rules attached to a table. The silver table uses two kinds, and a third exists.
| Decorator | Behavior on a violating row | Use when |
|---|---|---|
| `@dlt.expect` | Keeps the row, records the violation in metrics | The rule is informational |
| `@dlt.expect_or_drop` | Drops the row, records the count | Bad rows would corrupt downstream tables |
| `@dlt.expect_or_fail` | Stops the update | Any violation means the source is broken |
In the example, a missing order_id drops the row, because silver needs a key. A negative amount only gets recorded. You can then inspect the counts in the pipeline's event log.
Common errors
- Using
dltcode in a plain notebook. Thedltmodule works only when the code runs as part of a pipeline. Running the cell interactively fails or does nothing useful. - Expecting MERGE behavior. The silver table above does not deduplicate. A repeated
order_idstays as two rows. Deduplication in a pipeline needs a separate construct such asdlt.apply_changes, which is outside this chapter. - Reading a table that is not defined in the pipeline.
dlt.read("name")refers to tables in the same pipeline. For tables elsewhere, use their full three-level name such asmain.silver.orders.
Where the tables are stored
The pipeline publishes its tables to a target catalog and schema that you set in the pipeline settings. With the layout from the Unity Catalog chapter, you could send each layer to its own schema or run one pipeline per layer. A single pipeline is simpler to reason about. Separate pipelines give you independent schedules and permissions.
Exercise
You change positive_amount from @dlt.expect to @dlt.expect_or_fail. An order arrives with amount -5. What happens, and when would you choose this change?
Show answer
The pipeline update stops with an error instead of loading the row. Choose it when a negative amount means the source system is broken and you would rather halt than publish wrong revenue figures. Keep @dlt.expect if negative amounts are legitimate, such as refunds, and you only want to monitor them.
Exercise
Why does daily_revenue_gold use dlt.read while orders_silver uses dlt.read_stream?
Show answer
Silver can process each new bronze row once, so a streaming read fits. Gold is an aggregate over all days, and new orders change existing totals, so it reads the whole silver table and recomputes.