首页 > 解决方案 > 在 Spark Dataframe 中获取未定义类型的值

问题描述

无法过滤包含 的值null。我正在对空的 Spark 数据集尝试多项操作。

case class SourceWithoutFlag( id:String, phone:String, name:String)
case class Target(id:String, phone:String, name:String, start_date:String, end_date:String, flag:String)

代码描述如下: -

var target = spark.emptyDataset[Target]
val source: Dataset[SourceWithoutFlag] = spark
    .read.option("header", true).csv(sourceFile).as[SourceWithoutFlag]
println("New Data Read")
source.show(Int.MaxValue)

var operationRecordCheck = source
    .select("id")
    .withColumnRenamed("id","ids")
operationRecordCheck = target
    .join(operationRecordCheck, target("id") ===
                    operationRecordCheck("ids"),"full_outer")

operationRecordCheck.show
var insertRecordId = operationRecordCheck
    .where(isnull($"id"))
    .select("ids")
insertRecordId.show

在这里,我正在阅读source包含这些值的数据集

New Data Read
+---+---------+------+
| id|    phone|  name|
+---+---------+------+
|999|987654321|Jhoney|
|888|876543210|Stuart|
|444|576543210|Brocli|
|555|487654321|Advock|
+---+---------+------+

和另一个数据集target,它是一个空数据集

+---+-----+----+----------+--------+----+
| id|phone|name|start_date|end_date|flag|
+---+-----+----+----------+--------+----+
+---+-----+----+----------+--------+----+

现在我正在执行这两个数据集的连接,得到这个结果operationRecordCheck

+----+-----+----+----------+--------+----+---+
|  id|phone|name|start_date|end_date|flag|ids|
+----+-----+----+----------+--------+----+---+
|null| null|null|      null|    null|null|999|
|null| null|null|      null|    null|null|888|
|null| null|null|      null|    null|null|444|
|null| null|null|      null|    null|null|555|
+----+-----+----+----------+--------+----+---+

但是当我检查单元格值是否为空时,它会给出异常。

线程“主”java.util.NoSuchElementException 中的异常:None.get

异常的原因是

operationRecordCheck
        .where(isnull($"id"))
        .select("ids")

我只想SELECT ids FROM operationRecordCheck WHERE id IS null;在 operationRecordCheck 数据集上应用 sql 查询,但它没有将我的数据集值视为null.

我也尝试过isnan($"id"), $"id".isNull, $"id".isNaN, $"id".isNotNull, $"id" === ""$"id" === null但它没有给我正确的结果。

感谢帮助:)

标签: scalaapache-sparknullnullablenosuchelementexception

解决方案


我最近遇到了一个看起来非常相似的问题(同样的错误消息,类似的基于 spark 的数据操作,先是连接,然后是过滤器,并且故障可追溯到过滤器步骤)。在我的例子中,通过在 filter/'where' 调用之前添加一个 Dataset.cache() 调用来避免失败。我认为您的代码中的类似更改如下所示:

operationRecordCheck
        .cache()
        .where(isnull($"id"))
        .select("ids")

推荐阅读