Arrays, Maps & Structs
Apache Spark · Cleaning & Complex Types
Theory
Spark columns can hold complex types. An array is an ordered list of values of one type (products bought in a session), a map holds key-value pairs (attribute name to value), and a struct is a nested record with named fields (an address with city and pin). You build them with F.array, F.create_map and F.struct, or by aggregating: F.collect_list("product") gathers values per group into an array (keeps duplicates) and F.collect_set removes duplicates. Read struct fields with F.col("address.city").
F.explode("products") goes the other way: it turns one row with an array of three items into three rows, one per item (explode_outer keeps rows whose array is null or empty, posexplode adds the position). Useful helpers are F.size, F.array_contains, F.element_at, F.array_distinct, F.sort_array, F.map_keys and higher-order functions F.transform and F.filter, which apply a lambda to each element without a UDF.
Why we use it
JSON, event and API data are naturally nested, and many outputs need lists per entity (all products per customer). Complex types let you keep that structure, while explode and collect_list convert between one-row-per-item and one-row-per-entity shapes without Python code.
When to use it
Use collect_list/collect_set to build lists per key, explode to flatten arrays before joining or counting, structs to group related fields and to pick whole rows with max(struct). Avoid collect_list on huge groups: the whole array must fit in one row in executor memory.
How it works
- Data in rows or nested columns
- Do you need one row per entity with a list? Yes: groupBy + collect_list / collect_set. No: Keep rows.
- Do you need one row per array element? Yes: explode / explode_outer. No: Work on the array with size, array_contains, transform.
- Use struct to group related fields; read them with dot notation
- Shape fits the next join or report
Syntax
F.collect_list("product"); F.collect_set("product")
F.explode("items"); F.explode_outer("items"); F.posexplode("items")
F.struct("city", "segment").alias("info"); F.col("info.city")
F.create_map(F.lit("k"), F.col("v")); F.element_at("m", "k")
F.transform("arr", lambda x: x * 2); F.filter("arr", lambda x: x > 0)Example
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.appName("techtown-spark").getOrCreate()
orders = spark.createDataFrame([
(1, 101, "North", "Laptop", 1, 55000.0, "2026-01-05"),
(2, 102, "West", "Phone", 2, 30000.0, "2026-01-06"),
(3, 101, "North", "Mouse", 3, 1500.0, "2026-01-07"),
(4, 103, "South", "Laptop", 1, 52000.0, "2026-01-07"),
(5, 102, "West", "Tablet", 1, 25000.0, "2026-01-09"),
(6, 104, "North", "Phone", 1, 18000.0, "2026-01-10"),
(7, 103, "South", "Mouse", 2, 1000.0, "2026-01-11"),
(8, 105, "West", "Laptop", 1, 60000.0, "2026-01-12"),
], "order_id INT, customer_id INT, region STRING, product STRING, qty INT, amount DOUBLE, order_date STRING"
).withColumn("order_date", F.to_date("order_date"))
customers = spark.createDataFrame([
(101, "Asha", "Jaipur", "Retail"),
(102, "Ravi", "Pune", "Corporate"),
(103, "Meera", "Delhi", "Retail"),
(104, "Karan", "Jaipur", "SMB"),
(105, "Priya", "Mumbai", "Corporate"),
], "customer_id INT, name STRING, city STRING, segment STRING")
# One row per customer with an array of products and a struct of details
baskets = (orders.groupBy("customer_id")
.agg(F.collect_list("product").alias("products"),
F.sum("amount").alias("total"))
.join(customers, "customer_id")
.select("customer_id",
F.struct("name", "city", "segment").alias("info"),
"products",
F.size("products").alias("n_items"),
F.array_contains("products", "Laptop").alias("bought_laptop"),
"total"))
baskets.orderBy("customer_id").show(truncate=False)
# Read a struct field and explode the array back to rows
(baskets.select(F.col("info.name").alias("name"), F.explode("products").alias("product"))
.orderBy("name", "product").show())
# Map column and higher-order function
(baskets.select("customer_id",
F.create_map(F.lit("city"), F.col("info.city"), F.lit("segment"), F.col("info.segment")).alias("attrs"),
F.transform("products", lambda p: F.upper(p)).alias("products_upper"))
.orderBy("customer_id").show(truncate=False))
# Output:
# +-----------+--------------------------+---------------+-------+-------------+-------+
# |customer_id|info |products |n_items|bought_laptop|total |
# +-----------+--------------------------+---------------+-------+-------------+-------+
# |101 |{Asha, Jaipur, Retail} |[Laptop, Mouse]|2 |true |56500.0|
# |102 |{Ravi, Pune, Corporate} |[Phone, Tablet]|2 |false |55000.0|
# |103 |{Meera, Delhi, Retail} |[Laptop, Mouse]|2 |true |53000.0|
# |104 |{Karan, Jaipur, SMB} |[Phone] |1 |false |18000.0|
# |105 |{Priya, Mumbai, Corporate}|[Laptop] |1 |true |60000.0|
# +-----------+--------------------------+---------------+-------+-------------+-------+
#
# +-----+-------+
# | name|product|
# +-----+-------+
# | Asha| Laptop|
# | Asha| Mouse|
# |Karan| Phone|
# |Meera| Laptop|
# |Meera| Mouse|
# |Priya| Laptop|
# | Ravi| Phone|
# | Ravi| Tablet|
# +-----+-------+
#
# +-----------+--------------------------------------+---------------+
# |customer_id|attrs |products_upper |
# +-----------+--------------------------------------+---------------+
# |101 |{city -> Jaipur, segment -> Retail} |[LAPTOP, MOUSE]|
# |102 |{city -> Pune, segment -> Corporate} |[PHONE, TABLET]|
# |103 |{city -> Delhi, segment -> Retail} |[LAPTOP, MOUSE]|
# |104 |{city -> Jaipur, segment -> SMB} |[PHONE] |
# |105 |{city -> Mumbai, segment -> Corporate}|[LAPTOP] |
# +-----------+--------------------------------------+---------------+
Key points
- collect_list keeps duplicates and has no guaranteed order; collect_set removes duplicates
- explode drops rows with null or empty arrays; explode_outer keeps them
- Access struct fields with dot notation: col('info.city')
- transform / filter / aggregate apply lambdas to arrays without a Python UDF
- Huge collect_list groups can run executors out of memory