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
相关产品推荐
相关产品推荐

