如果您尝试合并两个数据帧,您将得到以下结果:
error:org.apache.spark.sql.AnalysisException: Union can only be performed on tables with the compatible column types. ArrayType(StringType,true) <> ArrayType(StructType(StructField(d1,StringType,true), StructField(d2,StringType,true)),true) at the second column of the second table
Json文件同时到达
为了解决这个问题,如果你可以同时读取JSON,我建议:
val jsonDf1 = spark.read.json("json1.json", "json2.json")
这将给出这个架构:
jsonDf1.printSchema
|-- age: string (nullable = true)
|-- details: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- d1: long (nullable = true)
| | |-- d2: long (nullable = true)
|-- name: string (nullable = true)
数据输出
jsonDf1.show(10,truncate = false)
+---+-------+------+
|age|details|name |
+---+-------+------+
|32 |[[1,2]]|Agent1|
|42 |null |Agent2|
+---+-------+------+
Json 文件到达的时间不同
如果您的 json 在不同时间到达,作为默认解决方案,我建议读取具有完整数组的模板 JSON 对象,这将使您的数据帧具有可能的空数组,对任何联合都有效。然后,在输出结果之前,您将使用过滤器删除这个假 JSON:
val df = spark.read.json("jsonWithMaybeAnEmptyArray.json",
"TemplateFakeJsonWithAFullArray.json")
df.filter($"name" !== "FakeAgent").show(1)
请注意:开放了Jira卡,以提高合并SQL数据类型的能力:https://issues.apache.org/jira/browse/SPARK-19536 https://issues.apache.org/jira/browse/SPARK-19536并且这种操作应该在下一个Spark版本中可以实现。