map, map_from_arrays & map_from_entries
A Map column stores key→value pairs per row. Build one inline with map(k1, v1, k2, v2, …), or from two parallel arrays with map_from_arrays(keys, values). Here's the dataset — each account carries a bag of attributes:
import org.apache.spark.sql.functions.map
val accounts = Seq(
(1, "Aisha", Map("plan" -> "pro", "seats" -> "5")),
(2, "Rohan", Map("plan" -> "free", "seats" -> "1")),
(3, "Mia", Map("plan" -> "pro", "region" -> "US"))
).toDF("id", "name", "attrs")
accounts.show(false)| id | name | attrs |
|---|---|---|
| 1 | Aisha | {plan -> pro, seats -> 5} |
| 2 | Rohan | {plan -> free, seats -> 1} |
| 3 | Mia | {plan -> pro, region -> US} |
def map(cols: Column*): Column // alternating key, value, key, value … def map_from_arrays(keys: Column, values: Column): Column def map_from_entries(e: Column): Column // Array[Struct(key,value)] → Map
spark.sql.mapKeyDedupPolicy). Values can be null. Unlike a struct, a map's key set can differ from row to row, which is exactly why you'd choose it over a struct for sparse or open-ended attributes.