Docsity

Data Design REALTED TOPIC, Summaries of Design

Toggle sidebar
bg1
Databricks Data Engineer
Study Notes — Unit 2.6 (Delta Lake Operations) & Unit 2.7 (Jobs & Task Orchestration)
Unit 2.6 — Databricks Delta Lake Operations
1. Extracting Data Directly from Files
• Query a single file: SELECT * FROM file_format.`/path/to/file`
• Example: SELECT * FROM json.`${da.paths.datasets}/raw/events-kafka/001.json`
• Query an entire directory (same format & schema for all files) by pointing to the directory path instead of one file:
SELECT * FROM json.`${da.paths.datasets}/raw/events-kafka`
• Chain Spark logic: create a temp view from a query against a path, then reference it later:
CREATE OR REPLACE TEMP VIEW events_temp_view AS SELECT * FROM json.`$
{da.paths.datasets}/raw/events-kafka/`; SELECT * FROM events_temp_view
• Extract text files as raw strings:
SELECT * FROM text.`${da.paths.datasets}/raw/events-kafka/`
• binaryFile format — for images/unstructured data. Returns fields: path, modificationTime, length, content.
SELECT * FROM binaryFile.`${da.paths.datasets}/raw/events-kafka/`
2. Providing Options for External Sources
• CSV is NOT self-describing (unlike JSON/Parquet) — direct queries rarely give the desired result (header row may be
read as data, columns may be a single truncated column).
• General syntax to create a table with options against an external source:
CREATE TABLE table_identifier (col_name1 col_type1, ...) USING data_source OPTIONS
(key1 = "val1", key2 = "val2", ...) LOCATION path
• Example — registering a CSV table with header & delimiter options:
CREATE TABLE sales_csv (order_id LONG, email STRING, transactions_timestamp LONG,
total_item_quantity INTEGER, purchase_revenue_in_usd DOUBLE, unique_items INTEGER,
items STRING) USING CSV OPTIONS (header = "true", delimiter = "|") LOCATION "$
{da.paths.working_dir}/sales-csv"
• DESCRIBE EXTENDED table_name — shows detailed table metadata.
3. Limits of Tables with External Data Sources
• Tables over external sources do NOT get Delta Lake / Lakehouse performance guarantees.
• Delta Lake tables always show the most recent data; tables on external sources may show older cached versions.
• If an external system updates files directly (bypassing Spark), Spark isn't notified — you must manually refresh:
REFRESH TABLE sales_csv
4. CTAS — CREATE TABLE AS SELECT
• Automatically infers schema from query results — does NOT support manual schema declaration.
• Useful for external data with well-defined schema (e.g., Parquet).
• Does NOT support specifying additional file options — a limitation for CSV ingestion.
pf3
pf4
pf5

Partial preview of the text

Download Data Design REALTED TOPIC and more Summaries Design in PDF only on Docsity!

Databricks Data Engineer

Study Notes — Unit 2.6 (Delta Lake Operations) & Unit 2.7 (Jobs & Task Orchestration)

Unit 2.6 — Databricks Delta Lake Operations

1. Extracting Data Directly from Files

  • Query a single file: SELECT * FROM file_format./path/to/file
  • Example: SELECT * FROM json.${da.paths.datasets}/raw/events-kafka/001.json
  • Query an entire directory (same format & schema for all files) by pointing to the directory path instead of one file: SELECT * FROM json.${da.paths.datasets}/raw/events-kafka
  • Chain Spark logic: create a temp view from a query against a path, then reference it later: CREATE OR REPLACE TEMP VIEW events_temp_view AS SELECT * FROM json.$ {da.paths.datasets}/raw/events-kafka/; SELECT * FROM events_temp_view
  • Extract text files as raw strings: SELECT * FROM text.${da.paths.datasets}/raw/events-kafka/
  • binaryFile format — for images/unstructured data. Returns fields: path, modificationTime, length, content. SELECT * FROM binaryFile.${da.paths.datasets}/raw/events-kafka/

