Skip to content
All writing Part 07 of 09 · [object Object]
Engineering · 1 min read

Spark 陣列函式與 collect_list、collect_set

Spark 的高階陣列函式——transform、filter、exists、forall,加上 NVL、array_contains,以及 collect_list 與 collect_set 的差別(保留重複 vs 去重)。

Spark 的 array 高階函式,以及把多列聚成 array 的 collect_*

常用

  • NVL(x, default) — 給 null 預設值
  • array_contains(arr, val) — array 成員判斷,回傳 Bool
  • collect_list() / collect_set() — 多列聚成 array
  • to_json() — struct → JSON
  • transform(arr, x -> x*2) — 對每個元素套用運算式
  • filter(arr, x -> x > 0) — 保留符合 predicate 的元素
  • exists(arr, x -> x > 0) — 只要有一個符合 → 等於 Python any()
  • forall(arr, x -> ...) — 全部符合 → 等於 Python all()

collect_list() vs collect_set()

資料:

customer_iditem_bought
101laptop
101mouse
101mouse
102monitor
102hdmi_cable
SELECT
    customer_id,
    collect_list(item_bought) AS all_items,
    collect_set(item_bought) AS unique_items
FROM store_sales
GROUP BY customer_id;

結果:

customer_idall_items (collect_list)unique_items (collect_set)
101["laptop", "mouse", "mouse"]["laptop", "mouse"]
102["monitor", "hdmi_cable"]["monitor", "hdmi_cable"]

差別:collect_list 保留重複、collect_set 去重複。


參考來源

Related: 回到跨引擎資料庫查詢總覽;另見 Spark 資料型別,以及 ClickHouse 對應版本 ClickHouse 陣列與條件函式

Tags #spark #sql
// connect

Be brave | Be wise | Be grateful

21 BreakinCode

// elsewhere
LinkedInMedium (lang: en)Youtube
wh:~$William Hung· © 2026 Taipei · GMT+8 · Available for collaboration