【问题标题】:Getting dataframe column in variable, how to?在变量中获取数据框列,如何?
【发布时间】:2016-12-29 20:01:41
【问题描述】:

环境:Spark 1.6,Scala

我正在尝试从数据框中获取一个日期时间字段以在 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 中使用?

谢谢
侯赛因

【问题讨论】:

    标签: scala apache-spark dataframe hive apache-spark-sql


    【解决方案1】:

    很简单——sql返回DataFrame,但你确定它只有一个元素,所以你可以这样做:

    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 + ")")
    

    【讨论】:

    • 感谢 Gaweda 的回复。我尝试了您的代码并收到错误java.lang.ClassCastException: java.sql.Timestamp cannot be cast to java.sql.Date
    • @Hossain 那是因为我的测试数据有Date 列,你有Timestamp - 我已经更新了答案
    • @Hossain 再举一个不解析时间戳的例子。请注意,您可以使用java.util.Date,因为它是 Timestamp 和 sql.Date 的父类
    • @Gaweda,非常感谢。您的代码完全按照我的需要工作。感谢您的支持。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多