spark java 如何 select 使用 withcolumn 新添加的列

spark java how to select newly added column using withcolumn

我正在尝试创建 java spark 程序并尝试使用

添加新列
qdf.withColumn("newColumn", functions.lit("newCOlumn_val"))

当我尝试 select 和

qdf.withColumn("newColumn", functions.lit("newColumn_val")).select(qdf.col("xyz"),qdf.col("newColumn")).show();

它说 无法重新爱列名称 newColumn。有人可以帮助我如何在 Java 中做到这一点吗?

试试下面的代码。

qdf.withColumn("newColumn", functions.lit("newColumn_val"))
.select("xyz","newColumn")
.show();

您实际上根本不需要使用 withColumn。(实际上,与直接使用 select 相比,它对性能的影响非常小。) 只需在 select 语句中引用 lit

qdf.select( 
  qdf.col("xyz"), 
  functions.lit("newColumn_val").alias("new Column") 
).show();

qdf 是您添加 newColumn 之前的数据帧,这就是为什么您无法使用 qdf.col("newColumn").

select 它的原因

要处理它,您可以使用 functions.col("newColumn") 例如

qdf.withColumn("newColumn", functions.lit("newColumn_val"))
    .select(functions.col("xyz"),functions.col("newColumn"))
    .show();

或者,您可以在调用 withColumn 后存储数据帧,然后它应该可以访问,例如

final var qdf2 = qdf.withColumn("newColumn", functions.lit("newColumn_val"));

qdf2.select(qdf2.col("xyz"), qdf2.col("newColumn")).show();

或者您可以像 Srinivas 的回答那样使用原始字符串。