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

  1. Data in rows or nested columns
  2. Do you need one row per entity with a list? Yes: groupBy + collect_list / collect_set. No: Keep rows.
  3. Do you need one row per array element? Yes: explode / explode_outer. No: Work on the array with size, array_contains, transform.
  4. Use struct to group related fields; read them with dot notation
  5. 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

Apache Spark topics

Spark Fundamentals

Spark Architecture

RDDs

DataFrames

Aggregations & Joins

Spark SQL

Window Functions

Cleaning & Complex Types

UDFs

Performance Tuning

Structured Streaming

MLlib & Ecosystem

Interview Prep

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Master Apache Spark

PySpark and Spark SQL from the ground up: DataFrames, joins, window functions, partitions and performance tuning, Structured Streaming and more. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice PySpark Write real PySpark — DataFrames, joins, window functions and Spark SQL — in a live editor with hidden tests and instant checking. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Spark  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

{{ sec.h }}

{{ sec.body }}

{{ sec.body }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
On screen — where to click

{{ rich.ui.title }}

{{ u.text }}
  1. {{ st.n }}{{ st.text }}
{{ rich.ui.title }}
{{ u.text }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
Want to run this yourself? Try the same API on Practice PySpark Online right in your browser, or run it locally after pip install pyspark (needs Java 17+), or paste it into a Databricks Free Edition notebook.
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic