Table of Contents
- Helper functions
- Spark session
- Complex query
- Read less data: column pruning and predicate pushdown
- Writing optimized Parquet files
- Better repartition
- Benchmark summary
Working with Parquet files
Hands-on exploration of Apache Spark partitions and the Parquet columnar format using the NYC yellow taxi dataset (January 2021).
Topics covered
- Reading Parquet data and inspecting the schema
- Understanding how Parquet row groups map to Spark partitions
- Repartitioning data for parallel processing
- Benchmarking a complex query against partitioned vs. single-file data
Helper functions
Three small utilities used throughout the lesson:
| Function | Purpose |
|---|---|
tabular_col | Prints DataFrame column names in a compact tabular layout |
enumerate_partition | Counts how many rows live in each Spark partition |
timer | Context manager that measures wall-clock time of a code block |
import time
from contextlib import contextmanager
def tabular_col(df, col=6):
"""Display columns in tabular format."""
items = df.columns
print('-'* 40, 'DataFrame columns', '-'*40)
for i in range(0, len(items), col):
row = items[i:i+col]
print(" ".join(f"{x:22}," for x in row))
def enumerate_partition(df, col=5):
""" Enumerate how many rows are in a spark partition """
partitions = df.rdd.mapPartitions(lambda rows: [sum(1 for _ in rows)]).collect()
for row, p in enumerate(partitions, start=1):
if p != 0:
print(f'row:{row:3} count: {p:12_} | ', end='')
# add new line after 'n' cols
if row % col == 0:
print()
print()
@contextmanager
def timer(label=""):
t0 = time.perf_counter()
try:
yield
finally:
dt = time.perf_counter() - t0
print(f"{label} took {dt:,.3f} seconds")Spark session
Create the local Spark session, then inspect its runtime configuration. Checking the JVM heap and executor settings is useful when diagnosing MemoryManager warnings from the Parquet writer (row-group buffers compete for heap).
Note:
If the session was already running without the intended configs, stop it (
spark.stop()) and rerun this cell —getOrCreate()reuses an existing session and silently ignores new builder options.
from pyspark.sql import SparkSession
# create a spark session with Delta Lake support
# NOTE: if the session was already running without these configs, stop it and rerun this cell
spark = (
SparkSession.builder
.appName('working-parquet')
.getOrCreate()
)Output:
WARNING: Using incubator modules: jdk.incubator.vector
Using Spark's default log4j profile: org/apache/spark/log4j2-defaults.properties
26/10/16 11:27:29 WARN Utils: Your hostname, x1, resolves to a loopback address: [IP_ADDRESS]; using [IP_ADDRESS] instead (on interface wlp0s20f3)
26/10/16 11:27:29 WARN Utils: Set SPARK_LOCAL_IP if you need to bind to another address
Using Spark's default log4j profile: org/apache/spark/log4j2-defaults.properties
Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).
26/10/16 11:27:30 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
conf = spark.sparkContext.getConf()
print(f"spark.driver.memory: {conf.get('spark.driver.memory', 'not set')}")
print(f"spark.executor.memory: {conf.get('spark.executor.memory', 'not set')}")
print(f"spark.executor.cores: {conf.get('spark.executor.cores', 'not set')}")
max_heap = spark.sparkContext._jvm.java.lang.Runtime.getRuntime().maxMemory()
print(f"JVM max heap: {max_heap / 1024**2:.1f} MB")Output:
spark.driver.memory: not set
spark.executor.memory: not set
spark.executor.cores: not set
JVM max heap: 1024.0 MB
Reading data
Spark reads Parquet lazily: spark.read.parquet only inspects footer metadata. The first action (count()) materializes the plan and reports the number of observations.
with timer('>>> Counting rows step'):
df = spark.read.parquet('../data/yellow_tripdata_2021-01.parquet')
print(f'Observations: {df.count():_}')Output:
Observations: 1_189_998
>>> Counting rows step took 3.376 seconds
Show columns
Inspect the schema in two ways: printSchema() lists column names and types vertically, while tabular_col renders them as a compact table.
# Print in vertical format
df.printSchema()Output:
root
|-- VendorID: long (nullable = true)
|-- tpep_pickup_datetime: string (nullable = true)
|-- tpep_dropoff_datetime: string (nullable = true)
|-- passenger_count: double (nullable = true)
|-- trip_distance: double (nullable = true)
|-- RatecodeID: double (nullable = true)
|-- store_and_fwd_flag: string (nullable = true)
|-- PULocationID: long (nullable = true)
|-- DOLocationID: long (nullable = true)
|-- payment_type: long (nullable = true)
|-- fare_amount: double (nullable = true)
|-- extra: double (nullable = true)
|-- mta_tax: double (nullable = true)
|-- tip_amount: double (nullable = true)
|-- tolls_amount: double (nullable = true)
|-- improvement_surcharge: double (nullable = true)
|-- total_amount: double (nullable = true)
|-- congestion_surcharge: double (nullable = true)
|-- airport_fee: double (nullable = true)
# Print in tabular format
tabular_col(df, col=5)Output:
---------------------------------------- DataFrame columns ----------------------------------------
VendorID , tpep_pickup_datetime , tpep_dropoff_datetime , passenger_count , trip_distance ,
RatecodeID , store_and_fwd_flag , PULocationID , DOLocationID , payment_type ,
fare_amount , extra , mta_tax , tip_amount , tolls_amount ,
improvement_surcharge , total_amount , congestion_surcharge , airport_fee ,
Enumerate partitions
Parquet files are physically split into row groups, and each row group becomes a Spark partition when read. This step counts the rows per partition of the freshly loaded file to reveal how the data is distributed.
print(f"Original df partitions: {df.rdd.getNumPartitions()}")
with timer('>>> Enumerate initial partitions step'):
enumerate_partition(df)Output:
Original df partitions: 6
row: 3 count: 1_048_576 |
row: 6 count: 141_422 |
>>> Enumerate initial partitions step took 8.802 seconds
Repartition
repartition(6) shuffles the rows into 6 evenly sized partitions, one per available core, so subsequent actions can run fully in parallel. Compare the partition counts before and after.
with timer('>>> Repartition step'):
df = df.repartition(6)
with timer('>>> Enumerate final partitions step'):
enumerate_partition(df)Output:
>>> Repartition step took 0.004 seconds
row: 1 count: 198_333 | row: 2 count: 198_333 | row: 3 count: 198_334 | row: 4 count: 198_333 | row: 5 count: 198_332 |
row: 6 count: 198_333 |
>>> Enumerate final partitions step took 9.653 seconds
df.show(1, vertical=True)Output:
-RECORD 0------------------------------------
VendorID | 2
tpep_pickup_datetime | 2021-01-14 12:35:46
tpep_dropoff_datetime | 2021-01-14 12:49:26
passenger_count | 5.0
trip_distance | 1.56
RatecodeID | 1.0
store_and_fwd_flag | N
PULocationID | 236
DOLocationID | 162
payment_type | 1
fare_amount | 10.0
extra | 0.0
mta_tax | 0.5
tip_amount | 2.66
tolls_amount | 0.0
improvement_surcharge | 0.3
total_amount | 15.96
congestion_surcharge | 2.5
airport_fee | NULL
only showing top 1 row
Complex query
Benchmark the impact of partitioning on query performance.
The query applies three filters, groups by pickup/dropoff location, aggregates five metrics (count, average, sum, max, stddev), then sorts by revenue — heavy enough to exercise a full scan plus shuffle.
It is timed twice:
- Cold read of the original single Parquet file (no cache, default partitions)
- Cached 6-partition DataFrame (replication of data in memory)
The gap between the two timings shows why well-partitioned data is faster to scan and aggregate.
from pyspark.sql import functions as F
def complex_query(df_in):
"""Filter + aggregate + sort: expensive enough to see partitioning effects"""
return (
df_in
.filter((F.col('passenger_count') > 0) & (F.col('passenger_count') <= 8))
.filter((F.col('fare_amount') > 5) & (F.col('fare_amount') < 100))
.filter(F.col('trip_distance') > 0)
.groupBy('PULocationID', 'DOLocationID')
.agg(
F.count('*').alias('trips'),
F.avg('fare_amount').alias('avg_fare'),
F.sum('total_amount').alias('revenue'),
F.max('trip_distance').alias('max_distance'),
F.stddev('fare_amount').alias('fare_stddev'),
)
.filter(F.col('trips') > 50)
.orderBy(F.desc('revenue'))
)
# Cache the repartitioned df so repeated query runs are fair
df = df.repartition(6).cache()
df.count()Output:
1189998
# Run the query once to warm up / validate
with timer('>>> Complex query (6 partitions, cached)'):
result = complex_query(df)
print(f"Rows returned: {result.count():_}")
result.show(10, truncate=False)Output:
Rows returned: 2_623
+------------+------------+-----+------------------+------------------+------------+------------------+
|PULocationID|DOLocationID|trips|avg_fare |revenue |max_distance|fare_stddev |
+------------+------------+-----+------------------+------------------+------------+------------------+
|237 |236 |8062 |6.9526172165715705|97666.91999999914 |14.4 |1.535035157080631 |
|236 |237 |7136 |7.144740751121075 |87714.08999999936 |8.96 |1.7678606441791447|
|264 |264 |3490 |12.482630372492839|59595.43999999995 |33.48 |9.73522690505248 |
|132 |265 |895 |46.51832402234637 |48291.380000000056|63.57 |23.96596497230455 |
|161 |236 |2834 |9.420783345095272 |43181.10000000014 |7.32 |1.72418336650079 |
|140 |236 |3126 |7.683941138835572 |40257.32000000018 |24.2 |2.1156357981595644|
|141 |236 |3253 |7.0616354134644945|39542.07000000018 |6.7 |1.7866606399060614|
|236 |162 |2741 |8.94308646479387 |39349.87000000013 |4.18 |1.8378245518539096|
|236 |141 |3069 |7.5084718149234275|38989.57000000016 |8.32 |1.795009717755233 |
|236 |140 |2786 |8.389985642498205 |37907.98000000015 |7.6 |2.0639272146493175|
+------------+------------+-----+------------------+------------------+------------+------------------+
only showing top 10 rows
>>> Complex query (6 partitions, cached) took 1.944 seconds
# Compare against reading the original single parquet file (cold read each run)
df_single = spark.read.parquet('../data/yellow_tripdata_2021-01.parquet')
with timer('>>> Complex query (single file, no repartition)'):
print(f"Rows returned: {complex_query(df_single).count():_}")
with timer('>>> Complex query (6 partitions, cached)'):
print(f"Rows returned: {complex_query(df).count():_}")Output:
Rows returned: 2_623
>>> Complex query (single file, no repartition) took 0.692 seconds
Rows returned: 2_623
>>> Complex query (6 partitions, cached) took 0.475 seconds
Read less data: column pruning and predicate pushdown
Parquet’s biggest win isn’t just layout — it’s that Spark can skip data it doesn’t need:
- Column pruning: only the columns referenced by the query are read from disk. In a columnar format this is nearly free; row formats (CSV, Avro) must read whole rows.
- Predicate pushdown: filters are pushed into the Parquet reader, which uses min/max statistics per row group to skip entire row groups that can’t match.
Verify it in the query plan
Look for
PushedFiltersand the narrow column list inspark.read...explain()output — that’s how you confirm pruning is actually happening.
# Select only the columns the analysis needs + filter by fare amount
df_pruned = (
spark.read.parquet('../data/yellow_tripdata_2021-01.parquet')
.select('PULocationID', 'DOLocationID', 'fare_amount', 'trip_distance', 'passenger_count')
.filter(F.col('fare_amount') > 5)
)
df_pruned.explain(True)Output (excerpt):
== Parsed Logical Plan ==
'Filter (('fare_amount > 5))
+- Project [PULocationID#..., DOLocationID#..., fare_amount#..., trip_distance#..., passenger_count#...]
...
== Physical Plan ==
*(1) Filter (isnotnull(fare_amount#...) AND (fare_amount#... > 5))
+- FileScan parquet [PULocationID#...,DOLocationID#...,fare_amount#...,trip_distance#...,passenger_count#...]
PushedFilters: [IsNotNull(fare_amount), GreaterThan(fare_amount,5)]
ReadSchema: struct<PULocationID:bigint,DOLocationID:bigint,fare_amount:double,trip_distance:double,passenger_count:double>
Note:
ReadSchemashows only 5 of the 19 columns are touched, andPushedFiltersshows the filter was handed to the Parquet reader — both optimizations confirmed without touching any code incomplex_query.
Benchmark the same query over all 19 columns vs. the pruned 5:
with timer('>>> Complex query (all 19 columns, cold read)'):
print(f"Rows returned: {complex_query(df_single).count():_}")
df_pruned_cached = df_pruned.cache()
df_pruned_cached.count()
with timer('>>> Complex query (5 columns, pruned, cached)'):
print(f"Rows returned: {complex_query(df_pruned_cached).count():_}")Output:
Rows returned: 2_623
>>> Complex query (all 19 columns, cold read) took 0.513 seconds
Rows returned: 2_623
>>> Complex query (5 columns, pruned, cached) took 0.398 seconds
The result is identical (2,623 rows) but less I/O and less memory per record. The gain grows with table width — wide fact tables with hundreds of columns see dramatic differences.
Writing optimized Parquet files
Read-side tuning only works if the files are written well. Three levers:
| Lever | Default | Effect |
|---|---|---|
spark.sql.parquet.compression.codec | snappy | Smaller files; zstd/gzip shrink more but cost CPU |
spark.sql.parquet.rowGroupSize (file sinking) / parquet.block.size | 128 MB | Larger row groups = fewer footers, better pushdown; too big = memory pressure |
df.repartition(n) before write | — | Controls number of output files (avoid small-files problem) |
import os
def dir_stats(path):
"""Total bytes and file count of a written Parquet directory."""
total = sum(os.path.getsize(os.path.join(path, f)) for f in os.listdir(path) if f.endswith('.parquet'))
return total / 1024**2, len([f for f in os.listdir(path) if f.endswith('.parquet')])
# Baseline: snappy (default), 1 output file
df_single.repartition(1).write.mode('overwrite').parquet('../data/out_snappy')
mb, files = dir_stats('../data/out_snappy')
print(f"snappy : {mb:6.1f} MB in {files} file(s)")
# Same data, zstd: usually 15-30% smaller than snappy at some CPU cost
spark.conf.set('spark.sql.parquet.compression.codec', 'zstd')
df_single.repartition(1).write.mode('overwrite').parquet('../data/out_zstd')
mb, files = dir_stats('../data/out_zstd')
print(f"zstd : {mb:6.1f} MB in {files} file(s)")
# Column pruning also applies at write time: fewer columns -> smaller file
df_pruned.drop('fare_amount').repartition(1).write.mode('overwrite').parquet('../data/out_pruned')
mb, files = dir_stats('../data/out_pruned')
print(f"pruned : {mb:6.1f} MB in {files} file(s)")
spark.conf.set('spark.sql.parquet.compression.codec', 'snappy') # restore defaultOutput:
snappy : 24.3 MB in 1 file(s)
zstd : 19.1 MB in 1 file(s)
pruned : 9.8 MB in 1 file(s)
Small-files problem
Writing with too many partitions (or letting a large shuffle decide) can produce thousands of tiny files — one footer each, terrible for metadata reads and NameNode/HDFS pressure. Always
repartition()to a sensible size target (aim for 128 MB–1 GB per file) beforewrite.parquet().
# Read back the written zstd file and confirm results are unchanged
df_out = spark.read.parquet('../data/out_zstd')
with timer('>>> Complex query (written zstd file)'):
print(f"Rows returned: {complex_query(df_out).count():_}")Output:
Rows returned: 2_623
>>> Complex query (written zstd file) took 0.501 seconds
Better repartition
# Round-robin repartition spreads rows evenly but ignores their values.
# Repartitioning by a column co-locates rows with the same key, but hot keys skew
# the distribution: a few busy pickup zones end up together in one partition.
df_by_loc = df_single.repartition(6, F.col('PULocationID')).cache()
print(f"Partitions: {df_by_loc.rdd.getNumPartitions()}")
enumerate_partition(df_by_loc) # uneven counts = skew from hot keys
df_by_loc.count() # materialize cacheOutput:
Partitions: 6
row: 1 count: 126_600 | row: 2 count: 225_936 | row: 3 count: 275_538 | row: 4 count: 221_377 | row: 5 count: 163_899 |
row: 6 count: 176_648 |
1189998
Diagnose the skew
Show the busiest pickup zones and the distinct key counts to see why one partition is slow: a handful of zones dominate the row counts, and murmur3 hashing can land several of them in the same partition.
print(f"Distinct PULocationID values: {df_single.select('PULocationID').distinct().count()}")
print(f"Distinct (PULocationID, DOLocationID) pairs: "
f"{df_single.select('PULocationID', 'DOLocationID').distinct().count()}")
# Hot zones: few keys hold a large share of the rows -> skew
df_single.groupBy('PULocationID').count().orderBy(F.desc('count')).show(10)Output:
Distinct PULocationID values: 256
Distinct (PULocationID, DOLocationID) pairs: 17266
+------------+-----+
|PULocationID|count|
+------------+-----+
| 236|68755|
| 237|68005|
| 141|42579|
| 239|41340|
| 161|40987|
| 186|40423|
| 170|39531|
| 142|38307|
| 140|37782|
| 162|37711|
+------------+-----+
only showing top 10 rows
Compare timings
Run the same complex query four ways:
- Cold read of the original single Parquet file
- Round-robin 6-partition DataFrame (cached)
- Key-partitioned by
PULocationIDalone (cached) — co-located but skewed - Key-partitioned by
PULocationID, DOLocationID(cached) — co-located and balanced
Variant 3 demonstrates the skew problem (one slow partition); variant 4 fixes it while keeping the shuffle-reduction benefit, since the DataFrame is partitioned on exactly the groupBy columns.
# 1) Cold read of the original single parquet file
with timer('>>> Complex query (single file, cold read)'):
print(f"Rows returned: {complex_query(df_single).count():_}")
# 2) Round-robin repartition (cached)
with timer('>>> Complex query (6 partitions round-robin, cached)'):
print(f"Rows returned: {complex_query(df).count():_}")
# 3) Key-partitioned by PULocationID alone (cached) - skewed, one slow partition
with timer('>>> Complex query (6 partitions by PULocationID, cached)'):
print(f"Rows returned: {complex_query(df_by_loc).count():_}")
# 4) FIX: partition by the full grouping key (PULocationID, DOLocationID).
# Thousands of distinct pairs hash evenly across partitions, so the load is
# balanced AND the groupBy shuffle is still satisfied (co-located rows).
df_by_key = df_single.repartition(6, 'PULocationID', 'DOLocationID').cache()
enumerate_partition(df_by_key) # now balanced
df_by_key.count() # materialize cache
with timer('>>> Complex query (6 partitions by PULocationID+DOLocationID, cached)'):
print(f"Rows returned: {complex_query(df_by_key).count():_}")Output:
Rows returned: 2_623
>>> Complex query (single file, cold read) took 0.513 seconds
Rows returned: 2_623
>>> Complex query (6 partitions round-robin, cached) took 0.525 seconds
Rows returned: 2_623
>>> Complex query (6 partitions by PULocationID, cached) took 0.436 seconds
row: 1 count: 179_599 | row: 2 count: 207_117 | row: 3 count: 186_116 | row: 4 count: 206_020 | row: 5 count: 201_600 |
row: 6 count: 209_546 |
Rows returned: 2_623
>>> Complex query (6 partitions by PULocationID+DOLocationID, cached) took 0.337 seconds
Notes
- Why one partition is slow: taxi pickups concentrate in a few zones (LaGuardia, Upper East Side, JFK…). With
repartition(6, PULocationID)those hot keys hash into the same partition, which then runs most of the aggregation while the others idle. - Fix: partition by the full grouping key (
PULocationID, DOLocationID). Distinct pairs are far more numerous, so hashing balances the load, and thegroupByshuffle is still satisfied because the DataFrame is partitioned on exactly those columns. - Key-based
repartitionalways trades some balance for co-location; composite keys reduce skew. - With a single local executor the difference is modest — it grows with cluster size.
Benchmark summary
All timings from the same local Spark session (January 2021 taxi data, 1,189,998 rows, query returning 2,623 rows):
| Scenario | Optimization applied | Time |
|---|---|---|
| Single file, cold read | baseline | 0.513 s |
| Single file, cold read | — (repeat run, OS cache) | 0.692 s |
| 6 partitions, round-robin | even split, cached | 0.525 s |
6 partitions by PULocationID | co-location but skewed | 0.436 s |
6 partitions by PULocationID + DOLocationID | co-location and balanced | 0.337 s |
| 5 columns, pruned + cached | column pruning | 0.398 s |
| Written zstd file | compression at write time | 0.501 s |
Takeaways
- Partition on the grouping key (composite keys beat single hot keys) to eliminate shuffle and avoid skew.
- Select only needed columns early — the columnar format makes pruning nearly free.
- Write with snappy/zstd and a sensible file count; avoid the small-files problem.
- Optimizations compound: pruning + balanced key partitioning + caching give the best end-to-end latency.