2016-01-11 57 views
1

下面的代码不起作用:链接数据帧函数调用

val newDF = df 
      .withColumn("timestamp", when(df("processingDate").isNull, lit(new Timestamp(System.currentTimeMillis))).otherwise(df("processingDate"))) 
      .withColumn("year", year(df("timestamp"))) 
      .withColumn("month", month(df("timestamp"))) 
      .withColumn("day", dayofmonth(df("timestamp"))) 

如果我运行它,我会得到以下异常:

Exception in thread "main" org.apache.spark.sql.AnalysisException: Cannot resolve column name "timestamp" among ... 

的问题是,虽然我已经加入“时间戳”作为一个专栏,它不是原始的,不可变的“df”的一部分。

有没有办法引用调用链中的前一个Dataframe?

我会将我的代码更新到以下版本,以便它能正常工作,但我想知道是否有更好的方法。

val dfWithTimestamp = df.withColumn("timestamp", when(df("monBusinessDateTimestamp").isNull, lit(new Timestamp(System.currentTimeMillis))).otherwise(df("monBusinessDateTimestamp"))) 

val newDF = dfWithTimestamp 
      .withColumn("year", year(dfWithTimestamp("timestamp"))) 
      .withColumn("month", month(dfWithTimestamp("timestamp"))) 
      .withColumn("day", dayofmonth(dfWithTimestamp("timestamp"))) 
+0

您可以共享Dataframe的模式吗? – eliasah

回答

2

我现在不能检查,但

val newDF = df 
      .withColumn("timestamp", when(df("processingDate").isNull, lit(new Timestamp(System.currentTimeMillis))).otherwise(df("processingDate"))) 
      .withColumn("year", year($"timestamp")) 
      .withColumn("month", month($"timestamp")) 
      .withColumn("day", dayofmonth($"timestamp")) 

可能会奏效。

+0

非常接近,更新了一个小的更正。谢谢你的帮助。 –