You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala中如何从org.apache.spark.sql.Column提取键并转为List?

从Spark Column中提取键并转为List[String]

场景说明

需要从org.apache.spark.sql.Column类型变量inputFieldMap(其内容显示为keys:[customerID,country],values[customerID,country])中提取键,存入List[String]用于Schema对比,期望得到List(customerID, country)。

解决方案

情况1:inputFieldMap为MapType列

如果该Column是Spark的MapType类型,可使用内置函数提取键并收集为Driver端的List:

import org.apache.spark.sql.functions.map_keys

// 提取所有键的列
val keysCol = map_keys(inputFieldMap)

// 从DataFrame中收集结果为List[String](假设df包含该列)
val newVariable: List[String] = df.select(keysCol).as[List[String]].first()

情况2:解析Column的字符串表示

如果仅能通过Column的toString输出获取键信息,可通过正则解析字符串:

// 获取Column的字符串形式
val columnStr = inputFieldMap.toString

// 正则匹配提取keys内的内容
val keysPattern = """keys:\[(.*?)\]""".r
val keysContent = keysPattern.findFirstMatchIn(columnStr).map(_.group(1)).getOrElse("")

// 分割为List[String]
val newVariable: List[String] = keysContent.split(",").toList

执行后newVariable即为List(customerID, country),可直接用于Schema对比。

内容的提问来源于stack exchange,提问作者Shankar Panda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 02:22:04