๐งบ Arrays, Maps & Structs
Not all data fits in flat columns. A shopping cart holds a list of items, a user profile holds key-value settings, and an address is a small record inside a row. Spark SQL stores these as arrays, maps and structs, and this tutorial shows how to create them, read from them, and flatten them into ordinary rows.
You meet these types constantly when reading JSON, Parquet and event data. Every query below runs on Spark 3.5 and shows its exact result.
1. Sample Data
carts has an array of items and a matching array of prices. Chen's cart is empty and Divya's is NULL, because these two cases behave differently:
CREATE OR REPLACE TEMP VIEW carts AS
SELECT * FROM VALUES
(1, 'Asha', array('laptop', 'mouse', 'mouse'), array(900, 20, 20)),
(2, 'Ben', array('phone', 'case'), array(500, 15)),
(3, 'Chen', CAST(array() AS ARRAY<STRING>), CAST(array() AS ARRAY<INT>)),
(4, 'Divya', NULL, NULL)
AS carts(cart_id, customer, items, prices)
users has a struct for the address and a map of preferences:
CREATE OR REPLACE TEMP VIEW users AS
SELECT * FROM VALUES
(1, 'Asha', named_struct('city', 'Pune', 'pin', '411001'), map('theme', 'dark', 'lang', 'en')),
(2, 'Ben', named_struct('city', 'Mumbai', 'pin', '400050'), map('theme', 'light')),
(3, 'Chen', NULL, map('lang', 'hi'))
AS users(user_id, name, address, prefs)
SELECT * FROM carts ORDER BY cart_id
+-------+--------+----------------------+-------------+
|cart_id|customer|items |prices |
+-------+--------+----------------------+-------------+
|1 |Asha |[laptop, mouse, mouse]|[900, 20, 20]|
|2 |Ben |[phone, case] |[500, 15] |
|3 |Chen |[] |[] |
|4 |Divya |NULL |NULL |
+-------+--------+----------------------+-------------+
2. The Three Complex Types
| Type | Holds | Create with | Read with |
|---|---|---|---|
ARRAY<T> | An ordered list of values of one type | array(1, 2, 3) | arr[0], element_at(arr, 1) |
MAP<K, V> | Key-value pairs | map('a', 1, 'b', 2) | m['a'], element_at(m, 'a') |
STRUCT<...> | Named fields, like a mini row | named_struct('city', 'Pune', 'pin', '411001') | s.city |
SELECT array(1, 2, 3) AS an_array,
map('a', 1, 'b', 2) AS a_map,
named_struct('city', 'Pune', 'pin', '411001') AS a_struct
+---------+----------------+--------------+
|an_array |a_map |a_struct |
+---------+----------------+--------------+
|[1, 2, 3]|{a -> 1, b -> 2}|{Pune, 411001}|
+---------+----------------+--------------+
Check the types with DESCRIBE:
DESCRIBE users
+--------+------------------------------+-------+
|col_name|data_type |comment|
+--------+------------------------------+-------+
|user_id |int |NULL |
|name |string |NULL |
|address |struct<city:string,pin:string>|NULL |
|prefs |map<string,string> |NULL |
+--------+------------------------------+-------+
3. Reading Arrays: Index, size, array_contains
SELECT customer,
items,
items[0] AS first_item,
element_at(items, -1) AS last_item,
size(items) AS item_count,
array_contains(items, 'mouse') AS has_mouse
FROM carts
ORDER BY cart_id
+--------+----------------------+----------+---------+----------+---------+
|customer|items |first_item|last_item|item_count|has_mouse|
+--------+----------------------+----------+---------+----------+---------+
|Asha |[laptop, mouse, mouse]|laptop |mouse |3 |true |
|Ben |[phone, case] |phone |case |2 |false |
|Chen |[] |NULL |NULL |0 |false |
|Divya |NULL |NULL |NULL |-1 |NULL |
+--------+----------------------+----------+---------+----------+---------+
items[0]uses a 0-based index;element_at(items, 1)is 1-based, and negative numbers count from the end.- Asking for an element that does not exist returns
NULL(Chen's empty cart) instead of failing. array_containschecks whether a value is in the array.
Common mistake:
size()of aNULLarray returns -1, notNULLor 0, with Spark 3.5's default settings. Divya'sitem_countabove shows this. If you sum or compare sizes, usesize(coalesce(items, array()))or filter outNULLarrays first.
4. Array Set Functions
These functions treat arrays like sets or lists:
SELECT array_distinct(items) AS distinct_items,
array_sort(items) AS sorted_items,
sort_array(items, false) AS sorted_desc,
array_union(items, array('bag')) AS with_bag,
array_intersect(items, array('mouse', 'pen')) AS in_both,
array_except(items, array('mouse')) AS without_mouse,
array_join(items, ', ') AS as_text
FROM carts
WHERE cart_id = 1
+---------------+----------------------+----------------------+--------------------+-------+-------------+--------------------+
|distinct_items |sorted_items |sorted_desc |with_bag |in_both|without_mouse|as_text |
+---------------+----------------------+----------------------+--------------------+-------+-------------+--------------------+
|[laptop, mouse]|[laptop, mouse, mouse]|[mouse, mouse, laptop]|[laptop, mouse, bag]|[mouse]|[laptop] |laptop, mouse, mouse|
+---------------+----------------------+----------------------+--------------------+-------+-------------+--------------------+
| Function | Returns |
|---|---|
array_distinct(a) | a without duplicates |
array_sort(a) / sort_array(a, asc) | a sorted (sort_array can sort descending) |
array_union(a, b) | Distinct values from both |
array_intersect(a, b) | Distinct values in both |
array_except(a, b) | Distinct values in a but not in b |
array_join(a, sep) | One string with the elements joined |
Notice that array_union, array_intersect and array_except also remove duplicates, so "mouse" appears only once in with_bag.
5. One Row per Element: explode
explode turns each array element into its own row. This is how you flatten nested data into a normal table:
SELECT customer,
explode(items) AS item
FROM carts
ORDER BY customer, item
+--------+------+
|customer|item |
+--------+------+
|Asha |laptop|
|Asha |mouse |
|Asha |mouse |
|Ben |case |
|Ben |phone |
+--------+------+
Asha's three items became three rows. But Chen (empty array) and Divya (NULL) disappeared, because there was nothing to explode.
explode_outer keeps those rows, with a NULL item:
SELECT customer,
explode_outer(items) AS item
FROM carts
ORDER BY customer, item
+--------+------+
|customer|item |
+--------+------+
|Asha |laptop|
|Asha |mouse |
|Asha |mouse |
|Ben |case |
|Ben |phone |
|Chen |NULL |
|Divya |NULL |
+--------+------+
posexplode also returns each element's position (starting at 0). It is useful for pairing two arrays that line up, such as items and prices:
SELECT customer,
pos,
item,
prices[pos] AS price
FROM (SELECT customer, prices, posexplode(items) AS (pos, item) FROM carts)
ORDER BY customer, pos
+--------+---+------+-----+
|customer|pos|item |price|
+--------+---+------+-----+
|Asha |0 |laptop|900 |
|Asha |1 |mouse |20 |
|Asha |2 |mouse |20 |
|Ben |0 |phone |500 |
|Ben |1 |case |15 |
+--------+---+------+-----+
Common mistake: Using
explodewhen some rows have empty orNULLarrays, then wondering why customers vanished from a report. If every parent row must survive, useexplode_outer.
6. LATERAL VIEW: The Other Way to Explode
You will often see Hive-style LATERAL VIEW syntax in existing code. It puts the explode in the FROM clause, which reads well when you explode more than one thing:
SELECT c.customer, t.item
FROM carts c
LATERAL VIEW explode(c.items) t AS item
ORDER BY c.customer, t.item
+--------+------+
|customer|item |
+--------+------+
|Asha |laptop|
|Asha |mouse |
|Asha |mouse |
|Ben |case |
|Ben |phone |
+--------+------+
t is a name for the generated table and item names its column. LATERAL VIEW OUTER works like explode_outer and keeps empty and NULL arrays:
SELECT c.customer, t.item
FROM carts c
LATERAL VIEW OUTER explode(c.items) t AS item
ORDER BY c.customer, t.item
+--------+------+
|customer|item |
+--------+------+
|Asha |laptop|
|Asha |mouse |
|Asha |mouse |
|Ben |case |
|Ben |phone |
|Chen |NULL |
|Divya |NULL |
+--------+------+
7. Building Arrays: collect_list and collect_set
The opposite of explode is aggregation into an array:
collect_list(col)gathers all values in a group, keeping duplicates.collect_set(col)gathers distinct values.
SELECT customer,
array_sort(collect_list(item)) AS all_items,
array_sort(collect_set(item)) AS unique_items,
count(*) AS item_rows
FROM carts
LATERAL VIEW explode(items) t AS item
GROUP BY customer
ORDER BY customer
+--------+----------------------+---------------+---------+
|customer|all_items |unique_items |item_rows|
+--------+----------------------+---------------+---------+
|Asha |[laptop, mouse, mouse]|[laptop, mouse]|3 |
|Ben |[case, phone] |[case, phone] |2 |
+--------+----------------------+---------------+---------+
Common mistake: Expecting
collect_listto keep the original order. Rows can arrive in any order after a shuffle, so the array order is not guaranteed. Wrap it inarray_sort(as above) when the order matters, or sort by a position column before collecting.
8. Structs: Records Inside a Row
Read a struct field with a dot, like address.city. address.* expands every field into its own column:
SELECT name,
address.city AS city,
address.pin AS pin
FROM users
ORDER BY user_id
+----+------+------+
|name|city |pin |
+----+------+------+
|Asha|Pune |411001|
|Ben |Mumbai|400050|
|Chen|NULL |NULL |
+----+------+------+
SELECT name, address.*
FROM users
ORDER BY user_id
+----+------+------+
|name|city |pin |
+----+------+------+
|Asha|Pune |411001|
|Ben |Mumbai|400050|
|Chen|NULL |NULL |
+----+------+------+
Chen's address is NULL, so every field of it is NULL too. Structs are common in JSON data, where an object inside an object becomes a struct column.
9. Maps: Key-Value Pairs
Look up a key with m['key'] or element_at(m, 'key'). A missing key returns NULL:
SELECT name,
prefs['theme'] AS theme,
element_at(prefs, 'lang') AS lang,
map_keys(prefs) AS all_keys,
map_values(prefs) AS all_values,
size(prefs) AS pref_count
FROM users
ORDER BY user_id
+----+-----+----+-------------+----------+----------+
|name|theme|lang|all_keys |all_values|pref_count|
+----+-----+----+-------------+----------+----------+
|Asha|dark |en |[theme, lang]|[dark, en]|2 |
|Ben |light|NULL|[theme] |[light] |1 |
|Chen|NULL |hi |[lang] |[hi] |1 |
+----+-----+----+-------------+----------+----------+
Exploding a map gives two columns, key and value, with one row per pair. This turns flexible key-value data into regular rows:
SELECT name, key, value
FROM users
LATERAL VIEW explode(prefs) p AS key, value
ORDER BY name, key
+----+-----+-----+
|name|key |value|
+----+-----+-----+
|Asha|lang |en |
|Asha|theme|dark |
|Ben |theme|light|
|Chen|lang |hi |
+----+-----+-----+
10. Higher-Order Functions: Work Inside Arrays
Higher-order functions run a small lambda function on each element, without exploding the array. A lambda is written x -> expression.
| Function | What it does |
|---|---|
transform(a, x -> ...) | Change every element |
filter(a, x -> ...) | Keep elements where the condition is true |
exists(a, x -> ...) | True if any element matches |
aggregate(a, start, (acc, x) -> ...) | Fold the array into one value |
SELECT customer,
transform(items, x -> upper(x)) AS upper_items,
transform(prices, p -> p * 1.18) AS with_tax,
filter(prices, p -> p >= 100) AS big_prices,
exists(items, x -> x = 'phone') AS has_phone,
aggregate(prices, 0, (acc, p) -> acc + p) AS cart_total
FROM carts
ORDER BY cart_id
+--------+----------------------+-----------------------+----------+---------+----------+
|customer|upper_items |with_tax |big_prices|has_phone|cart_total|
+--------+----------------------+-----------------------+----------+---------+----------+
|Asha |[LAPTOP, MOUSE, MOUSE]|[1062.00, 23.60, 23.60]|[900] |false |940 |
|Ben |[PHONE, CASE] |[590.00, 17.70] |[500] |true |515 |
|Chen |[] |[] |[] |false |0 |
|Divya |NULL |NULL |NULL |NULL |NULL |
+--------+----------------------+-----------------------+----------+---------+----------+
transform(prices, p -> p * 1.18)adds 18% tax to each price. The results show two decimal places because Spark reads1.18as aDECIMALliteral, not a floating-point number.aggregate(prices, 0, (acc, p) -> acc + p)starts at 0 and adds each price, giving the cart total. Chen's empty cart totals 0, while Divya'sNULLcart givesNULL.
These functions keep the data in one row, which is much cheaper than exploding, transforming and collecting it back.
11. Putting It Together: Parsing Nested JSON
Raw events often arrive as JSON strings. from_json parses a string into structs and arrays, given a schema written in DDL style:
CREATE OR REPLACE TEMP VIEW raw_events AS
SELECT * FROM VALUES
('{"order_id": 501, "customer": {"name": "Asha", "city": "Pune"}, "lines": [{"sku": "laptop", "qty": 1}, {"sku": "mouse", "qty": 2}]}'),
('{"order_id": 502, "customer": {"name": "Ben", "city": "Mumbai"}, "lines": [{"sku": "phone", "qty": 1}]}')
AS raw_events(json)
CREATE OR REPLACE TEMP VIEW events AS
SELECT from_json(
json,
'order_id INT, customer STRUCT<name: STRING, city: STRING>, lines ARRAY<STRUCT<sku: STRING, qty: INT>>'
) AS e
FROM raw_events
Now use everything from this tutorial on it: dots for struct fields, explode for the array of order lines, and a higher-order function for the total quantity:
SELECT e.order_id,
e.customer.name AS customer,
e.customer.city AS city,
line.sku,
line.qty,
aggregate(e.lines, 0, (acc, l) -> acc + l.qty) AS order_qty
FROM events
LATERAL VIEW explode(e.lines) t AS line
ORDER BY e.order_id, line.sku
+--------+--------+------+------+---+---------+
|order_id|customer|city |sku |qty|order_qty|
+--------+--------+------+------+---+---------+
|501 |Asha |Pune |laptop|1 |3 |
|501 |Asha |Pune |mouse |2 |3 |
|502 |Ben |Mumbai|phone |1 |1 |
+--------+--------+------+------+---+---------+
Each JSON order became one row per order line, with the customer details repeated on each row. to_json goes the other way and turns a struct back into a JSON string:
SELECT to_json(e.customer) AS customer_json
FROM events
ORDER BY e.order_id
+------------------------------+
|customer_json |
+------------------------------+
|{"name":"Asha","city":"Pune"} |
|{"name":"Ben","city":"Mumbai"}|
+------------------------------+
Interview tip: "Flatten this nested JSON" questions combine exactly these pieces: parse with a schema, read struct fields with dots, and
explodethe arrays. Mentionexplode_outerif some records may have empty arrays.
12. Try It in the Online Compiler
Copy this into the PySpark Online Compiler:
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("Spark SQL Complex Types").getOrCreate()
spark.sql("""
CREATE OR REPLACE TEMP VIEW carts AS
SELECT * FROM VALUES
(1, 'Asha', array('laptop', 'mouse', 'mouse'), array(900, 20, 20)),
(2, 'Ben', array('phone', 'case'), array(500, 15)),
(3, 'Chen', CAST(array() AS ARRAY<STRING>), CAST(array() AS ARRAY<INT>)),
(4, 'Divya', NULL, NULL)
AS carts(cart_id, customer, items, prices)
""")
spark.sql("""
SELECT customer, explode_outer(items) AS item
FROM carts
ORDER BY customer, item
""").show(truncate=False)
spark.sql("""
SELECT customer,
size(items) AS item_count,
aggregate(prices, 0, (acc, p) -> acc + p) AS cart_total
FROM carts
ORDER BY cart_id
""").show(truncate=False)
Summary
- Arrays hold lists, maps hold key-value pairs, and structs hold named fields. Create them with
array(),map()andnamed_struct(). - Array
[i]is 0-based;element_atis 1-based and accepts negative indexes. A missing element or key returnsNULL. size()of aNULLarray is -1 in Spark 3.5 by default.explodegives one row per element but drops empty andNULLarrays;explode_outerandLATERAL VIEW OUTERkeep them.collect_listandcollect_setrebuild arrays; wrap them inarray_sortfor a predictable order.transform,filter,existsandaggregatework inside arrays without exploding them.from_jsonwith a DDL schema turns JSON strings into structs and arrays you can query.
Next, you will learn how to read Spark's query plans with EXPLAIN and use hints and caching to make queries faster.