2. Providing Options for External Sources

  • CSV is NOT self-describing (unlike JSON/Parquet) — direct queries rarely give the desired result (header row may be read as data, columns may be a single truncated column).
  • General syntax to create a table with options against an external source: CREATE TABLE table_identifier (col_name1 col_type1, ...) USING data_source OPTIONS (key1 = "val1", key2 = "val2", ...) LOCATION path
  • Example — registering a CSV table with header & delimiter options: CREATE TABLE sales_csv (order_id LONG, email STRING, transactions_timestamp LONG, total_item_quantity INTEGER, purchase_revenue_in_usd DOUBLE, unique_items INTEGER, items STRING) USING CSV OPTIONS (header = "true", delimiter = "|") LOCATION "$ {da.paths.working_dir}/sales-csv"
  • DESCRIBE EXTENDED table_name — shows detailed table metadata.

3. Limits of Tables with External Data Sources

  • Tables over external sources do NOT get Delta Lake / Lakehouse performance guarantees.
  • Delta Lake tables always show the most recent data; tables on external sources may show older cached versions.
  • If an external system updates files directly (bypassing Spark), Spark isn't notified — you must manually refresh: REFRESH TABLE sales_csv

4. CTAS — CREATE TABLE AS SELECT

  • Automatically infers schema from query results — does NOT support manual schema declaration.
  • Useful for external data with well-defined schema (e.g., Parquet).
  • Does NOT support specifying additional file options — a limitation for CSV ingestion.

CREATE OR REPLACE TABLE sales AS SELECT * FROM parquet.${da.paths.datasets}/raw/sales-historical/; DESCRIBE EXTENDED sales;

  • To ingest CSV via CTAS: define a temp view WITH options, then CTAS from that view: CREATE OR REPLACE TEMP VIEW sales_tmp_vw (order_id LONG, email STRING, transactions_timestamp LONG, total_item_quantity INTEGER, purchase_revenue_in_usd DOUBLE, unique_items INTEGER, items STRING) USING CSV OPTIONS (path = "$ {da.paths.datasets}/raw/sales-csv", header = "true", delimiter = "|"); CREATE TABLE sales_delta AS SELECT * FROM sales_tmp_vw; SELECT * FROM sales_delta
  • Filter/rename columns during table creation (simple transformation): CREATE OR REPLACE TABLE purchases AS SELECT order_id AS id, transaction_timestamp, purchase_revenue_in_usd AS price FROM sales;
  • Same result achievable with a VIEW instead of a physical table.
  • Generated columns: computed automatically from a function on other columns — CTAS does not support schema declaration otherwise. CREATE OR REPLACE TABLE purchase_dates ( id STRING, transaction_timestamp STRING, price STRING, date DATE GENERATED ALWAYS AS ( cast(cast(transaction_timestamp/1e6 AS TIMESTAMP) AS DATE)) COMMENT "generated based on transactions_timestamp column")
  • Allow generated columns during a MERGE: SET spark.databricks.delta.schema.autoMerge.enabled = true; MERGE INTO purchase_dates a USING purchases b ON a.id = b.id WHEN NOT MATCHED THEN INSERT *

5. Table Constraints

  • Delta Lake enforces schema on write, enabling SQL constraint management.
  • Two supported constraint types: NOT NULL and CHECK (generated columns are a special implementation of CHECK). ALTER TABLE purchase_dates ADD CONSTRAINT valid_date CHECK (date > '2020-01-01'); DESCRIBE EXTENDED purchase_dates

6. Cloning Tables

  • DEEP CLONE — fully copies data AND metadata from source to target. Runs incrementally (re-running syncs changes). Can take a while for large datasets. CREATE OR REPLACE TABLE purchases_clone DEEP CLONE purchases
  • SHALLOW CLONE — quickly copies just the Delta transaction log; data files are not moved. Great for testing changes without risk. CREATE OR REPLACE TABLE purchases_shallow_clone SHALLOW CLONE purchases
  • In both cases, modifications to the clone are tracked/stored separately from the source.

