Spark 从不同的模式目录中读取数据帧 [英] Spark Reading data frames from different schema directory

查看:54
本文介绍了Spark 从不同的模式目录中读取数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的spark程序必须从一个目录中读取,这个目录有不同模式的数据

My spark program has to read from a directory, This directory has data of different schema

目录/子目录1/文件
1,10, 外星人
1,11,鲍勃

Dir/subdir1/files
1,10, Alien
1,11, Bob

目录/子目录2/文件
2,蓝色,123,芝加哥
2,red, 34, 达拉斯

Dir/subdir2/files
2,blue, 123, chicago
2,red, 34, Dallas

大约还有 50 个不同架构的目录.

Around 50 more directories with different schemas.

我的 spark 作业必须从所有这些目录中读取数据并生成一个合并这些文件的文件,如下所示

My spark job has to read data from all these directories and generate a file merging this files as shown below

1, 10, 外星人;
1, 11, 鲍勃;
2、蓝色、123、芝加哥;
2,红色,34,达拉斯;

1, 10, Alien;
1, 11, Bob;
2, blue, 123,chicago;
2, red, 34, Dallas;

Spark 数据框期望架构在所有目录中都相同.有什么方法可以读取所有这些不同架构的文件并使用 spark 合并到单个文件中

Spark data frame expects schema to be same in all directories. is there any way I can read all these files of different schema and merge into single file using spark

推荐答案

对于镶木地板和不同的架构,我知道有 2 种策略

With parquet and different schema there are 2 strategy that I know of

  1. 如果架构兼容,您可以使用 mergeSchema

  1. If the schema is compatible you can use mergeSchema

spark.read.option("mergeSchema", "true").parquet("Dir/")

文档:https://spark.apache.org/docs/latest/sql-programming-guide.html#partition-discovery

  1. 如果列是不兼容的类型,您需要读取单个目录,那么您需要使用

  1. If the columns are incompatible type you need to read individual directories then you need to convert them to jsonRDD with

df.toJSON

然后联合所有的jsonRDD

and then union all the jsonRDD

   df.toJSON.union(df2.toJSON)

随后转换回镶木地板

   spark.read.json(finalJsonRDD)

这篇关于Spark 从不同的模式目录中读取数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