SparkSession and DataFrames

Part of the free LogicWiz Data Engineering course, Module 11: PySpark DataFrames. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 7:40 on Monday, and the monthly clickstream report is blank. The script behind it reads 2 billion events into DuckDB on one server, and at 3:12 a.m. it stopped with an out-of-memory error. Nora sends you a Databricks link and one line: "Write it in PySpark. If you know SQL and a little Python, you know most of it already."

You'll learn to

  • Start a SparkSession and read a file into a DataFrame
  • Tell a transformation from an action, and say why Spark waits
  • Write columns as expressions, and say what a Column is underneath
  • Bring small results back to Python without crashing the driver

Learn

One machine ran out of room

DuckDB and pandas run on one machine. When the data outgrows it, you can buy a bigger machine, or split the work across many.

Apache Spark splits it. It cuts a big table into pieces called partitions, sends them to many machines, runs the same steps on every piece at once, and combines the answers. Think of an election count: each polling station counts its own box, and the head office adds up the totals.

PySpark is Spark's Python interface. Your Python describes the work, and Spark's engine does it, on the Java virtual machine (the JVM). That is why the same few lines count 80 rows here and 8 billion on Databricks.

One table, four machines

A table of 2 billion events is cut into four partitions of 500 million rows, each counted on its own machine, and the four counts are added into one answer.

Read it left to right: one table, four pieces counted at the same time, one answer. The numbers are made up for the example, and real jobs cut a table into far more than four partitions.

Your way in: a SparkSession

Every PySpark program starts with a SparkSession, your connection to Spark. It reads files, runs SQL and makes DataFrames, Spark's tables.

from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.getOrCreate()

getOrCreate() returns the session that already exists, or makes one. On Databricks, spark is ready in every notebook.

functions as F is the name everyone uses. F.col, F.sum, F.round and hundreds of other built-in functions live there.

Run the read below. header=True takes the column names from the first line, and inferSchema=True asks Spark to look at the values and guess each column's type.

Read the orders export

from pyspark.sql import SparkSession, functions as F

spark = SparkSession.builder.getOrCreate()
orders = spark.read.csv("data/orders.csv", header=True, inferSchema=True)

orders.printSchema()
print("rows:", orders.count())
print("columns:", orders.columns)

It prints each column's name and type, then the size. Lesson 11.5 shows why production jobs write the schema down instead of guessing it.

What runs on this page: real PySpark code on a small engine, SQLFrame, which turns it into SQL for DuckDB. Some output looks a little different from real Spark, and code that needs a cluster gets its own Databricks card.

A DataFrame is a table that never changes

What came back is a DataFrame: a table with rows and named, typed columns. The names and types are its schema, which printSchema() prints.

Two things make it different from a pandas DataFrame:

  • It is spread out. On a cluster its rows live in partitions on many machines, so you never loop over them in Python.
  • It never changes. filter, select and withColumn do not edit a DataFrame. Each returns a new one, and you keep it by giving it a name: delivered = orders.filter(...).

A line on its own, such as orders.filter(...), builds a new DataFrame and throws it away.

Nothing runs until you ask

Steps like filter, select and withColumn are called transformations. A transformation computes nothing. It adds one step to a plan, a list of what to do, and returns at once.

The work starts only when you ask for a result. A call that asks for a result is an action: count(), show(), collect(), or a write. At the action, Spark looks at the whole plan, picks the best way to run it, and only then reads the data.

Think of a shopping list. Writing items down costs nothing; the trip to the shop happens once, when you go. Module 12 shows what Spark gains by planning the whole trip first.

Four lines, one plan, one run

Four lines of PySpark are added to a plan one at a time: a read, a filter, a select and a count; nothing runs until the count, which reads the file and returns 29.

  1. Line 1: orders = spark.read.csv(...). Spark notes the file and its columns. With inferSchema=True it scans the file once to guess the types, but it keeps no rows. The plan has one step.

  2. Line 2: delivered = orders.filter(...). Nothing is read. Spark adds a Filter step on top of the plan and hands you a new DataFrame. orders is unchanged.

  3. Line 3: ids = delivered.select(...). One more step, a Project. Three lines in, and Spark has still not looked at a single order.

  4. Line 4: ids.count(), an action. Now Spark plans the whole chain, reads the file, keeps the delivered rows, counts them and returns one number: 29.

Read each step left to right, in the order you wrote the lines. Nothing turns green until the action.

Remember: a transformation adds a step to the plan and returns a new DataFrame. Only an action makes Spark read the data.

A column is a recipe, not numbers

In pandas, df['qty'] * df['unit_price'] computes numbers at once. In PySpark, F.col('qty') * F.col('unit_price') computes nothing. It is an expression: a recipe Spark applies to every row later, on whichever machine holds that row.

