【问题标题】:Is there a way to control number of part files in hdfs created from spark dataframe? [duplicate]有没有办法控制从 spark 数据帧创建的 hdfs 中的零件文件数量? [复制]
【发布时间】:2023-03-18 22:15:01
【问题描述】:

当我将 sparksql 查询产生的 DataFrame 保存在 HDFS 中时,它会生成大量的部分文件,每个部分文件大小为 1.4 KB。有没有办法增加文件的大小,因为每个部分文件包含大约 2 条记录。

df_crimes_dates_formated = spark.sql('SELECT CONCAT( SUBSTR(Dates,1,2), SUBSTR(Dates,7,4)) AS DATES , Primary_Type , COUNT(1) AS COUNT  FROM crimes_data Group By CONCAT( SUBSTR(Dates,1,2), SUBSTR(Dates,7,4)) , Primary_Type ORDER BY CONCAT( SUBSTR(Dates,1,2), SUBSTR(Dates,7,4)) , COUNT(1) DESC' )

df_crimes_dates_formated.write.save('hdfs:///user/maria_dev/crimes/monthly_crimes/') 

【问题讨论】:

  • 可以查看分区数,然后重新分区吗?

标签: pyspark hdfs pyspark-sql


【解决方案1】:

您可以根据您的用例使用.repartition() (or) .coalesce() 来控制HDFS 中的文件数量。

#to get number of partitions of dataframe, spark creates part files depends on number of partitions in dataframe
>>> df_crimes_dates_formated.rdd.getNumPartitions()

#create 10 part files in HDFS
>>> df_crimes_dates_formated.repartition(10).write.save('hdfs:///user/maria_dev/crimes/monthly_crimes/') 

Caluculating number of partitons dynamically:

您可以得出每个分区将拥有的行数,这样
将给出所需的文件大小,然后将其除以数据帧计数以动态确定分区数。

df.count()
#3

#req rows for each partition
rows=1
par=df.count()/rows
partitions=int('1' if par <= 0 else par)

#repartition with partitions value
df.repartition(partitions).rdd.getNumPartitions()
#3

另外:

从 Spark-2.2 开始,如果我们在数据帧中有 1 个分区并控制写入文件的行数,请使用 maxRecordsPerFile 选项。

#assuming df_crimes_dates_formated having 1 partition then spark creates each file with 100 records in it.
df_crimes_dates_formated.write.option("maxRecordsPerFile", 100).save("hdfs:///user/maria_dev/crimes/monthly_crimes/")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-19
    • 2016-09-21
    • 1970-01-01
    • 1970-01-01
    • 2015-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多