我知道使用.withColumn()
和UDF
向Spark DataSet添加新列的方法,它返回一个DataFrame。我也知道,我们可以将生成的DataFrame转换为DataSet。如何将数据列添加到数据集而不从DataFrame转换并访问它?
我的问题是:
- 如何DataSet的类型安全进场这里,如果我们依然遵循着传统的DF方法(即通过列名作为UDF的输入字符串)
- 是否有“像面向对象的方式”访问列(不需要像字符串那样传递列名),就像我们以前用RDD做的那样,用于追加一个新列。
- 如何访问像地图,过滤器等正常操作中的新列?
例如:
scala> case class Temp(a : Int, b : String) //creating case class
scala> val df = Seq((1,"1str"),(2,"2str),(3,"3str")).toDS // creating DS
scala> val appendUDF = udf((b : String) => b + "ing") // sample UDF
scala> df.withColumn("c",df("b")) // adding a new column
res5: org.apache.spark.sql.DataFrame = [a: int, b: string ... 1 more field]
scala> res5.as[Temp] // converting to DS
res6: org.apache.spark.sql.Dataset[Temp] = [a: int, b: string ... 1 more field]
scala> res6.map(x =>x.
// list of autosuggestion :
a canEqual equals productArity productIterator toString
b copy hashCode productElement productPrefix
新列c
,即我已经使用.withColumn()
是无法访问的添加,由于柱c
不在的情况下类Temp
(它仅包含a
& b
)在使用res5.as[Temp]
将其转换为DS时。
如何访问列c
?
有没有其他的方式来添加一列而不传递字符串? – vdep
@vdep''字符串'只是一个遵循问题脉络的例子。 – maasg
不,我的意思是,我们可以做到这一点,而不需要在这里传递列名'b'作为字符串:'df.withColumn(“c”,df(“b”))' – vdep