Advanced Map Operations
Concepts covered: Maps
This section assumes the intermediate map toolkit. map_filter, transform_values and transform_keys take a 2-parameter lambda (k, v) -> ...; map_concat lets the later map win on a shared key; map_zip_with hands its lambda both values for every key. The table below is the reference. The work here is reshaping: turning parallel arrays into a map, reaching into arrays of records, and folding colliding keys into a map whose values are arrays.
| Function | Lambda returns | Result |
|---|---|---|
| `transform_values(m, (k, v) -> ...)` | the new value | Same keys, new values |
| `transform_keys(m, (k, v) -> ...)` | the new key | New keys, same values; fails if 2 keys collide |
| `map_filter(m, (k, v) -> ...)` | a BOOLEAN | Only the entries where it is TRUE |
| `map_zip_with(m1, m2, (k, v1, v2) -> ...)` | the merged value | Every key from either map; a side without the key passes NULL |
Parallel arrays into a map
Producers often ship related values as parallel arrays, such as track_ids and durations_sec, matched by position. Two functions turn that pair into a lookup keyed by id. zip(a, b) merges the arrays element by element into a single array of ROW values, each a small record holding one value from each array. map_from_entries reads an array of 2-field rows as key and value pairs and returns a map. The MAP(keys, values) constructor builds the same map from 2 plain arrays; the entries form also accepts rows built by transform or trimmed by filter first, which the records example below relies on.
| Step | Expression | Playlist 101's value |
|---|---|---|
| Input | `track_ids`, `durations_sec` | `['t9', 't4', 't7']`, `[210, 170, 240]` |
| Pair | `zip(track_ids, durations_sec)` | `[ROW('t9', 210), ROW('t4', 170), ROW('t7', 240)]` |
| Map | `map_from_entries(...)` | `{t9: 210, t4: 170, t7: 240}` |
| Look up | `element_at(m, 't4')` | `170` |
SELECT
playlist_id,
map_from_entries(zip(track_ids, durations_sec)) AS sec_by_track,
map_filter(map_from_entries(zip(track_ids, durations_sec)), (k, v) -> v > 180) AS long_by_track
FROM playlistsPlaylist 101's map holds 3 entries, and long_by_track keeps t9 and t7. Playlist 102's t5 keeps its NULL value in sec_by_track, since a map value may be NULL, and map_filter drops that entry because NULL > 180 is not TRUE, leaving t2 and t8. Keys are stricter than values: a NULL key or a track id that appears twice fails the whole query, so check cardinality(array_distinct(track_ids)) = cardinality(track_ids) before building the map when a producer can repeat an id.
Arrays of records
An array of ROW values is a list of records, the shape a session log takes when each play carries a track id and a duration together. Its type is written ARRAY(ROW(track_id VARCHAR, sec INTEGER)), and inside a lambda the current element is a record whose fields are read with a dot: r.track_id, r.sec. Every array function from the first 2 sections works on it. What changes from one function to the next is the type of the result, which follows what the lambda returns.
SELECT
session_id,
transform(plays, r -> r.track_id) AS track_ids,
filter(plays, r -> r.sec > 180) AS long_plays,
map_from_entries(transform(plays, r -> ROW(r.track_id, r.sec))) AS sec_by_track
FROM sessions| Column | Type | Session s1 |
|---|---|---|
| `plays` | `ARRAY(ROW(track_id VARCHAR, sec INTEGER))` | `[('t9', 210), ('t4', 170), ('t7', 240)]` |
| `track_ids` | `ARRAY(VARCHAR)` | `['t9', 't4', 't7']` |
| `long_plays` | `ARRAY(ROW(track_id VARCHAR, sec INTEGER))` | `[('t9', 210), ('t7', 240)]` |
| `sec_by_track` | `MAP(VARCHAR, INTEGER)` | `{t9: 210, t4: 170, t7: 240}` |
A transform with a field access pulls one field out of every record, so 3 records become an array of 3 strings. filter returns whole records, so long_plays keeps the row type and both fields of the 2 plays over 180 seconds. The last column rebuilds each record as an anonymous 2-field row and hands the array to map_from_entries: the same move as zip, with the pairing done by the lambda.
Renaming keys without collisions
transform_keys(m, (k, v) -> lower(k)) fails on a map holding both 'Rock' and 'rock', because the result would put 2 entries under one key and a map allows each key once. Apps that disagree on capitalisation produce exactly this. The repair goes through rows: unnest the map into key and value columns, lower the key, and fold the entries back with multimap_agg, which collects every value for a key into an array. A transform_values with reduce then sums each array.
SELECT
r.user_id,
multimap_agg(lower(g.genre), g.sec) AS grouped,
transform_values(multimap_agg(lower(g.genre), g.sec), (k, v) -> reduce(v, 0, (s, x) -> s + x, s -> s)) AS genre_sec
FROM raw AS r
CROSS JOIN UNNEST(r.genre_sec) AS g(genre, sec)
GROUP BY r.user_idgrouped is the nested middle shape, a map from lowered genre to an array: rock holds 600 and 300, and jazz holds 120. The order inside each array carries no guarantee, which a sum ignores. The reduce in genre_sec folds each array to a number, rock 900 and jazz 120, so listener 9 comes back as a single row whose 3 raw entries have become 2 clean ones. A listener with an empty map would vanish at the UNNEST, the trade section 2 described.
A producer repeats a track: track_ids is ['t2', 't5', 't2'] and durations_sec is [195, 140, 260]. What does map_from_entries(zip(track_ids, durations_sec)) return?
- {t2: 260, t5: 140}, because the later entry overwrites t2
- {t2: 195, t5: 140}, because the first entry for t2 is kept
- {t2: [195, 260], t5: [140]}, because repeats gather into an array
- An error, because the key t2 appears twice in the entries
About this lesson
This section is part of the Complex Data: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.