python - 如何从按月分区的镶木地板文件中删除特定月份
问题描述
我有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
删除特定月份数据的正确方法是什么?
解决方案
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")
推荐阅读
- python - 如何以非字典顺序排列 Pandas multiIndex 项目
- python - U-net 图像分割的 Dice 系数不增加
- javascript - 如何使用 JS 激活 Bootstrap 5.0(beta 3)导航栏链接
- flutter - Flutter BLoC 架构中自定义辅助类的放置位置
- amazon-web-services - 如何以编程方式停止 AWS Fargate 容器?
- javascript - Laravel (Vue.js) - 如何从导入的库中删除未使用的 JavaScript?
- python-3.x - cv2.imwrite 不提供图像输出
- spring-boot - Aurora 数据库架构自动更改并破坏 API
- javascript - 如何调试 Python Django Errno 54 'Connection reset by peer'
- node.js - 如何使用 node.js 从 google adwords 中的 location_id 获取位置名称?