Expressions go into a few methods:

  • select(...) picks or computes columns (SQL's SELECT)
  • filter(...), or its twin where(...), keeps rows where a condition is true
  • withColumn(name, expr) adds a column, or replaces the one with that name
  • .alias(name) names a computed column (SQL's AS)

Conditions use ==, !=, >, >= and .isin('a', 'b') (SQL's IN). Join them with & (and), | (or) and ~ (not), with brackets around each comparison: (F.col('a') > 1) & (F.col('b') == 'x').

Line amounts, the PySpark way

from pyspark.sql import SparkSession, functions as F

spark = SparkSession.builder.getOrCreate()
items = spark.read.csv("data/order_items.csv", header=True, inferSchema=True)

lines = items.withColumn("line_amount", F.round(F.col("qty") * F.col("unit_price"), 2))
big = (
    lines
    .filter(F.col("line_amount") >= 100)
    .select("order_id", "product_id", "qty", "line_amount")
)
big.show(5)
print("lines worth $100 or more:", big.count())

Brackets around a chain let you put one step per line, which is how most teams format PySpark. Read it top to bottom like a SQL query.

What withColumn did to order 1003

orderidlinenoqtyunitpricelineamount (new)
10031319.558.5
10032254.0108.0

line_amount is computed for each row from that row's own qty and unit_price, so Spark can do it on any machine without looking at other rows.

Under the hood: a tree, not a value

So what is F.col('qty') * F.col('unit_price'), really? A Column is one node of an expression tree, the structure Spark's optimiser, Catalyst, works on. The multiply is a node over two column references. Wrap it in F.round(..., 2), compare it with >= 100, and the tree grows. Python's *, >= and & are overloaded: they build nodes and compute nothing.

Where the tree lives depends on how you connect. In classic PySpark, the Python object is a handle to an object in the JVM of the driver, the process that plans the job. Python reaches it through Py4J, a socket bridge. With Spark Connect (Spark 3.4 and later), Python builds the plan itself and ships it to the server over gRPC, as protocol buffers.

Either way, Python never touches a row.

The tree behind one filter condition

An expression tree with a greater-or-equal node at the top, a round node and the literal 100 under it, and a multiply node over the qty and unit_price columns under the round.

Read it from the bottom up: two column references, a multiply, a round, then the comparison at the top. After analysis each reference becomes a typed one such as qty#3 (Spark numbers every column it sees), and the optimiser may fold or simplify nodes before any data is read.

The browser engine builds a tree too

from pyspark.sql import SparkSession, functions as F

spark = SparkSession.builder.getOrCreate()
amount = F.col("qty") * F.col("unit_price")
big = F.round(amount, 2) >= 100

print(type(big).__name__)    # a Column: nothing has been computed yet
print(repr(amount))          # the tree behind it

The browser engine (SQLFrame) builds a sqlglot tree and turns it into SQL for DuckDB. PySpark 3.5 prints the same object as Column<'(qty * unit_price)'>, a SQL rendering of its Catalyst tree. Different libraries, same idea: a recipe, not numbers.

When a typo gets caught

Each transformation wraps the plan in one more step: the read is a relation, withColumn adds a Project, filter a Filter.

Spark also checks your column names, but when depends on how you connect. Classic PySpark checks at once: a typo fails on the line that made it, with [UNRESOLVED_COLUMN.WITH_SUGGESTION] "A column, variable, or function parameter with name qtyy cannot be resolved. Did you mean one of the following?" (SQLSTATE 42703). Spark Connect keeps the plan unchecked on the client. The same error appears only when something needs the schema or the data, such as df.columns, show() or count(), so a typo surfaces several lines later.

At the action the optimiser rewrites the plan, and the work goes out to the executors, the worker processes on each machine.

Who does what when you call count()

A sequence between the Python driver, the JVM driver and the executors: Python builds the plan, the JVM analyses and optimises it, executors run one task per partition, and one number comes back.

Read it top to bottom: plan steps go down, one number comes back, and no row ever passes through Python. With Spark Connect, the first arrow is a gRPC call that carries the unresolved plan.

Bringing answers back to Python

An action brings its answer back to the driver. count() returns a number, show(n) prints rows, first() returns one Row, and collect() returns a list of them (read a field with row['status'] or row.status).

collect() is how you test PySpark code, and the classic way to crash a job. Two limits stand in the way:

  • spark.driver.maxResultSize (default 1g) caps the results of one action. Past it the job stops with Total size of serialized results of 3125 tasks (1025.3 MiB) is bigger than spark.driver.maxResultSize (1024.0 MiB).
  • The driver's own memory. Every row that comes back becomes Python objects, and Python objects are big.

What one row costs on the driver

A bar splits one 4-column row, as Python objects on a 64-bit driver, into a 72-byte tuple, two 28-byte ints, a 50-byte short string and a 24-byte float, 202 bytes in all.

The parts add up: 72 + 28 + 28 + 50 + 24 = 202 bytes, before the list that holds the rows. The browser's Python is 32-bit, so the same row measures smaller on this page.

Collect a small result

from pyspark.sql import SparkSession, functions as F

spark = SparkSession.builder.getOrCreate()
orders = spark.read.csv("data/orders.csv", header=True, inferSchema=True)

june2 = orders.filter(F.to_date("order_ts") == "2025-06-02").orderBy("order_id")
rows = june2.select("order_id", "status").collect()

print(len(rows), "orders placed on 2 June")
print("first:", rows[0]["order_id"], rows[0].status)
print("ids:", [r["order_id"] for r in rows])

Collect only results you know are small, and write big ones to storage. orderBy matters here: without it, Spark returns rows in whatever order the partitions finish. F.to_date('order_ts') turns a timestamp into a date, so it can be compared with '2025-06-02'.

The trap: forgetting that DataFrames never change. items.withColumn("line_amount", ...) on a line of its own builds a new DataFrame and throws it away, so the next step fails with a missing column. Always assign: lines = items.withColumn(...). The same goes for filter, select, drop and every other transformation.

On Databricks you write exactly this code in a notebook cell, and display(df) shows a sortable table instead of show(). The data usually comes from a table (spark.table("sales.orders")) or cloud storage (an s3:// or abfss:// path) rather than a local CSV, but the DataFrame code does not change. Module 13 reruns this module's code on a free Databricks workspace.

Numbers to remember

Setting or nameDefault or valueWhat to know
spark.driver.maxResultSize1gCaps the serialized results of one action. 0 means no limit, which turns the abort into a driver out-of-memory error.
One 4-column row in Pythonabout 202 bytesOn a 64-bit CPython 3.12. 10 million rows is about 2 GB on the driver.
spark.sql.files.maxPartitionBytes128 MBThe most file data one input partition holds; one task runs per partition.
Spark ConnectSpark 3.4 and laterThe client sends an unresolved plan over gRPC, so names are checked at the action.
[UNRESOLVEDCOLUMN.WITHSUGGESTION]SQLSTATE 42703The error for a misspelled column.
Output on this pageNone, bigintReal Spark prints NULL and says integer; show() here also centres values.
Optimiser rules at the actionCollapseProject, PushPredicateThroughNonJoinMerge neighbouring projections, and move a filter below them. Lesson 12.7 follows the rest of Catalyst.

What changed at SwiftKart

The clickstream script is now a PySpark notebook. It reads, filters and counts with the same kind of lines you ran here, and on Databricks the work is spread over the cluster's machines, so no single machine has to hold 2 billion events. The report is back by 9:00.

One habit came with it: the notebook never collect()s the events. It writes its counts to a table, and brings back only the few numbers it prints.

Next, Lesson 11.2: Tess's first question for the new engine needs a join and a sum, and the answer comes out $91.25 too high.

In one line

A DataFrame never changes and never runs early: each step returns a new one, and only an action such as count() makes Spark do the work.

Interview corner

What is a SparkSession?

It is the entry point to Spark: you use it to read data, create DataFrames, run SQL and set configuration. SparkSession.builder.getOrCreate() returns the existing session or makes one, so a program has one session. On Databricks it already exists as spark.

What is the difference between a transformation and an action?

Transformations such as select, filter, withColumn, join and groupBy are lazy: they return a new DataFrame and only add a step to the plan. Actions such as count, collect, show and write make Spark run the plan and return or save a result. Because nothing runs until an action, Spark can optimise the whole plan first.

Why is collect() dangerous on a large DataFrame?

It brings every row from the executors back to one process. Spark first guards the serialized size with spark.driver.maxResultSize (1 GiB by default) and aborts the job past it; below that, the rows still have to fit in the driver as Python objects, about 200 bytes for a small 4-column row on a 64-bit CPython, so 40 million rows is roughly 8 GB. Raising the limit only turns the abort into an out-of-memory error. Collect aggregates or a limit(), and write big results to storage.

What happens between `df.filter(...)` and the first result coming back?

The filter adds a Filter node to the logical plan; classic PySpark analyses it at once, so a misspelled column fails on that line, while Spark Connect analyses only when the schema or data is needed. At the action, Catalyst optimises the plan (pushing filters down, pruning columns), picks a physical plan and generates Java code per stage. The driver splits the input into partitions, by default up to 128 MB of file data each (spark.sql.files.maxPartitionBytes), and runs one task per partition on executor cores. Each task streams its rows through the generated code and returns a partial result; Python only sends the plan and receives the answer.