Skip to content
Silver 4 min read · Arrays 2 practice problems ↓

collect_list / collect_set

Sometimes you want the opposite of explode: all of a customer's products in one list, all the pages a user visited in one session. collect_list and collect_set build those arrays per group. This lesson shows both, why the order of the list is not guaranteed, and why collecting can run out of memory.

Step 1 · PySpark functions · Silver · Arrays and nested data, lesson 3 of 5

Read first: groupBy + agg (skip if you know it)

In plain words first

At the end of a shopping day, you gather all of one customer's receipts and staple them into a single bundle. A list keeps every receipt, even repeats; a set keeps each distinct item once. Either way the bundle has to fit in one hand, which is why collecting a huge group can fail.

What it does

It is the reverse of explodeexplode: Turn each element of an array into a row of its own, copying the other columns. Learn more →: many rows in, one arrayarray: A column that holds a list of values in each row, such as the items of one order. Learn more → per group out.

Step by step

visits

userpage
u1home
u1search
u1home
u2cart
u2nullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more →

Output

userpagesdistinct_pages
u1[home, search, home][home, search]
u2[cart][cart]

The null page for u2 is skipped by both. collect_set drops the second "home".

Run the example

PySparkSpark SQL

Input: visits

usertspage
u110:00home
u110:02search
u110:05home
u211:00cart
u211:03null
from pyspark.sql import functions as F
result = (visits.groupBy("user").agg(
    F.collect_list("page").alias("pages"),
    F.collect_set("page").alias("distinct_pages"),
    F.size(F.collect_set("page")).alias("n_distinct"),
))
SELECT user,
       collect_list(page)        AS pages,
       collect_set(page)         AS distinct_pages,
       size(collect_set(page))   AS n_distinct
FROM visits
GROUP BY user

Getting a reliable order

collect_list adds values in whatever order rows reach the aggregationaggregate: A function that turns many rows into one value per group: count, sum, avg, min, max. Learn more →, which depends on partitioning and shuffleshuffle: Moving rows between machines so that all rows with the same key end up together. Needed by joins, groupBy and sorting, and usually the most expensive step of a job. Learn more → timing. Sorting the DataFrameDataFrame: A table of rows and named columns that Spark processes in parallel. It never changes: every operation returns a new one. Learn more → first does not fix that, because the groupBy shuffle reorders rows. Two reliable options:

  1. Collect structsstruct: A column that holds a small record with named fields, like an address with a city and a pin code. Learn more → whose first field is the sort key, then sort the array: F.sort_array(F.collect_list(F.struct("ts", "page"))), and take .page from the result. Structs sort by their fields in order.
  2. Use a window ordered by time with a full framewindow frame: The rows around the current one that a window function looks at, such as "the previous 6 rows" or "the last 7 days". Learn more →, and collect_list over it, then deduplicate to one row per group.
Tip: Spark SQL also accepts array_agg, the SQL-standard name for collect_list, in recent versions. It has the same ordering caveat; the struct-and-sort trick works everywhere.

Under the hood: memory Optional deep dive

Most aggregations shrink data before the shuffle: a sum is one number per group. collect_list cannot; the partial result is the whole list. Every value is shuffled, and the complete array for a group must fit in one tasktask: The work for one partition in one stage, run on one CPU core. Learn more →'s memory. A single user with 50 million events produces one 50-million-element array and, often, an out-of-memory error. Collect only what you need, cap it with slice, or rethink whether you need the array at all.

Common mistakes

  • Relying on collect_list order — Sort explicitly with structs and sort_array.
  • Sorting before groupBy and expecting it to stick — The shuffle destroys that order.
  • Collecting huge groups — Skewedskew: When one key has far more rows than the others, so one task does most of the work while the rest wait. Learn more → keys produce giant arrays and OOM errors.

Key takeaways

  • collect_list keeps duplicates; collect_set removes them. Both skip nulls.
  • Neither guarantees order, even after an orderBy.
  • Collect structs and sort_array them for a deterministic order.
  • Collecting shuffles every value and holds each group's array in memory.

Interview prep

THE QUESTION

"Build each user's page path in time order."

sort_array(collect_list(struct(ts, page))), then extract the page field, with a note that a plain collect_list after orderBy is not guaranteed to be ordered. Bonus: warn about users with millions of events and suggest limiting to a session or a time range.

Avoid: orderBy then groupBy with collect_list, assuming the order survives. The shuffle does not preserve it.

Follow-ups · answer out loud, then open

Follow-up"Do collect_list and collect_set keep nulls?"
No. Both skip null values. collect_set also removes duplicates and gives no order.
Scenario"Some users have millions of events. collect_list per user fails with out-of-memory. What do you do?"
One array per user must fit in one task. Limit it (keep the last N with a window first), aggregate into counts instead of raw lists, or split by time (per user per day). Ask whether the consumer really needs the full list.
Trap"collect_list is cheap because it is just an aggregation."
It cannot be shrunk by partial aggregation: the partial result is as big as the input. It also uses object-based aggregation, which falls back to sorting when there are many keys.

Check yourself

3 questions

How do you get a guaranteed time-ordered list of pages per user?

Show the answer

sort_array(collect_list(struct("ts", "page"))). Structs sort by their first field, so sorting the collected structs orders by ts. A prior orderBy is lost in the shuffle.

A group has values a, b, null, a. What does collect_set return (in some order)?

Show the answer

[a, b]. collect_set removes duplicates and both collect functions skip nulls.

Why is collect_list risky on skewed data?

Show the answer

The full array of a huge group must fit in one task's memory. Partial aggregation cannot shrink a list, so a hot key builds one enormous array.

Practise this

Problems that use collect_list / collect_set, graded on hidden tests

Keep going

Up next · Arrays and nested data · lesson 4 of 5 · 4 min read
Array functions
array_contains, size, element_at, sort_array and the set functions, without exploding.

Related lessons

Previous: posexplode

Primary sources: functions.collect_list · functions.collect_set