Analysis

Every DataFrame call you chain, and every SQL string you hand to spark.sql, first becomes a tree of names Spark has not checked. The tree mentions a relation called order_items and a column called quantity, but nothing in it says whether either exists or what type the column holds. Analysis settles those questions. The driver walks the tree and resolves each name against the catalog, the registry of tables, views and functions your session knows about. No executor takes part.

Each arrow carries the current tree: unresolved into the Analyzer, resolved into the Optimizer, optimized into the Planner. The 3 middle phases run on the driver, and only the physical plan turns into tasks.
  • Unresolved plan (source, DataFrame calls or SQL)
  • Analyzer (transform, catalog lookups)
  • Optimizer (transform, rewrite rules)
  • Planner (transform, strategies)
  • Physical plan (consumer, tasks on executors)
  • Unresolved plan -> Analyzer
  • Analyzer -> Optimizer
  • Optimizer -> Planner
  • Planner -> Physical plan

What the analyzer fills in

Take a query that totals each order's line items, run against an order_items table whose quantity is an int and whose unit_price is a double. Calling explain(extended=True) prints the tree after every phase, and the first 2 trees show the analyzer's work.

query = """
SELECT
  order_id,
  SUM(quantity * unit_price) AS order_total
FROM order_items
GROUP BY order_id
"""
totals = spark.sql(query)
totals.explain(extended=True)
Parsed plan showsAnalyzed plan showsWhat the analyzer did
'UnresolvedRelation [order_items]Relation spark_catalog.default.order_items[...] parquetFound the table in the catalog and attached its columns and files
'quantityquantity#5Matched the name to a column of that table and gave it an ID
'SUM(...)sum(...)Found the function and resolved the type of its argument
('quantity * 'unit_price)(cast(quantity#5 as double) * unit_price#6)Cast the int side to double so both operands share a type
no schema lineorder_id: int, order_total: doubleWorked out the type of every output column

Watch for 2 marks. A leading apostrophe, as in 'quantity, means unresolved: a name with no column behind it yet. A # number, as in quantity#5, is an expression ID. Your session will print different numbers. What holds everywhere is that 2 columns printing the same name with different IDs are different columns, and every later phase tracks a column by its ID.

The cast in the fourth row is type coercion. Multiplication needs both operands to share a type, so the analyzer widens the int side to double. That cast exists in the analyzed plan and nowhere in your code, which makes the analyzed plan the first place to look when a comparison or a calculation behaves differently from what you wrote.

Analysis errors arrive before the action

The laziness lessons showed failures that wait for an action: the plan builds and the error appears once tasks run. Analysis keeps a different schedule. A DataFrame is analyzed when it is created, so a misspelled column raises an AnalysisException on the line that names it, before any job exists. When an error fires tells you which kind of mistake you are looking at.

Raised as the line runs
  • A column name the input does not have
  • A table or view missing from the catalog
  • A function name Spark does not recognize
  • In SQL, a selected column that is neither grouped nor aggregated
Raised at the action
  • A file deleted between planning and reading
  • A value that breaks a cast with spark.sql.ansi.enabled on
  • An executor running out of memory
  • A corrupt file in the input path

On a Spark Connect session the client sends the plan to the server without analyzing it, so the same misspelling raises at the first action or the first call that needs the schema.

Which call raises an exception, and at what moment?

from pyspark.sql import functions as F

orders = spark.table("orders")
completed = orders.filter(F.col("status") == "Completed")
totals = completed.groupBy("regoin").agg(F.sum("profit"))
rows = totals.collect()

Run the cell as written: it reads order_items, multiplies quantity by unit_price, and prints the first 5 rows. Then rename unit_price in the select to unit_prise and run again. The error arrives before show is reached, and it lists the columns it could have meant.

About this lesson

This section is part of the Catalyst Optimizer: Intermediate lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.