首页 > 解决方案 > 如何从按月分区的镶木地板文件中删除特定月份

问题描述

我有monthly过去 5 年的收入数据,并且我将各个月份的 DataFrames 以模式的parquet格式存储append,但列。这是下面的伪代码 -partitioned by month

def Revenue(filename):
    df = spark.read.load(filename)
    .
    .
    df.write.format('parquet').mode('append').partitionBy('month').save('/path/Revenue')

Revenue('Revenue_201501.csv')
Revenue('Revenue_201502.csv')
Revenue('Revenue_201503.csv')
Revenue('Revenue_201504.csv')
Revenue('Revenue_201505.csv')

每月df以格式存储,parquet如下所示 -

在此处输入图像描述

问题:如何删除parquet特定月份对应的文件夹?

一种方法是将所有这些parquet文件加载​​到一个大文件中df,然后使用.where()子句过滤掉该特定月份,然后以模式将其保存回parquet格式partitionBy月份overwrite,如下所示 -

# If we want to remove data from Feb, 2015
df = spark.read.format('parquet').load('Revenue.parquet')
df = df.where(col('month') != lit('2015-02-01'))
df.write.format('parquet').mode('overwrite').partitionBy('month').save('/path/Revenue')

但是,这种方法相当麻烦。

另一种方法是直接删除该特定月份的文件夹,但我不确定这是否是处理事情的正确方法,以免我们metadata以不可预见的方式更改。

parquet删除特定月份数据的正确方法是什么?

标签: pythonapache-sparkpysparkparquet

解决方案


Spark 支持删除分区,包括数据和元数据。
引用 scala 代码注释

/**
 * Drop Partition in ALTER TABLE: to drop a particular partition for a table.
 *
 * This removes the data and metadata for this partition.
 * The data is actually moved to the .Trash/Current directory if Trash is configured,
 * unless 'purge' is true, but the metadata is completely lost.
 * An error message will be issued if the partition does not exist, unless 'ifExists' is true.
 * Note: purge is always false when the target is a view.
 *
 * The syntax of this command is:
 * {{{
 *   ALTER TABLE table DROP [IF EXISTS] PARTITION spec1[, PARTITION spec2, ...] [PURGE];
 * }}}
 */

在您的情况下,没有后备表。我们可以将数据帧注册为临时表并使用上述语法(临时表文档

在 pyspark 中,我们可以使用此链接 示例中的语法运行 SQL:

df = spark.read.format('parquet').load('Revenue.parquet'). registerTempTable("tmp")
spark.sql("ALTER TABLE tmp DROP IF EXISTS PARTITION (month='2015-02-01') PURGE")

推荐阅读