7. Writing to Delta Tables — Overwrites

  • Overwriting > dropping & recreating: no files need deleting, no recursive directory listing → much faster.
  • Time travel still works — you can access the previous version of the table.
  • Overwrite is atomic — concurrent queries can keep reading the table while it's being replaced.
  • If an overwrite fails partway, ACID guarantees revert the table to its prior state.
  • Two simple ways to fully overwrite a table:

a) CREATE OR REPLACE TABLE (CRAS)

  • Fully replaces table contents every execution (unlike CREATE IF NOT EXISTS).
  • from_json() parses a JSON string into a Spark struct type using a schema (schema_of_json() can derive the schema from an example): CREATE OR REPLACE TEMP VIEW parsed_events AS SELECT from_json(value, schema_of_json('{insert_example_schema_here}')) AS json FROM events_strings; SELECT
    • FROM parsed_events
    • (star) unpacking flattens a struct's fields into columns: CREATE OR REPLACE TEMP VIEW new_events_final AS SELECT json.* FROM parsed_events; SELECT * FROM new_events_final
  • Dot syntax accesses struct subfields, e.g.: SELECT ecommerce.purchase_revenue_in_usd FROM events WHERE ecommerce.purchase_revenue_in_usd IS NOT NULL
  • Array functions: ā—¦ explode() — puts each array element on its own row ā—¦ collect_set() — collects unique values for a field (incl. within arrays) ā—¦ flatten() — combines multiple arrays into a single array ā—¦ array_distinct() — removes duplicate elements from an array SELECT user_id, collect_set(event_name) AS event_history, array_distinct(flatten(collect_set(items.item_id))) AS cart_history FROM events GROUP BY user_id

12. Joins & Set Operators

  • Default JOIN type = INNER JOIN — returns only the intersection (rows present in both sets). CREATE OR REPLACE VIEW sales_enriched AS SELECT * FROM (SELECT *, explode(items) AS item FROM sales) a INNER JOIN item_lookup b ON a.item.item_id = b.item_id; SELECT * FROM sales_enriched
  • UNION — combines results of two+ SELECT statements. Column count, data types, and order must match across queries. SELECT * FROM events UNION SELECT * FROM new_events_final
  • INTERSECT — returns rows found in BOTH relations. SELECT * FROM events INTERSECT SELECT * FROM new_events_final
  • MINUS — returns rows found in one dataset but NOT the other. SELECT * FROM events MINUS SELECT * FROM new_events_final

13. PIVOT

  • Aggregates data and transforms rows into columns using the PIVOT clause (placed after a table/subquery name).
  • PIVOT's first argument = aggregate function + column to aggregate; FOR subclause = pivot column; IN operator = pivot column values. CREATE OR REPLACE TABLE transactions AS SELECT * FROM ( SELECT email, order_id, transaction_timestamp, total_item_quantity, purchase_revenue_in_usd, unique_items, item.item_id AS item_id, item.quantity AS quantity FROM sales_enriched ) PIVOT ( sum(quantity) FOR item_id IN ('P_FOAM_K','M_STAN_Q','P_FOAM_S','M_PREM_Q', 'M_STAN_F','M_STAN_T','M_PREM_K','M_PREM_F','M_STAN_K','M_PREM_T','P_DOWN_S','P_DOWN _K') ); SELECT * FROM transactions

