繁体   English   中英

尝试将模式应用于 JSON 数据时,SPARK dataframe 返回 null

[英]SPARK dataframe returning null when trying to apply schema to JSON data

我正在使用 SPARK Java API 读取文本文件,将其转换为 JSON,然后对其应用架构。 架构可以根据数据库中的映射表而有所不同,这就是为什么我需要首先将文件转换为 JSON 以便架构映射不必按列顺序。 这是我所做的:

// Defined the schema (basic representation)
StructType myschema = new StructType().add("a", DataTypes.StringType, true)
                                      .add("b", DataTypes.StringType, true)
                                      .add("x", DataTypes.StringType, true)
                                      .add("y", DataTypes.IntegerType, true)
                                      .add("z", DataTypes.BooleanType, true);

//Reading a pipe delimited text file as JSON, the file has less columns than myschema
Dataset<String> data = spark.read().option("delimiter","|").option("header","true").csv(myFile).toJSON();

上表返回如下内容:

data.show(false);

|value|
+----------------------------------------+
|      {"x":"name1","z":"true","y":"1234"}|
|      {"x":"name2","z":"false","y":"1445"}|
|      {"x":"name3","z":"true",:y":"1212"}|

当我运行这个时,我的问题出现了:

Dataset<Row> data_with_schema = spark.read().schema(myschema).json(data);

因为我的结果变成了这样:

data_with_schema.show(false);
|x|y|z|
+-------+-------+-------+
|null  |null  |null  |
|null  |null  |null  |
|null  |null  |null  |

我在 stackoverflow 上读到这可能是因为我试图将 json 字符串转换为整数。 但是,我尝试将数据变量定义为行数据集而不是字符串数据集,但出现了不兼容的类型错误。 我不确定解决方法是什么或真正的问题是什么。

想通了问题:

如果输入的文件中存在无法应用架构的数据,它将为表中的所有数据返回 Null。 例如:“1n”是不可能转换成integer的。 如果将 DataTypes.IntegerType 应用于包含“1n”的列,则整个表具有 null 值。

我认为这是由于 JSON 和定义的架构中的数据类型不匹配而发生的。 例如,在 JSON 中,属性具有 integer 的“年龄”,但架构定义了字符串类型的“年龄”。 由于这种不匹配,所有数据都得到 null。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM