# Databricks notebook source # MAGIC %md # MAGIC # Your first Databricks Free Edition notebook # MAGIC Use synthetic shipments to find the routes with the most late deliveries. # MAGIC Upload shipments.csv to a Unity Catalog volume and keep the lab in a new schema. # COMMAND ---------- import re from pyspark.sql import functions as F SOURCE_SCHEMA = "shipment_id STRING, route STRING, promised_date STRING, delivered_date STRING" ISO_DATE = r"^[0-9]{4}-[0-9]{2}-[0-9]{2}$" # COMMAND ---------- # MAGIC %md # MAGIC ## Set up the lab # MAGIC Set the catalog, schema and volume widgets to the names you see in Catalog. # MAGIC The notebook writes a table named shipment_status_lab in that schema. # MAGIC Use a schema you created specifically for this exercise. # COMMAND ---------- def lab_locations(catalog, schema, volume): for name in (catalog, schema, volume): if not re.fullmatch(r"[A-Za-z0-9_-]+", name): raise ValueError("Use catalog, schema and volume names containing letters, digits, _ or -") csv_path = f"/Volumes/{catalog}/{schema}/{volume}/shipments.csv" table = f"`{catalog}`.`{schema}`.`shipment_status_lab`" return csv_path, table if "dbutils" in globals(): current = spark.sql("SELECT current_catalog() AS name").first()["name"] dbutils.widgets.text("catalog", current) dbutils.widgets.text("schema", "tfod_delivery_lab") dbutils.widgets.text("volume", "shipping_files") # COMMAND ---------- # MAGIC %md # MAGIC ## Read and classify shipments # MAGIC A blank actual date marks an open shipment when the promised date is valid. # MAGIC Invalid dates remain visible as a separate group. # COMMAND ---------- def read_shipments(session, csv_path): return ( session.read.schema(SOURCE_SCHEMA) .option("header", True) .option("enforceSchema", False) .option("mode", "FAILFAST") .csv(csv_path) ) def clean_shipments(rows): def as_date(field): text = F.trim(F.col(field)) return F.when( text.rlike(ISO_DATE), F.try_to_timestamp(text, F.lit("yyyy-MM-dd")).cast("date"), ) actual = F.trim(F.col("delivered_date")) actual_missing = actual.isNull() | (actual == "") rows = ( rows.withColumn("shipment_id", F.trim("shipment_id")) .withColumn("route", F.trim("route")) .withColumn("promised_day", as_date("promised_date")) .withColumn("delivered_day", as_date("delivered_date")) ) status = ( F.when( F.col("promised_day").isNull() | (~actual_missing & F.col("delivered_day").isNull()), "invalid", ) .when(actual_missing, "open") .when(F.col("delivered_day") > F.col("promised_day"), "late") .otherwise("on_time") ) return rows.withColumn("status", status) def check_grain(rows): missing_keys = rows.where( F.col("shipment_id").isNull() | (F.col("shipment_id") == "") | F.col("route").isNull() | (F.col("route") == "") ) if missing_keys.limit(1).count(): raise ValueError("Every shipment needs an ID and a route") duplicates = rows.groupBy("shipment_id").count().where(F.col("count") > 1) if duplicates.limit(1).count(): raise ValueError("Duplicate shipment IDs would change the KPI") if "dbutils" in globals(): csv_path, target_table = lab_locations( dbutils.widgets.get("catalog"), dbutils.widgets.get("schema"), dbutils.widgets.get("volume") ) shipments = clean_shipments(read_shipments(spark, csv_path)) check_grain(shipments) display(shipments.select("shipment_id", "route", "promised_date", "delivered_date", "status").orderBy("shipment_id")) # COMMAND ---------- # MAGIC %md # MAGIC ## Save the lab table as Delta # MAGIC The write replaces shipment_status_lab in the chosen lab schema. # MAGIC Re-running the synthetic CSV keeps the same shipment counts. # COMMAND ---------- def save_lab_table(rows, table): rows.write.format("delta").mode("overwrite").saveAsTable(table) if "dbutils" in globals(): save_lab_table(shipments, target_table) print(f"Saved {target_table}") # COMMAND ---------- # MAGIC %md # MAGIC ## Calculate the rate by route with SQL # MAGIC The denominator includes only completed deliveries with valid dates. # MAGIC A route with zero eligible shipments has no rate. # MAGIC In the result, choose + then Visualization, and use route on X and late_pct on Y. # COMMAND ---------- def route_kpis(session, table): return session.sql(f""" WITH route_counts AS ( SELECT route, SUM(CASE WHEN status IN ('late', 'on_time') THEN 1 ELSE 0 END) AS eligible, SUM(CASE WHEN status = 'late' THEN 1 ELSE 0 END) AS late, SUM(CASE WHEN status = 'open' THEN 1 ELSE 0 END) AS open_shipments, SUM(CASE WHEN status = 'invalid' THEN 1 ELSE 0 END) AS invalid_shipments FROM {table} GROUP BY route ) SELECT *, ROUND(100.0 * late / NULLIF(eligible, 0), 2) AS late_pct FROM route_counts ORDER BY late_pct DESC NULLS LAST, route """) if "dbutils" in globals(): display(route_kpis(spark, target_table))