Sub topic 1
Working in a Databricks Notebook
Prerequisites
Assume that you know basic Python or SQL and understand tables as rows and columns. You also need a Databricks notebook attached to running compute.
The Notebook and Spark Session
A Databricks notebook is an interactive document made of cells. You run Python, SQL, or other supported code in each cell. Databricks provides a preconfigured SparkSession named spark. A SparkSession is the main entry point for creating DataFrames and running Spark operations.
What a DataFrame Is
A Spark DataFrame is a distributed table with named columns and data types. Distributed means Spark can split the data across multiple machines. A DataFrame describes data and the operations that should be applied to it.
from pyspark.sql import functions as F
orders = spark.createDataFrame(
[
(1, "alice", "2024-01-05", 120.0),
(2, "bob", "2024-01-06", 75.5),
(3, "alice", "2024-02-10", 30.0),
(4, "carol", "2024-02-11", None),
],
"order_id INT, customer STRING, order_date STRING, amount DOUBLE",
)
orders = orders.withColumn("order_date", F.to_date("order_date"))The orders variable now refers to a DataFrame. Its columns have names and types, and its order_date values have been converted to dates.
Looking at Your Data
Use display() in a Databricks notebook for an interactive table. Use show() for text output, and printSchema() to inspect column names, types, and whether values may be null.
orders.printSchema()
display(orders)
orders.show(2)Transformations, Actions, and Lazy Evaluation
A transformation describes a new DataFrame. Examples include select, filter, and withColumn. Spark evaluates these operations lazily, so it builds a plan without immediately reading all data.
An action needs a result and starts execution. Examples include show(), count(), display(), and writing a table.
big_orders = (
orders
.filter(F.col("amount") > 50)
.select("order_id", "customer", "amount")
.withColumn("amount_rounded", F.round("amount"))
)
big_orders.show()Schemas and Data Types
A schema defines the columns and their data types. Explicit schemas are safer than automatic type inference because they make the expected structure clear and avoid guessing. Common types include INT, STRING, DATE, DOUBLE, and BOOLEAN.
Exercise
Which operation in the example causes Spark to execute the lazy plan?
Show answer
big_orders.show() is an action, so it causes Spark to execute the transformations.