首页 > 解决方案 > Spark SQL 将数据集转换为数据框

问题描述

如何将数据集 obj 转换为数据框?在我的示例中,我将 JSON 文件转换为数据帧并转换为 DataSet。在数据集中,我添加了一些额外的属性(newColumn)并将其转换回数据框。这是我的示例代码:

val empData = sparkSession.read.option("header", "true").option("inferSchema", "true").option("multiline", "true").json(filePath)

......

 import sparkSession.implicits._
    val res = empData.as[Emp]

    //for (i <- res.take(4)) println(i.name + " ->" + i.newColumn)

    val s = res.toDF();

    s.printSchema()

  }
  case class Emp(name: String, gender: String, company: String, address: String) {
    val newColumn = if (gender == "male") "Not-allowed" else "Allowed"
  }

但我预计newColumns.printschema(). 输出结果。但它没有发生吗?为什么?任何原因?我怎样才能做到这一点?

标签: scalaapache-sparkapache-spark-sql

解决方案


输出的模式Product Encoder完全取决于它的构造函数签名。因此,身体中发生的任何事情都被简单地丢弃。

你可以

empData.map(x => (x, x.newColumn)).toDF("value", "newColumn")

推荐阅读