Sub topic 2
Ingesting Files into Bronze with Auto Loader
Assume basic SQL, PySpark DataFrames, JSON or Parquet files, and Databricks notebooks. This chapter follows an order-based pipeline: ingest raw files into bronze, clean them into silver, and apply quality rules before downstream use.
Ingesting Files into Bronze with Auto Loader
Auto Loader is Databricks’ incremental file-ingestion tool. It detects new files in cloud storage and reads them as a stream. The bronze layer stores this data with minimal transformation so it can be replayed later.
from pyspark.sql import functions as F
raw = (
spark.readStream.format("cloudFiles")
.option("cloudFiles.format", "json")
.option(
"cloudFiles.schemaLocation",
"/Volumes/main/sales/checkpoints/orders_schema",
)
.load("/Volumes/main/sales/landing/orders/")
.withColumn("_ingested_at", F.current_timestamp())
.withColumn("_source_file", F.col("_metadata.file_path"))
)
(
raw.writeStream
.option(
"checkpointLocation",
"/Volumes/main/sales/checkpoints/orders_bronze",
)
.trigger(availableNow=True)
.toTable("main.bronze.orders")
)The _source_file column identifies the original file. The ingestion timestamp records when Databricks read the record. Keep this metadata because it helps with debugging, auditing, and deduplication.
Processing Only New Data
Structured Streaming processes data incrementally. A checkpoint stores progress, including discovered files and completed micro-batches. If the job restarts, it uses the checkpoint rather than scanning every file as new.
availableNow=True processes all currently available files and then stops. This is useful for scheduled jobs. A continuously running stream uses a different trigger and waits for future files.
Silver: Clean, Type, and Conform
Silver data has consistent names, types, and keys. Convert strings to timestamps or decimals, remove unusable records, and standardize values before consumers query the data.
Deduplicating and Upserting into Silver with MERGE
A source can contain repeated updates for the same order. Select the newest record per order_id, then use MERGE to update an existing row or insert a new one.
MERGE INTO main.silver.orders AS t
USING (
SELECT
order_id,
customer_id,
CAST(order_ts AS TIMESTAMP) AS order_ts,
CAST(amount AS DECIMAL(12, 2)) AS amount,
status
FROM main.bronze.orders
WHERE order_id IS NOT NULL
QUALIFY ROW_NUMBER() OVER (
PARTITION BY order_id
ORDER BY _ingested_at DESC
) = 1
) AS s
ON t.order_id = s.order_id
WHEN MATCHED THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *;Enforcing Data Quality Between Layers
Expectations define acceptable records. Use warn behavior when you want to keep invalid rows and measure violations. Use drop behavior for records that cannot safely continue. Use fail behavior when invalid data must stop the pipeline.
> callout warning > Do not deduplicate without a stable key and ordering column. An ingestion timestamp is useful, but an application update timestamp is usually better when it is reliable. >
Exercise
Which setting lets a scheduled job process existing files and stop after catching up?
Show answer
The availableNow=True trigger.