Nested and messy data
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 9:30 on Monday. Over the weekend Dana's team shipped an app update: each order event now carries a list of coupons next to its list of items. This morning Tess's app revenue for Sunday is almost three times what the payments say, and some orders are missing from it altogether. Nothing failed. Your job reads the events and turns both lists into rows.
You'll learn to
- Read nested JSON and reach fields inside structs
- Turn a list into rows with explode, and count what it makes
- Never cross two lists by accident
- Parse JSON text with from_json, and handle nulls and dates
Learn
An event is not a flat row
Before the coupons, look at what one event is. The app sends every tap as one line of JSON, and JSON nests. Spark keeps the nesting with three column types:
- struct: a small row inside a row, with named fields. SwiftKart's
deviceisstruct<os, app_version>. - array: a list of values of one type.
itemsis an array of structs, one per product in the event. - map: keys and values, for JSON whose keys change from row to row.
spark.read.json works these types out from the data, and printSchema() draws them as a tree. Nested data is not a mess to remove at once: it keeps one event as one row, the honest grain. You flatten only the parts a question needs.
Read the clickstream
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.getOrCreate()
events = spark.read.json("data/events.jsonl")
events.printSchema()
print("events:", events.count())
first = events.orderBy("event_id").first()
print(first["device"], first["items"])
A struct comes back to Python as a Row inside the row; a missing list comes back as None. Page views carry no items at all.
Reach into a struct
A struct field is a path: F.col('device.os'), or F.col('device')['os'], or F.col('device').getField('os'). All three mean the same.
Always give the result a name with .alias('os'). Depending on the engine, the column is otherwise called os or device.os, and a dot inside a column name is a pain in every later step.
On Databricks, select('device.*') turns every field of a struct into its own column. The browser engine does not support that star; name the fields you need, which is better practice anyway because a new field in the JSON cannot sneak into your table.
One event, as Spark sees it
One add-to-cart event drawn as a row: plain columns for its id, user, type and time, a device struct with two fields, and an items array holding one struct with a product id and a quantity.
Read it from the outside in: F.col("device.os") reaches "android". items is a list that could hold many elements, so you turn it into rows before you reach inside.
explode: one row per element
F.explode('items') turns a list into rows. An event with three items becomes three rows, each with one item and a copy of every other column you kept (event id, device, time). In the plan, the operator that does this is called Generate.
Two things change, and both bite:
- The grain changes. After the explode, one row is one item of an event. An event-level number, such as an order total, now appears once per item, so summing it counts it several times.
- Rows with a null or empty list disappear. A page view has no
items, soexplodemakes no row for it.F.explode_outerkeeps those rows, with a null item.
Step through three carts.
Three carts through explode
Three carts, with three items, one item and no items, are exploded one at a time: the first becomes three rows, the second one row, and the empty cart makes no row, four rows in all.
Before. Three carts, one row each. Cart 1 has three items, cart 2 has one, and cart 3 has none.
Cart 1. One row per element: three rows, each with
cart_id1 copied beside one item.Cart 2. One element, one row.
Cart 3. An empty list has no elements, so explode makes no row for it. Three carts became four rows, and a count of carts after the explode says 2, not 3.
Rows out is the sum of the list lengths: 3 + 1 + 0 = 4. The same three carts come back in the from_json example further down.
Explode the items: adds to cart by phone
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.getOrCreate()
events = spark.read.json("data/events.jsonl")
items = events.select(
"event_id",
"type",
F.col("device.os").alias("os"),
F.explode("items").alias("item"),
)
print("events:", events.count(), " item rows:", items.count())
adds = (
items.filter(F.col("type") == "add_to_cart")
.select("os", F.col("item.product_id").alias("product_id"), F.col("item.qty").alias("qty"))
.groupBy("os")
.agg(F.sum("qty").alias("adds"))
.orderBy("os")
)
for r in adds.collect():
print(r["os"], r["adds"])
The select keeps only what the question needs before the explode. Then each item is a struct, so item.product_id and item.qty reach inside it.
Keeping the empty rows with explode_outer (Databricks)
Runs on Databricks:
from pyspark.sql import functions as F
events = spark.read.json("/Volumes/main/swiftkart/raw/events.jsonl")
print(events.select("event_id", F.explode("items").alias("item")).count())
print(events.select("event_id", F.explode_outer("items").alias("item")).count())
111
192
explode_outer keeps the 81 events with no items, with a null item. The browser engine does not have explode_outer; in this course, run the explode and remember which rows it dropped.
Remember: rows out = the sum of the list lengths. A null or empty list adds nothing, so its row is gone.
Under the hood: rows and bytes
Generate emits one row per element, each with a copy of every other column you kept. So you can size an explode before you run it:
- Rows out = the sum of the list lengths. SwiftKart's 2 billion events a month, 40% of them with 3 items on average, become 0.4 x 2 billion x 3 = 2.4 billion rows. The 1.2 billion events without items vanish.
- Bytes out = rows out x (the kept columns + one element). Keep a 300-byte
user_agentstring beside a 16-byte item, and 2.4 billion rows carry 720 GB of copied text into the shuffle.
So select the columns you need before the explode.
Adds to cart by phone, as Spark plans it on Parquet
A plan tree: a project over a Generate explode, over a filter that includes the inferred isnotnull and size conditions, over a Parquet scan whose read schema holds only the nested fields the query uses.
Read it bottom up. Two savings come free: the rule InferFiltersFromGenerate adds the null and size checks, so rows that would make nothing go early, and nested schema pruning (spark.sql.optimizer.nestedSchemaPruning.enabled, on by default, for Parquet and ORC) reads only device.os, not the whole device struct. Raw JSON text gets no such pruning: every line is parsed whole, one more reason to land JSON once and query Parquet or Delta.
Why Sunday tripled: two lists, crossed
Explode items, then explode coupons, and every item is paired with every coupon. With 3 coupons, each item appears three times, so revenue summed over those rows triples. An order with no coupons makes no row at all in the second explode, so it vanishes. That is Tess's Sunday: almost three times too high, and short of some orders.
The mistake no longer fails loudly. Spark 3.5 refuses two generators in one select (UNSUPPORTED_GENERATOR.MULTI_GENERATOR); Spark 4.0 allows it and returns the cross product. Chained withColumn explodes, like the job's, cross on every version.
Watch the cross product
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.getOrCreate()
orders = spark.createDataFrame([
(1, [101, 103, 110, 104], ["SPRING", "VIP", "FREESHIP"]),
(2, [107, 102], []),
(3, [105], ["VIP", "WELCOME"]),
], "order_id INT, items ARRAY<INT>, coupons ARRAY<STRING>")
by_item = orders.withColumn("item", F.explode("items"))
crossed = by_item.withColumn("coupon", F.explode("coupons"))
print("orders:", orders.count(), " after items:", by_item.count(), " after items then coupons:", crossed.count())
print("order 1 rows:", crossed.filter(F.col("order_id") == 1).count())
coupons = orders.select("order_id", F.explode("coupons").alias("coupon"))
print("child tables instead:", by_item.count(), "item rows +", coupons.count(), "coupon rows")
print([tuple(r) for r in orders.select("order_id", F.posexplode("items")).filter(F.col("order_id") == 2).collect()])
Order 1 makes 4 x 3 = 12 rows; order 2 has no coupons, so it vanishes from crossed altogether. Two child tables hold 7 + 5 = 12 rows that mean what they say. (arrays_zip runs here too, but its struct fields are named differently from Spark's, so it is left out.)
Two lists, two tables
The fix depends on what the two lists mean.
- Parallel lists, where element i of one belongs with element i of the other: zip them, then explode once.
F.explode(F.arrays_zip('a', 'b'))makes one row per position and pads the shorter list with nulls.posexplodeadds the position if you need it. - Independent lists, like items and coupons: write two child tables,
order_itemsandorder_coupons, each keyed byorder_id, and sum each one before any join.
A coupon does not belong to one item, so SwiftKart's lists are independent: two tables.
Rows after each step, for 50 million order events
Bars compare 50 million events, 200 million rows after exploding items, 600 million after also exploding coupons, and 350 million rows in two separate child tables.
With 4 items and 3 coupons per event: 50 M x 4 = 200 M rows, then x 3 = 600 M. The two child tables hold 50 M x 4 + 50 M x 3 = 350 M rows, none of them wrong.
JSON inside a string column
Payment webhooks, Kafka messages and API logs often arrive as JSON text in one column. F.from_json(col, schema) parses that text into a struct, using a schema you give as a DDL string:
schema = 'order_id INT, event STRING, amount DOUBLE, card STRUCT<brand: STRING, last4: STRING>'
parsed = raw.withColumn('j', F.from_json('body', schema))
Then reach the fields as before: F.col('j.card.brand'). An array works too: 'ARRAY<STRUCT<product_id: INT, qty: INT>>', followed by an explode.
On real Spark, text that is not valid JSON, or that lacks a field, gives null for it. The browser engine is stricter and stops with an error, so the examples here use complete JSON.
Parse webhook bodies and cart lists
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.getOrCreate()
raw = spark.createDataFrame([
(1, '{"order_id": 1012, "event": "payment_failed", "amount": 142.44, "card": {"brand": "visa", "last4": "4242"}}'),
(2, '{"order_id": 1013, "event": "payment_captured", "amount": 109.30, "card": {"brand": "mastercard", "last4": "5100"}}'),
(3, '{"order_id": 1033, "event": "payment_captured", "amount": 91.25, "card": {"brand": "amex", "last4": "0005"}}'),
], "id INT, body STRING")
schema = "order_id INT, event STRING, amount DOUBLE, card STRUCT<brand: STRING, last4: STRING>"
parsed = raw.withColumn("j", F.from_json("body", schema)).select(
F.col("j.order_id").alias("order_id"),
F.col("j.event").alias("event"),
F.col("j.card.brand").alias("brand"),
)
for r in parsed.orderBy("order_id", "event").collect():
print(r["order_id"], r["event"], r["brand"])
carts = spark.createDataFrame([
(1, '[{"product_id": 101, "qty": 2}, {"product_id": 103, "qty": 1}, {"product_id": 110, "qty": 1}]'),
(2, '[{"product_id": 107, "qty": 1}]'),
(3, '[]'),
], "cart_id INT, body STRING")
lines = (
carts.withColumn("items", F.from_json("body", "ARRAY<STRUCT<product_id: INT, qty: INT>>"))
.select("cart_id", F.explode("items").alias("item"))
)
print("carts:", carts.count(), " cart lines:", lines.count())
The cart lists are the three carts from the walkthrough: three carts, four cart lines.
Nulls and dates
Nulls behave as in SQL. F.col('user_id') == None is never true; write .isNull() or .isNotNull(). F.count('user_id') and F.countDistinct skip nulls. F.coalesce(a, b) takes the first non-null value, the usual way to set a default. (fillna does the same on Databricks; in the browser engine a later filter or groupBy can still see the nulls, so use coalesce here.)
Dates: F.to_date(ts) keeps the day, F.date_format(ts, 'yyyy-MM-dd') makes text, and F.hour(ts), F.dayofweek(ts) and F.datediff(end, start) do what they say. Store and compare times in UTC. On Databricks, spark.read.json leaves a timestamp like 2025-06-01T08:14:34Z as a string unless you give a schema, so add F.to_timestamp('ts').
Anonymous visitors and daily users
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.getOrCreate()
events = spark.read.json("data/events.jsonl")
print("anonymous events:", events.filter(F.col("user_id").isNull()).count())
print("== None finds:", events.filter(F.col("user_id") == None).count())
labelled = events.withColumn("who", F.coalesce(F.col("user_id").cast("string"), F.lit("anonymous")))
print("labelled anonymous:", labelled.filter(F.col("who") == "anonymous").count())
daily = (
events.groupBy(F.date_format("ts", "yyyy-MM-dd").alias("day"))
.agg(
F.count("*").alias("events"),
F.countDistinct("user_id").alias("users"),
)
.orderBy("day")
)
for r in daily.collect():
print(r["day"], r["events"], r["users"])
countDistinct("user_id") ignores the anonymous rows on its own, because null is not a value it counts.
The trap: explode changes the grain, and drops rows. After explode("items"), an event-level number such as a session length or an order total appears once per item, so a sum counts it several times. And events with an empty or missing list vanish, so "events after explode" is not the number of events. Aggregate event-level facts before you explode, and count rows before and after.
Numbers to remember
| Setting or rule | Default or value | What to know |
|---|---|---|
| spark.sql.optimizer.nestedSchemaPruning.enabled | true | Parquet and ORC read only the nested fields a query uses. Raw JSON is parsed whole. |
| InferFiltersFromGenerate | an optimiser rule | Adds isnotnull(items) AND size(items) 0 below an inner explode; explodeouter gets no such filter. |
| Two generators in one select | Spark 3.5: an error. Spark 4.0: a cross product. | The error is UNSUPPORTEDGENERATOR.MULTIGENERATOR. Chained explodes cross on every version. |
| fromjson on bad text | null | In the default PERMISSIVE mode; count the nulls after parsing. The browser engine raises an error instead. |
| JSON timestamps on Databricks | read as strings | Without a schema, 2025-06-01T08:14:34Z stays text: add F.totimestamp. The browser engine reads it as a timestamp. |
What changed at SwiftKart
The job no longer explodes both lists in one chain. It writes two child tables, order_items and order_coupons, each keyed by order_id, and sums each before any join. Sunday's app revenue matches the payments again, and the orders without coupons are back.
Two checks went into the job: a row count before and after every explode, and a short list of the columns kept before it. The raw JSON still lands as it arrived, in bronze, and the parsed tables are silver, so the next app update cannot break them silently (Module 13).
Next, Lesson 11.5: the files themselves. A CSV carries no types, and one option missing from a read can change a price.
In one line
Reach struct fields with F.col("a.b").alias(...), turn a list into rows with explode (it changes the grain and drops empty lists), never explode two lists in a row, and parse JSON text with from_json and a schema.
Interview corner
What is the difference between explode and explode_outer?
Both turn each element of an array (or map) into its own row, repeating the other columns. explode produces no row for a null or empty array, so those records disappear; explode_outer keeps them with a null element. Use explode_outer when the parent row must survive, for example events without items in a funnel count.
How do you parse a column of JSON strings?
Use F.from_json(col, schema) with an explicit schema (a StructType or a DDL string), which returns a struct you can reach with dot paths; then alias the fields you need and explode any arrays. Giving the schema keeps types stable and makes unexpected input visible: on Spark, malformed records parse to null in the default PERMISSIVE mode, so count the nulls after parsing.
Why does `F.col("x") == None` not find null rows?
Spark follows SQL three-valued logic: comparing anything with null gives null, and filter keeps only rows where the condition is true. So the filter keeps nothing. Use isNull() or isNotNull(), and F.coalesce to replace nulls with a default.
An order event has 4 items and 3 coupons, and you explode both. What do you get, and how should it be modelled?
A cross product: 12 rows per event, every item repeated per coupon, and events with no coupons dropped, so any sum over items triples. Spark 3.5 rejects two generators in one select, but Spark 4.0 accepts it and chained withColumn explodes always cross, so nothing fails. If the arrays are parallel, explode arrays_zip of them (one row per position, nulls padding the shorter); if they are independent, write two child tables keyed by order_id and aggregate each before joining. And size it first: rows out is the sum of the array sizes, times the bytes of every column you carry along.