在 Spark scala 程序中解析日期时出错 [重复]

Posted

技术标签:

【中文标题】在 Spark scala 程序中解析日期时出错 [重复]【英文标题】:Error while parsing Date in Spark scala program [duplicate] 【发布时间】:2018-01-09 02:54:32 【问题描述】:

我正在通过以下语句解析日期,并且 spark 程序在执行时抛出错误。

import java.time.LocalDate
val filterDate = "2017-06-26"
val filter = LocalDate.parse(load_dt)

我在过滤数据框列中的记录时使用了过滤器变量。

val df1 = spark.sql("select * from tableA")
val df2 = df1.filter(load_dt = filter)

在执行上述程序时,它抛出了以下错误

User class threw exception: org.apache.spark.sql.AnalysisException: cannot resolve '(tableA.`load_dt` = ((2017 - 6) - 26))' due to data type mismatch: differing types in '(tableA.`load_dt` = ((2017 - 6) - 26))' (date and int).; line 1 pos 0;

我不明白为什么它分别查看 (2017 - 6) 和 (-26)。

谁能帮忙 谢谢

【问题讨论】:

【参考方案1】:

Spark 的 DataFrame API 没有 java.time.LocalDate 的编码器,但由于您的 load_dt 列已经是 java.sql.Date 类型,您不需要将您的 filterDate 转换为 LocalDate。另一个问题是 === 应该用于在您的 filter 条件中进行相等性检查,如下例所示:

val filterDate = "2017-06-26"

val df1 = Seq(
  (1, java.sql.Date.valueOf("2017-06-25")),
  (2, java.sql.Date.valueOf("2017-06-26")),
  (3, java.sql.Date.valueOf("2017-06-27"))
).toDF("id", "load_dt")

val df2 = df1.filter($"load_dt" === filterDate)

df2.show
+---+----------+
| id|   load_dt|
+---+----------+
|  2|2017-06-26|
+---+----------+

[更新]

根据您的评论,如果 filterColumnfilterValue 作为变量提供:

使用 Spark SQL:

df1.createOrReplaceTempView("df1Table")

val tableName = "df1Table"
val filterColumn = "load_dt"
val filterValue = "2017-06-26"

val df2 = spark.sqlContext.sql(
  "select * from " + tableName + " where " + filterColumn + " = '" + filterValue + "'"
)

// Alternative: use string interpolation `s"..."`
val df2 = spark.sqlContext.sql(
  s"select * from $tableName where $filterColumn = '$filterValue'"
)

使用 Spark DataFrame API:

val df2 = df1.select("*").where(col(filterColumn) === filterValue)

【讨论】:

感谢 Leo 的回答。我能够使用 '===' 执行程序并在程序内部传递 filterDate = "2017-06-26" 。我现在有一个问题,当我尝试将 filterValue 作为 spark-submit 的参数传递时,它没有正确读取它,因为我无法在引号“”下给出日期。比如 val df = spark.sql("select * from" + tableName + "where" + filterColumn + " = " + " ' " + filterValue + " ' ")。我已经在程序中这个语句之前定义了表名和filterColumn。 看起来您在编写 SQL 语句时缺少/错放了空格。请查看我的更新答案。

以上是关于在 Spark scala 程序中解析日期时出错 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

在 IntelliJ IDE 中将 Spark 与 Scala 项目集成时出错

使用Scala在Spark中创建DataFrame时出错

在 Spark 中处理日期

forEach Spark Scala 中的错误:值选择不是 org.apache.spark.sql.Row 的成员

在火花簇scala中保存随机森林模型时出错

Spark 出错:NoSuchMethodError: scala.Predef$.$conforms()Lscala/Predef$$less$colon$less