Spark:如何将字符串转换为多列

Spark: How to convert a String to multiple columns

我有一个包含字段项的数据框,它是一个包含项数组的字符串:

[{"item":"76CJMX4Y"},{"item":"7PWZVWCG"},{"item":"967NBPMS"},{"item":"72LC5SMF"},{"item":"8N6DW3VD"},{"item":"045QHTU4"},{"item":"0UL4MMSI"}]

root
 |-- item: string (nullable = true)

我想获取字符串数组形式的项目。如果有一种简单的方法可以使用默认值 from_json 来做到这一点,有人可以告诉我吗?

根 |-- 项目:数组 (nullable = true)

这样我就只有

["76CJMX4Y", "7PWZVWCG", "967NBPMS", "72LC5SMF", "8N6DW3VD", "045QHTU4", "0UL4MMSI"]

谢谢

您可以在 : 上使用 split(),然后使用 sort_array() 对值进行排序(以便您不感兴趣的值位于顶部或底部,然后使用 slice( ).

供大家参考:https://spark.apache.org/docs/latest/api/java/org/apache/spark/sql/functions.html(虽然是Java版本,也是函数的综合列表)

使用 Spark 内置函数 from_json 然后使用高阶函数 transform 从数组中提取项目。

示例

//from_json we are creating a json array then extracting item from the array
import org.apache.spark.sql.functions._


df.selectExpr("""transform(from_json(item,'array<struct<item:string>>'),x->x.item) as item""").show(10,false)

//+----------------------------------------------------------------------+
//|item                                                                  |
//+----------------------------------------------------------------------+
//|[76CJMX4Y, 7PWZVWCG, 967NBPMS, 72LC5SMF, 8N6DW3VD, 045QHTU4, 0UL4MMSI]|
//+----------------------------------------------------------------------+