14. Higher-Order Functions

  • Built-in functions operate on a single simple data type in a cell — they cannot process array values directly. Higher- order functions solve this.
  • FILTER — creates a new column by filtering elements out of an array via a lambda condition: SELECT order_id, items, FILTER(items, i -> i.item_id LIKE "%K") AS king_items FROM sales ā—¦ Syntax parts: FILTER = function name; items = input array; i = iterator variable; -> = starts the lambda; the boolean expression is the function body.
  • EXISTS — tests whether a condition is true for one or more elements in an array: SELECT *, EXISTS(categories, c -> c = "Company Blog") AS companyFlag FROM blog_posts
  • TRANSFORM — applies an existing function to every element in an array, producing a new array: CREATE OR REPLACE TEMP VIEW king_item_revenues AS SELECT order_id, king_items, TRANSFORM(king_items, k -> CAST(k.item_revenue_in_usd * 100 AS INT)) AS item_revenues FROM king_size_sales; SELECT * FROM king_item_revenues TRANSFORM(categories, cat -> LOWER(cat)) AS lwrCategories

15. SQL UDFs & Control Flow

  • A SQL UDF applies custom logic to input(s) and returns a result. CREATE OR REPLACE FUNCTION function_name(param TYPE) RETURNS type_to_be_returned RETURN function_itself
  • Example: CREATE OR REPLACE TEMPORARY VIEW foods(food) AS VALUES ("beef"), ("beans"), ("potatoes"), ("bread"); CREATE OR REPLACE FUNCTION yelling(text STRING) RETURNS STRING RETURN concat(upper(text), "!!!"); SELECT yelling(food) FROM foods; DESCRIBE FUNCTION EXTENDED yelling
  • CASE WHEN ... THEN ... ELSE ... END evaluates multiple conditional statements: SELECT *, CASE WHEN food = "beans" THEN "I love beans" WHEN food = "potatoes" THEN "My favorite vegetable is potatoes" WHEN food <> "beef" THEN concat("Do you have any good recipes for ", food, "?") ELSE concat("I don't eat ", food) END FROM foods
  • SQL UDFs let a small group of users encode complex/custom logic once, reusable by many — useful when migrating from systems with many custom procedures.
  • Python for Databricks SQL & control flow: ā—¦ spark.sql("...") runs a SQL query from Python; display(spark.sql("...")) renders it like a SQL notebook cell ā—¦ f-strings let you substitute variables/function results into a string, e.g. f"...{variable}..." table_name = "users" filter_clause = "WHERE state = 'CA'" query = f""" SELECT * FROM {table_name} {filter_clause} """ print(query)

16. Incremental Ingestion with Auto Loader

  • Auto Loader solves the historically hard problem of ingesting files from a data lake into a database (continuous, affordable, maintainable, scalable).
  • Creates a Delta Lake table by incrementally/progressively processing new files from a directory in cloud object storage.
  • Automatically configures and listens to a cloud notification service for new files — no manual polling needed.
  • Scales to millions of files per second.
  • Databricks recommends Auto Loader as general best practice when ingesting data from cloud object storage.

5. Viewing Job Runs & Run Details

  • Clicking a task name opens the Runs tab — a table of active and completed runs. Click Matrix to switch views.
  • The matrix's Job Runs row shows overall run duration/status; hover to see start time, duration, status.
  • The Tasks row shows each task and its status; job/task run bars are color-coded by run state.
  • Databricks keeps job run history for up to 60 days — export results before expiration if preservation is required.
  • The job run details page links to logs, job output, and success/failure details for each task.

6. Exporting Job Run Results

  • For all job types, you can export job run logs and notebook run results.
  • Notebook job runs: export a rendered notebook, which can be imported back into a Databricks workspace.
  • Job run logs can also be exported; via the program/API, logs can be configured to send automatically to DBFS or cloud storage.

7. SQL Query Refresh Schedule

  • Locate the Refresh Schedule field at the bottom right of the SQL query editor box; click the blue 'Never'.
  • Use the dropdown to change to, e.g., Refresh every 1 minute. For Ends, click the On radio button and select an end date.
  • Use the left sidebar to navigate to Dashboards; click the blue Refresh button to update a dashboard.
  • Click the Schedule button to review dashboard scheduling options.
  • Note: scheduling a dashboard to update executes ALL queries associated with that dashboard.