如何在spark3.0.0中使用tranformapi?

raogr8fs  于 2021-05-27  发布在  Spark
关注(0)|答案(1)|浏览(357)

如你所知, transform api已经集成到spark3.0.0中,但是我已经厌倦了,不知道如何使用它,也不能用google搜索任何用法。有人能给我一个用法吗?比你还厉害!
我累了什么:

val source = spark.read.format("json").option("multiLine", "true").load("/home/user/Desktop/test.json")
    source.select(transform($"array0",x =>struct($"x.a".as("A")) ))
org.apache.spark.sql.AnalysisException: cannot resolve '`x.a`' given input columns: [array0];;
'Project [transform(array0#0, lambdafunction(named_struct(NamePlaceholder, 'x.a), lambda x#4, false)) AS transform(array0, lambdafunction(named_struct(NamePlaceholder(), x.a AS `A`), x))#3]
+- RelationV2[array0#0] json file:/home/usr/Desktop/test.json

我的源json:

{
    "array0":[
        {
            "a":"0",
            "b":"1"
        }
    ]
}
whlutmcx

whlutmcx1#

如果你是指高阶函数 transform 与数组一起使用,下面是一个简单的工作示例:

val df = spark.range(2).withColumn("arr", array(lit(1), lit(2)))

df.withColumn("x", transform($"arr", x => x + 1)).show()

+---+------+------+
| id|   arr|     x|
+---+------+------+
|  0|[1, 2]|[2, 3]|
|  1|[1, 2]|[2, 3]|
+---+------+------+

在您的示例中,由于数组中有结构,因此可以按如下方式访问结构的元素:

df.withColumn("x", transform($"arr", x => x.getItem("a") + 1))

相关问题