首页 > 解决方案 > 如何使用列值在 Spark Scala 中为 withColumn 生成另一个列的名称

问题描述

我试图在读取 json 资源文件后生成数据框。我的 json 文件包含依赖属性,并且在使用 withColumn 时,我需要获取列值来创建另一个列名。

你可以在下面找到我现在正在做的事情:

val getInfo= df
      .withColumn("transactions", explode($"transactions"))//this is array
      .withColumn("id", $"transactions.data.profile.id")
      .withColumn("totalAmounts", explode($"transactions.data.activity.total"))
      .withColumn("amount", $"totalAmounts.amount")
      .withColumn("code", $"totalAmounts.code")
      .withColumn("category", $"totalAmounts.category")
      .withColumn("createdAt", $"transactions.data.meta.created.at")
      .withColumn("relatedDetails", explode($"transactions.data.related"))
      .withColumn("resourceId", $"relatedDetails.id")
      .withColumn("mainType", $"relatedDetails.type")
      .withColumn("subType", $"transactions.data.subType")
      .drop("transactions")
      .drop("totalAmounts")
      .drop("relatedDetails")
      .as[TransactionData]
      .toDF()

上面的代码对我来说没问题,但是在 json 文件中有一个动态生成的属性。当我想添加另一列“transactionType”时,它取决于“resourceId”列的值。

我需要做的如下:

.withColumn("transactionType",$"transactions.included.transactionDetail.<<resourceId value>>.transactionType")  .

标签: jsonscaladataframedynamicapache-spark-sql

解决方案


推荐阅读