gpt4 book ai didi

java - 尝试将架构应用于 JSON 数据时,SPARK 数据帧返回 null

转载 作者:行者123 更新时间:2023-12-04 01:01:02 25 4
gpt4 key购买 nike

我正在使用 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”不可能转换为整数。如果将 DataTypes.IntegerType 应用于包含“1n”的列,则整个表具有空值。

关于java - 尝试将架构应用于 JSON 数据时,SPARK 数据帧返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58349787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com