从struct keys spark添加值

kyks70gy  于 2021-07-12  发布在  Spark
关注(0)|答案(1)|浏览(291)

我有以下代码:

val df2 = df.withColumn("col", expr("transform(col, x -> struct(x.amt as amt))"))
Output: [{"amt": 10000}, {"amt": 20000}]

我要添加amt key的所有值。所以我把所有的值都列在一个列表中,如下所示:

df.withColumn("list_val", expr("transform(col, x -> x.amt)"))
Output: [10000,20000]

要对这些值求和,我有以下代码,但getting error无法解析aggregate

.withColumn("amount", aggregate($"list_val", lit(0), (x, y) => (x + y)))

如何修复此代码,或者是否有更好的方法添加值?

gmxoilav

gmxoilav1#

aggregate 应该在sparksql中使用 expr 对于spark 2.4。此外,最好添加类型转换以确保没有类型不匹配:

df.withColumn("amount", expr("aggregate(list_val, 0, (x, y) -> (x + int(y)))")

// for float type; for double type, replace "float" with "double"
df.withColumn("amount", expr("aggregate(list_val, float(0), (x, y) -> (x + float(y)))")

在scalaapi中

df.withColumn("amount", aggregate($"list_val", lit(0), (x, y) => (x + int(y))))

df.withColumn("amount", aggregate($"list_val", lit(0f), (x, y) => (x + float(y))))

df.withColumn("amount", aggregate($"list_val", lit(0.0), (x, y) => (x + double(y))))

相关问题