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 成員判斷,回傳 Boolcollect_list()/collect_set()— 多列聚成 arrayto_json()— struct → JSONtransform(arr, x -> x*2)— 對每個元素套用運算式filter(arr, x -> x > 0)— 保留符合 predicate 的元素exists(arr, x -> x > 0)— 只要有一個符合 → 等於 Pythonany()forall(arr, x -> ...)— 全部符合 → 等於 Pythonall()
collect_list() vs collect_set()
資料:
| customer_id | item_bought |
|---|---|
| 101 | laptop |
| 101 | mouse |
| 101 | mouse |
| 102 | monitor |
| 102 | hdmi_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_id | all_items (collect_list) | unique_items (collect_set) |
|---|---|---|
| 101 | ["laptop", "mouse", "mouse"] | ["laptop", "mouse"] |
| 102 | ["monitor", "hdmi_cable"] | ["monitor", "hdmi_cable"] |
差別:collect_list 保留重複、collect_set 去重複。
參考來源
- Spark SQL Built-in Functions — https://spark.apache.org/docs/latest/api/sql/
Related: 回到跨引擎資料庫查詢總覽;另見 Spark 資料型別,以及 ClickHouse 對應版本 ClickHouse 陣列與條件函式。