2016-12-29 109 views
0

環境:Spark 1.6,Scala在變量中獲取dataframe列,如何?

我想從數據框中獲取一個datetime字段以便在SparkSQL中進行比較。

val las_max_date_from_hive= hivecontext.sql("select min(SampleTime) max_SampleTime from mytable") 

DF2 = hivecontext.sql ("select * from table2 where sampleDate >" + las_max_date_from_hive) // error here as las_max_date_from_hive is a DF 

如何獲取數據框中的日期時間並在SQL中使用?

感謝
侯賽因

回答

0

很簡單 - sql返回數據幀,但你確信它只有一個元素,那麼你可以這樣做:

val last_max_date_from_hive = hivecontext.sql("select min(SampleTime) max_SampleTime from mytable") 

val firstRow = last_max_date_from_hive.map { 
    // only value is important 
    case Row (value) => value.asInstanceOf[java.sql.Timestamp]; // cast to Date 
}.first() 

// we use SimpleDateFormat to parse to proper string format 
val df2 = sqlContext.sql ("select * from mytable where SampleTime > cast('" 
    + new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").format(firstRow) 
    + "' as date)"); 

如果你不想解析Timestamp對象,那麼你可以使用from_unixtime功能和getTime()

val firstRow = las_max_date_from_hive.map { 
    case Row (value) => value.asInstanceOf[java.sql.Timestamp].getTime()/1000 
}.first(); 

val df2 = sqlContext.sql ("select * from mytable where cast(SampleTime as timestamp) > from_unixtime(" + firstRow + ")") 
+0

感謝,Gaweda您的回覆。我試過你的代碼,並得到錯誤'java.lang.ClassCastException:java.sql.Timestamp不能轉換爲java.sql.Date' – Jhon

+0

@Hossain這是因爲我的測試數據有'日期'列,你有'時間戳' - 我已經更新了回答 –

+0

@Hossain另外一個沒有解析Timestamp的例子。請注意,您可以使用'java.util.Date',因爲它是Timestamp和sql.Date的父類 –