library(tidyverse)
library(arrow)
library(duckdb)13 Parquet: columns that compress
13.1 Introduction
In 2010 engineers at Google described Dremel, the system they used to query enormous tables in seconds (Melnik et al. 2010). Part of its secret was storage: instead of writing a table row by row, Dremel wrote it column by column. In March 2013 Twitter and Cloudera announced an open file format built on the same idea, called Parquet. It became an Apache project, and then the standard way to store analytical data: Python, R, Julia, Java, Rust, Go, Spark, DuckDB and every major cloud service read and write it. A Parquet file you write from R today will open in tools that have not been invented yet, because its specification is open and it has many independent implementations.
Parquet is also where Part II of this book comes to life. Inside a Parquet file you will find dictionary encoding, run-length encoding, bit packing and a choice of the codecs from Chapter 10, all applied column by column. This chapter looks inside a file, measures what each idea buys, and shows how to make your files both small and fast to read.
Prerequisites
arrow reads and writes Parquet. DuckDB appears briefly, to look inside a file; Chapter 15 covers it properly. The data are the dimuon events, read with declared types as in Chapter 12:
dimuon <- read_csv("data/dimuon.csv.gz", col_types = "iidddidddi")
dir.create("scratch", showWarnings = FALSE)13.2 Rows and columns
A CSV file stores a table the way you read it: the first row, then the second, then the third.
2301,1,11.327,1.4866,1.6389,1,5.534,1.9578,1.8601,1
2301,2,24.276,0.2864,-0.6402,1,4.772,0.2233,-0.3567,-1
2301,3,13.371,-1.4485,-3.0105,1,12.036,-1.5876,2.8936,-1
A columnar format stores all the values of the first column, then all of the second, and so on:
run: 2301, 2301, 2301, ...
event: 1, 2, 3, ...
mu1_pt: 11.327, 24.276, 13.371, ...
If you learned Fortran, you know this layout: it is how Fortran stores a matrix, column by column (Chapter 3). Storing by column has three big advantages for analysis. A query that needs two columns out of fifty reads only those two. Values of the same kind sit next to each other, and similar values compress far better than a jumble of different kinds. And each column can be encoded in the way that suits its type and its values.
13.3 Writing and reading
write_parquet() writes a data frame and read_parquet() reads one back:
write_parquet(dimuon, "scratch/dimuon.parquet")
read_parquet("scratch/dimuon.parquet")
#> # A tibble: 119,528 × 10
#> run event mu1_pt mu1_eta mu1_phi mu1_charge mu2_pt mu2_eta mu2_phi
#> * <int> <int> <dbl> <dbl> <dbl> <int> <dbl> <dbl> <dbl>
#> 1 2301 1 11.3 1.49 1.64 1 5.53 1.96 1.86
#> 2 2301 2 24.3 0.286 -0.640 1 4.77 0.223 -0.357
#> 3 2301 3 13.4 -1.45 -3.01 1 12.0 -1.59 2.89
#> 4 2301 4 19.1 0.149 1.72 1 16.6 -0.034 1.93
#> 5 2301 5 11.8 -2.21 2.19 1 7.29 -2.26 1.97
#> 6 2301 6 11.1 1.39 1.08 1 4.57 1.37 0.635
#> 7 2301 7 14.5 -0.637 2.99 1 5.03 -0.813 -3.11
#> 8 2301 8 16.7 0.246 1.60 1 11.4 0.391 1.32
#> 9 2301 9 6.92 0.113 1.25 -1 4.55 -0.432 1.50
#> 10 2301 10 16.4 2.35 -2.08 -1 12.7 2.17 -1.95
#> # ℹ 119,518 more rows
#> # ℹ 1 more variable: mu2_charge <int>Unlike CSV, the file records each column’s type, so nothing has to guess. col_select reads only the columns you name, and the rest of the file is never decompressed:
read_parquet("scratch/dimuon.parquet", col_select = c(mu1_pt, mu2_pt))
#> # A tibble: 119,528 × 2
#> mu1_pt mu2_pt
#> * <dbl> <dbl>
#> 1 11.3 5.53
#> 2 24.3 4.77
#> 3 13.4 12.0
#> 4 19.1 16.6
#> 5 11.8 7.29
#> 6 11.1 4.57
#> 7 14.5 5.03
#> 8 16.7 11.4
#> 9 6.92 4.55
#> 10 16.4 12.7
#> # ℹ 119,518 more rowsOn a table this size every read is instant. On a hundred columns and a billion rows, reading two columns instead of a hundred is the difference between seconds and an hour.
13.4 Inside a Parquet file
A Parquet file is organised in three levels. The rows are split into row groups, typically up to about a million rows each. Within a row group, each column’s values are stored together as a column chunk. Each chunk is divided into pages, and each page is first encoded, which rewrites the values in a more compact form, and then compressed with a codec. At the end of the file a footer records where everything is, plus statistics for each column chunk: its minimum and maximum value and its number of missing values.
DuckDB can read that footer. Its parquet_metadata() function returns one row per column chunk, and duckdb’s tbl_function() makes the result a table you can work on with dplyr:
con <- dbConnect(duckdb())
inside <- tbl_function(con, "parquet_metadata('scratch/dimuon.parquet')") |>
select(column = path_in_schema, encodings, compression, bytes = total_compressed_size) |>
collect()
inside
#> # A tibble: 10 × 4
#> column encodings compression bytes
#> <chr> <chr> <chr> <dbl>
#> 1 run PLAIN, RLE, RLE_DICTIONARY SNAPPY 275
#> 2 event PLAIN, RLE, RLE_DICTIONARY SNAPPY 269707
#> 3 mu1_pt PLAIN, RLE, RLE_DICTIONARY SNAPPY 371024
#> 4 mu1_eta PLAIN, RLE, RLE_DICTIONARY SNAPPY 475634
#> 5 mu1_phi PLAIN, RLE, RLE_DICTIONARY SNAPPY 549512
#> 6 mu1_charge PLAIN, RLE, RLE_DICTIONARY SNAPPY 15570
#> 7 mu2_pt PLAIN, RLE, RLE_DICTIONARY SNAPPY 305215
#> 8 mu2_eta PLAIN, RLE, RLE_DICTIONARY SNAPPY 473514
#> 9 mu2_phi PLAIN, RLE, RLE_DICTIONARY SNAPPY 541207
#> 10 mu2_charge PLAIN, RLE, RLE_DICTIONARY SNAPPY 15568Every column was written with Snappy, arrow’s default codec, and every column lists three encodings. PLAIN is the raw values; RLE_DICTIONARY means the values were replaced by indices into a dictionary of distinct values, exactly like an R factor (Chapter 11); and RLE is a hybrid of run-length encoding and bit packing that Parquet uses to store those indices and other small integers compactly.
Now look at the sizes. The run column holds 119,528 values in a few hundred bytes. It has only 8 distinct values, so the dictionary is tiny, and the data are sorted by run, so the indices form 8 long runs that run-length encoding collapses to almost nothing. The two charge columns take about 15 kB each. That is no accident:
nrow(dimuon) / 8 / 1000 # kilobytes needed at one bit per value
#> [1] 14.941A charge is +1 or −1 with equal probability, an entropy of exactly one bit (Chapter 4), and Parquet’s dictionary encoding with bit packing stores it in almost exactly one bit per value. Shannon’s floor, met by a file format.
The kinematic columns are another story. Each holds a double with a noisy last digit, and Snappy, which has no entropy coder, can do little with them.
13.5 Making Parquet files smaller
Everything Part II taught applies. Here are four versions of the same table: readr’s defaults with Snappy, zstd instead of Snappy, the kinematics stored as integers in their natural units (MeV for momenta, 10−4 for angles) with zstd, and the same integers with Brotli at its highest level:
as_integers <- dimuon |>
mutate(
across(ends_with("_pt"), \(x) as.integer(round(x * 1000))),
across(ends_with(c("_eta", "_phi")), \(x) as.integer(round(x * 1e4)))
)
parquet_mb <- function(data, ...) {
path <- tempfile(fileext = ".parquet")
write_parquet(data, path, ...)
file.size(path) / 1e6
}
tribble(
~version, ~megabytes,
"doubles, Snappy (default)", parquet_mb(dimuon),
"doubles, zstd level 9", parquet_mb(dimuon, compression = "zstd", compression_level = 9),
"integers, zstd level 9", parquet_mb(as_integers, compression = "zstd", compression_level = 9),
"integers, Brotli level 11", parquet_mb(as_integers, compression = "brotli", compression_level = 11),
"for comparison: gzipped CSV", file.size("data/dimuon.csv.gz") / 1e6
)
#> # A tibble: 5 × 2
#> version megabytes
#> <chr> <dbl>
#> 1 doubles, Snappy (default) 3.03
#> 2 doubles, zstd level 9 2.39
#> 3 integers, zstd level 9 2.26
#> 4 integers, Brotli level 11 1.99
#> 5 for comparison: gzipped CSV 2.53The integers hold exactly the same information as the doubles, because the doubles were rounded to those units in the first place; nothing has been lost. Each step helps, and together they make the file about a third smaller than the default. The highest Brotli level is slow to write, but like all these codecs it reads back quickly.
How close is that to the floor? Using the entropy estimate from Chapter 4, column by column, the information in the integer table can be added up:
entropy_bits <- function(x) {
p <- table(x) / length(x)
-sum(p * log2(p))
}
as_integers |>
select(!c(run, event)) |>
summarise(across(everything(), \(x) entropy_bits(x) * length(x) / 8 / 1e6)) |>
pivot_longer(everything(), names_to = "column", values_to = "entropy_mb") |>
mutate(total_mb = sum(entropy_mb))
#> # A tibble: 8 × 3
#> column entropy_mb total_mb
#> <chr> <dbl> <dbl>
#> 1 mu1_pt 0.215 1.36
#> 2 mu1_eta 0.227 1.36
#> 3 mu1_phi 0.232 1.36
#> 4 mu1_charge 0.0149 1.36
#> 5 mu2_pt 0.197 1.36
#> 6 mu2_eta 0.227 1.36
#> 7 mu2_phi 0.232 1.36
#> 8 mu2_charge 0.0149 1.36The kinematic and charge columns carry about 1.4 MB of information between them, treating each value as independent of the others. The run and event columns add very little, since they could be regenerated from a count. So no format that compresses each column on its own can store this table in much less than about 1.4 MB, and the best Parquet file above is about 0.6 MB from that floor. The remaining gap is the price of a format that keeps every column chunk separately readable, rather than compressing the whole file as one stream. R’s own saveRDS() with xz gets closer, as Chapter 12 found, but only R can read it and it must be decompressed whole.
13.6 Simulation output: the bits a planet deserves
Measured data arrive with their precision attached: the instrument’s noise says which digits are real. Simulation output does not. Every number comes out as a double with sixteen significant digits, and nothing in the file says how many of them the physics supports. The numerical method decides that, and you can measure it.
Here is the solar system for two years, integrated with my orbitr package (Rosenman 2026) by the velocity Verlet method (Verlet 1967) with a one-hour step. load_solar_system() places the Sun, the eight planets, the Moon and Pluto from Keplerian elements, and simulate_system() returns an ordinary tidy table, one row per body per step, ready for everything in this book:
library(orbitr)
solar <- load_solar_system() |>
simulate_system(time_step = seconds_per_hour, duration = 2 * seconds_per_year)
solar
#> # A tibble: 192,863 × 9
#> id mass x y z vx vy vz time
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 Sun 1.99e30 0 0 0 0 0 0 0
#> 2 Mercury 3.30e23 1.01e10 4.48e10 2.73e 9 -57287. 12561. 6280. 0
#> 3 Venus 4.87e24 -7.11e10 8.04e10 5.20e 9 -26354. -23404. 1200. 0
#> 4 Earth 5.97e24 -3.30e10 1.43e11 0 -29520. -6788. 0 0
#> 5 Mars 6.42e23 1.89e11 -8.37e10 -6.40e 9 10750. 24226. 243. 0
#> 6 Jupiter 1.90e27 7.17e11 1.83e11 -1.68e10 -3394. 13287. 21.0 0
#> 7 Saturn 5.68e26 -7.38e10 1.35e12 -2.07e10 -10158. -549. 414. 0
#> 8 Uranus 8.68e25 -2.71e12 4.18e11 3.65e10 -1087. -7035. -11.6 0
#> 9 Neptune 1.02e26 3.15e12 3.14e12 -1.37e11 -3880. 3893. 9.45 0
#> 10 Moon 7.34e22 -3.29e10 1.44e11 -2.18e 7 -30586. -6659. 71.9 0
#> # ℹ 192,853 more rowsThe standard way to estimate an integrator’s error is to repeat the run with half the step and compare. Velocity Verlet’s global error scales as the square of the step, so the difference between the two runs is three quarters of the error of the coarser one, a fair estimate. A join on body and time pairs the runs up, and the ratio of each body’s distance from the origin to its error says how many bits of each coordinate are worth keeping:
solar_fine <- load_solar_system() |>
simulate_system(time_step = seconds_per_hour / 2, duration = 2 * seconds_per_year)
trust <- solar |>
inner_join(solar_fine, join_by(id, time), suffix = c("", "_fine")) |>
mutate(error_m = sqrt((x - x_fine)^2 + (y - y_fine)^2 + (z - z_fine)^2)) |>
group_by(id) |>
summarise(
max_error_m = max(error_m),
max_distance_m = max(sqrt(x^2 + y^2 + z^2))
) |>
mutate(bits_worth_keeping = log2(max_distance_m / max_error_m)) |>
arrange(bits_worth_keeping)
trust
#> # A tibble: 11 × 4
#> id max_error_m max_distance_m bits_worth_keeping
#> <chr> <dbl> <dbl> <dbl>
#> 1 Mercury 13921092. 6.98e10 12.3
#> 2 Moon 2022199. 1.53e11 16.2
#> 3 Venus 712305. 1.09e11 17.2
#> 4 Earth 275698. 1.52e11 19.1
#> 5 Mars 70038. 2.49e11 21.8
#> 6 Sun 4.02 4.47e 8 26.7
#> 7 Jupiter 381. 7.61e11 30.9
#> 8 Saturn 53.1 1.36e12 34.6
#> 9 Uranus 4.67 2.74e12 39.1
#> 10 Pluto 1.04 4.44e12 42.0
#> 11 Neptune 0.908 4.44e12 42.2A double offers 53 bits. Mercury’s position deserves about 12 of them: its 88-day orbit is the fastest in the system, so its error in orbital phase grows fastest, to about 14,000 km after two years. Neptune’s deserves about 42. The energy, meanwhile, hardly moves. orbitr’s conserved_quantities() reports the relative energy error (E − E0)/|E0| at every step:
conserved_quantities(solar) |>
summarise(max_energy_error = max(abs(energy_error)))
#> # A tibble: 1 × 1
#> max_energy_error
#> <dbl>
#> 1 0.00000000490Energy stays within a few parts in a billion while Mercury drifts thousands of kilometres along its orbit. That is the signature of a symplectic integrator like velocity Verlet: its energy error stays bounded, and its errors appear as phase, which a check on energy alone would never reveal.
For storage, that means most of the 53 bits are numerical noise. Round positions to the nearest kilometre and velocities to the nearest millimetre per second. For the outer planets that throws away digits the integrator does know, to within metres, but no question about where a planet is turns on metres; for Mercury, the Moon and the inner planets a kilometre is still finer than the integrator’s own error. Pluto is more than seven billion kilometres away, beyond the reach of R’s 32-bit integers, so the rounded values stay doubles. Parquet still sees the long runs of zero bits at the end of each one:
solar_rounded <- solar |>
mutate(
across(c(x, y, z), \(position_m) round(position_m / 1000)), # km
across(c(vx, vy, vz), \(velocity_ms) round(velocity_ms * 1000)) # mm/s
) |>
rename(x_km = x, y_km = y, z_km = z, vx_mm_s = vx, vy_mm_s = vy, vz_mm_s = vz)
tribble(
~version, ~megabytes,
"full doubles, zstd", parquet_mb(solar, compression = "zstd"),
"km and mm/s, zstd", parquet_mb(solar_rounded, compression = "zstd"),
"km and mm/s, zstd level 9", parquet_mb(solar_rounded, compression = "zstd", compression_level = 9)
)
#> # A tibble: 3 × 2
#> version megabytes
#> <chr> <dbl>
#> 1 full doubles, zstd 10.5
#> 2 km and mm/s, zstd 5.40
#> 3 km and mm/s, zstd level 9 4.84The file shrinks by about half, and every number in it is still finer than the physics can support. Renaming the columns to carry their new units matters as much as the rounding: x_km cannot be mistaken for metres.
The stored table answers questions as easily as the original. Here is each inner planet’s closest approach to the Sun in these two years, read back from Parquet and computed relative to the Sun’s own position at each step:
write_parquet(solar_rounded, "scratch/solar.parquet", compression = "zstd")
stored <- read_parquet("scratch/solar.parquet")
closest <- stored |>
filter(id %in% c("Sun", "Mercury", "Venus", "Earth", "Mars")) |>
group_by(time) |>
mutate(
r_km = sqrt(
(x_km - x_km[id == "Sun"])^2 + (y_km - y_km[id == "Sun"])^2 +
(z_km - z_km[id == "Sun"])^2
)
) |>
ungroup() |>
filter(id != "Sun") |>
group_by(id) |>
summarise(closest_au = min(r_km) * 1000 / distance_earth_sun) |>
arrange(closest_au)
closest
#> # A tibble: 4 × 2
#> id closest_au
#> <chr> <dbl>
#> 1 Mercury 0.308
#> 2 Venus 0.718
#> 3 Earth 0.983
#> 4 Mars 1.38Each inner planet completes at least one orbit in two years, so these are their perihelion distances: 0.308, 0.718, 0.983, 1.381 astronomical units, in order from Mercury to Mars. For a long simulation the same table would be written with write_dataset(), partitioned by body or by stretches of time, and queried with arrow or DuckDB as in the next two chapters.
13.7 Reading less
The statistics in the footer let a reader skip data it does not need. Suppose the rows are sorted by the leading muon’s transverse momentum, and written in row groups of 20,000 rows; chunk_size sets the row-group size:
dimuon |>
arrange(mu1_pt) |>
write_parquet("scratch/dimuon-sorted.parquet", chunk_size = 20000)
tbl_function(con, "parquet_metadata('scratch/dimuon-sorted.parquet')") |>
filter(path_in_schema == "mu1_pt") |>
select(row_group_id, row_group_num_rows, stats_min, stats_max) |>
collect()
#> # A tibble: 6 × 4
#> row_group_id row_group_num_rows stats_min stats_max
#> <dbl> <dbl> <chr> <chr>
#> 1 0 20000 4.019 7.18
#> 2 1 20000 7.18 9.349
#> 3 2 20000 9.349 11.785
#> 4 3 20000 11.786 15.003
#> 5 4 20000 15.003 20.779
#> 6 5 19528 20.782 84.566A query for muons above 50 GeV needs only the last row group: every other group’s maximum is below 50, so a reader that checks the statistics never decompresses them. arrow and DuckDB both do this automatically when you filter a Parquet file or dataset, a trick called predicate pushdown. It works best when the data are sorted, or at least grouped, by the columns you filter on most. For collider data that might be the run number; for a sky survey, a region of the sky; for a time series, the time.
dbDisconnect(con)13.8 Parquet’s promise
Parquet is the right default for tables you analyse and share. It records types, so nothing guesses. It is columnar, so you read only what you need. It compresses each column with the encoding and codec that suit it, so files are small. Its statistics let readers skip what they do not need. And it is an open, language-neutral standard with many independent implementations, so the files will outlast any one tool, including R.
Two cautions. Parquet has evolved, and very old readers may not understand every feature a new writer uses; if you must share files with old software, arrow’s write_parquet() has a version argument for writing older variants of the format. And Parquet is not the smallest format: for a file that is written once and only ever read whole, an xz-compressed CSV or RDS file can be smaller. Choose Parquet for files you will query.
13.9 Summary
Parquet stores a table column by column, in row groups and pages, each page encoded and then compressed, with statistics in a footer. You wrote and read Parquet with arrow, read only the columns you needed with col_select, and used DuckDB’s parquet_metadata() to look inside: dictionary encoding and run-length encoding shrank the run column to almost nothing, and bit packing stored each charge in one bit, its entropy. Storing measured values as integers and switching from Snappy to zstd or Brotli made the file about a third smaller, and sorting before writing let statistics skip whole row groups. For simulation output, a convergence test told you how many bits each body’s position deserves, from about 12 for Mercury to about 42 for Neptune, and storing the solar system at that precision halved the file without losing anything the physics supports.
13.10 Exercises
- Write the star catalog to Parquet with the default settings and look at its metadata with
parquet_metadata(). Which columns compress best, and why? - The
eventcolumn restarts at 1 in each run and counts upward. How many bits per value would a delta encoding need? Compare that with the compressed size of theeventcolumn chunk ininside. - Write the magnetometer data to Parquet twice: with the field components as doubles, and as integer counts of 0.01 nT. Use zstd for both. How do the sizes compare with the gzipped CSV?
- Sort the dimuon table by
runand thenmu1_pt, write it with row groups of 5,000 rows, and count how many row groups a filter forrun == 2305 & mu1_pt > 30could skip, using the statistics. - Time
read_parquet()for the whole dimuon file and forcol_select = mu1_ptalone, usingsystem.time(). Repeat each a few times. How much faster is reading one column? - Repeat the solar-system convergence test with a two-hour step against a one-hour step. Velocity Verlet’s error should grow by a factor of four when the step doubles. Does it, for every body? How many bits worth keeping does each body lose?