What are the best practices for data partitioning and repartitioning in PySpark?
Instruction: Discuss how to effectively partition data in PySpark to optimize parallel processing and reduce shuffle operations.
Updated
There are several distinct meanings of partitioning:
- A DataFrame's execution partitions divide work among tasks.
repartition(n, "key")shuffles rows using the specified key;repartition(n)redistributes without that key contract. - A writer's
partitionBy("day")creates a directory layout based on values. It does not pin rows to an executor or promise to eliminate later shuffles. - A window specification's
partitionBy("user")defines independent logical window groups. It is not the writer API.
This local fixture demonstrates execution repartitioning separately from disk layout, using an existing classic session named spark:
from pathlib import Path
from tempfile import TemporaryDirectory
data = spark.createDataFrame([(1, "east"), (2, "west"), (3, "east")], "id int, region string")
by_region = data.repartition(3, "region")
assert by_region.rdd.getNumPartitions() == 3
assert by_region.coalesce(2).rdd.getNumPartitions() == 2
with TemporaryDirectory() as directory:
path = str(Path(directory) / "regions")
by_region.write.partitionBy("region").parquet(path)
restored = spark.read.parquet(path)
assert [(r.id, r.region) for r in restored.orderBy("id").collect()] == [
(1, "east"), (2, "west"), (3, "east")
]
Use shared storage rather than a driver-local temporary directory on a cluster. The three-row fixture verifies semantics, not a recommended partition count.
Choose task size and count from measured bytes, CPU, spill, skew and available slots. coalesce reduces partitions with a narrow dependency and cannot increase their count; drastic reduction can constrain parallelism. Repartitioning after a filter may rebalance work but has a shuffle cost. Increasing the count while hashing by the same hot key does not split that key.
Use moderate-cardinality directory keys aligned with pruning needs; avoid blindly partitioning by unique customer/event IDs. Check adaptive execution's final plan and output-file counts rather than applying a universal MB target. Preserve row multiplicity and aggregation results when changing the layout.