在Spark中使用验证来强制转换Dataframe列

时间:2019-06-21 06:34:22

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

我需要将包含值的数据框的列作为所有字符串转换为已定义的模式数据类型。 在进行转换时,我们需要将损坏的记录(数据类型错误的记录)放入单独的列

数据框示例

+---+----------+-----+
|id |name      |class|
+---+----------+-----+
|1  |abc       |21   |
|2  |bca       |32   |
|3  |abab      | 4   |
|4  |baba      |5a   |
|5  |cccca     |     |
+---+----------+-----+

文件的Json模式:

 {"definitions":{},"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://example.com/root.json","type":["object","null"],"required":["id","name","class"],"properties":{"id":{"$id":"#/properties/id","type":["integer","null"]},"name":{"$id":"#/properties/name","type":["string","null"]},"class":{"$id":"#/properties/class","type":["integer","null"]}}}

在此行4中,由于类列的类型为Integer,所以记录已损坏 因此,只有此记录必须存在于损坏的记录中,而不是第五行

1 个答案:

答案 0 :(得分:2)

只需在投射前检查值是否为NOT NULL,然后在投射后检查值NULL

import org.apache.spark.sql.functions.when

df
  .withColumn("class_integer", $"class".cast("integer"))
  .withColumn(
    "class_corrupted", 
    when($"class".isNotNull and $"class_integer".isNull, $"class"))

为您需要的每一列/演员表重复。