我希望通过将巨大的csv文件细分为不同的分区来优化Spark应用程序的运行时,具体取决于它们的特性。
E.g。我有一个包含客户ID的列(整数,a),一个包含日期的列(月份+年份,例如01.2015,b),以及一个包含产品ID的列(整数,c)(以及更多包含产品特定数据的列,不需要用于分区)。
我想构建一个像/customer/a/date/b/product/c
这样的文件夹结构。当用户想要了解2016年1月出售的客户X的产品信息时,他可以加载并分析/customer/X/date/01.2016/*
中保存的文件。
是否有可能通过通配符加载此类文件夹结构?还应该可以加载特定时间范围的所有客户或产品,例如, 2015年1月至2015年9月。是否可以使用/customer/*/date/*.2015/product/c
之类的通配符?或者如何解决这样的问题?
我想对数据进行一次分区,然后在分析中加载特定文件,以减少这些作业的运行时间(忽略分区的额外工作)。
解决方案:使用Parquet文件
我更改了我的Spark应用程序以将我的数据保存到Parquet文件,现在一切正常,我可以通过给出文件夹结构来预先选择数据。这是我的代码片段:
JavaRDD<Article> goodRdd = ...
SQLContext sqlContext = new SQLContext(sc);
List<StructField> fields = new ArrayList<StructField>();
fields.add(DataTypes.createStructField("keyStore", DataTypes.IntegerType, false));
fields.add(DataTypes.createStructField("textArticle", DataTypes.StringType, false));
StructType schema = DataTypes.createStructType(fields);
JavaRDD<Row> rowRDD = goodRdd.map(new Function<Article, Row>() {
public Row call(Article article) throws Exception {
return RowFactory.create(article.getKeyStore(), article.getTextArticle());
}
});
DataFrame storeDataFrame = sqlContext.createDataFrame(rowRDD, schema);
// WRITE PARQUET FILES
storeDataFrame.write().partitionBy(fields.get(0).name()).parquet("hdfs://hdfs-master:8020/user/test/parquet/");
// READ PARQUET FILES
DataFrame read = sqlContext.read().option("basePath", "hdfs://hdfs-master:8020/user/test/parquet/").parquet("hdfs://hdfs-master:8020/user/test/parquet/keyStore=1/");
System.out.println("READ : " + read.count());
重要
不要尝试只有一列的桌子!当您尝试调用partitionBy
方法时,您将获得例外!
答案 0 :(得分:21)
因此,在Spark中,您可以按照您要查找的方式保存和读取分区数据。但是,不是像/customer/a/date/b/product/c
那样创建路径,而是在使用以下方法保存数据时,Spark将使用此约定/customer=a/date=b/product=c
:
df.write.partitionBy("customer", "date", "product").parquet("/my/base/path/")
当您需要读入数据时,需要指定basepath-option
,如下所示:
sqlContext.read.option("basePath", "/my/base/path/").parquet("/my/base/path/customer=*/date=*.2015/product=*/")
并且/my/base/path/
后面的所有内容都将被Spark解释为列。在此处给出的示例中,Spark会将三列customer
,date
和product
添加到数据框中。请注意,您可以根据需要为任何列使用通配符。
至于在特定时间范围内读取数据,您应该知道Spark使用谓词下推,因此它实际上只会将数据加载到符合条件的内存中(由某些过滤器转换指定)。但是,如果您确实要明确指定范围,则可以生成路径名列表,然后将其传递给read函数。像这样:
val pathsInMyRange = List("/my/path/customer=*/date=01.2015/product=*",
"/my/path/customer=*/date=02.2015/product=*",
"/my/path/customer=*/date=03.2015/product=*"...,
"/my/path/customer=*/date=09.2015/product=*")
sqlContext.read.option("basePath", "/my/base/path/").parquet(pathsInMyRange:_*)
无论如何,我希望这会有所帮助:)