这是 Spark shell 代码
scala> val colName = "time_period_id"
scala> val df = spark.sql("""select time_period_id from prod.demo where time_period_id =
202101102 """)
df: org.apache.spark.sql.DataFrame = [time_period_id: int]
scala> val result = df.agg(max(colName)).head(1)
result: Array[org.apache.spark.sql.Row] = Array([null])
scala> result(0).getInt(0) match {
| case null => 0
| case _ => result(0).getInt(0)
| }
如果结果是Array([null])
,那么我希望返回0
,如果结果是Array([20210110])
code> 然后我想要返回 20210110
但我收到此错误
<console>:33: error: type mismatch;
found : Null(null)
required: Int
case null => 0
最佳答案
您可以使用 lift
获取数组项,以便将其作为选项进行处理。如果元素内部为 null,则返回 Some(null);如果根本没有元素,则返回 None
result.lift(0) match {
case Some(element) if element != null => element.getInt(0)
case _ => 0
}
或者,如果您不介意在模式匹配中包含更多行:
result.lift(0) match {
case Some(null) => 0
case Some(element) => element.getInt(0)
case _ => 0
}
另一种选择是使用尝试
import scala.util.Try
import scala.util.Success
Try(result(0).getInt(0)) match {
case Success(date) => date
case _ => 0
}
关于scala - 我如何处理 Spark scala 中的模式匹配中的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66571770/