≈ The Lake

Part 3 · Parquet and columnar files · Chapter 8

Statistics, page indexes and bloom filters

The metadata that lets readers skip data: column chunk statistics and their sort-order rules, the column and offset index (page index), dictionary filtering, split block Bloom filters, and the order in which parquet-java and Spark apply them.

complete ~40 min

After this chapter you should be able to:
  • Explain min/max statistics semantics, including sort order, NaN, signed zero and truncation.
  • Use the page index to turn a predicate into row ranges and pages to fetch, across columns whose pages do not line up.
  • Know when a Bloom filter or a dictionary can drop a row group that statistics cannot.
  • Describe the order in which parquet-java and Spark apply each structure, and what each one costs in reads.

Chapter 5 ended with a reader that fetches the footer, compares a predicate with each row group’s min and max, and skips the row groups that cannot match. That is the first of four structures a Parquet file can carry for skipping data. This chapter covers all four: chunk statistics, the page index (a ColumnIndex and an OffsetIndex per column chunk), the dictionary, and split block Bloom filters. For each, it gives what the spec requires, what writers actually produce, and how a reader uses it.

The code is in src/sim/parquet/pushdown.ts (XXH64, the Bloom filter, the page index structures) and src/sim/parquet/scan.ts (the scan planner). The tests rebuild a Bloom filter that pyarrow 26 wrote, byte for byte, and check that our writer produces the same ColumnIndex bytes as Arrow for the same data. The scan planner decodes its answer from a buffer that holds only the bytes it fetched, and the tests compare that answer with a full scan for every combination of predicate, sort order and reader setting.

Where the metadata lives

Each structure sits in a different place, and that placement decides what it costs to use:

StructureWhereRead cost
Statistics per chunkColumnMetaData.statistics, in the footerfree once the footer is read
Statistics per pageDataPageHeader.statisticsmust read every page header
ColumnIndex, OffsetIndexafter the row groups; offsets in ColumnChunk fields 4–7one small read each
Dictionarythe chunk’s dictionary pageone read: the dictionary page
Bloom filterafter the row groups (or between them); ColumnMetaData fields 14–15one read per chunk

Arrow C++ 26 writes data, then all Bloom filters, then all column indexes, then all offset indexes, then the footer. The fixture arrow-index.parquet has exactly this layout, and so does our writer.[BloomFilter.md: file format] parquet-java writes the column and offset indexes and then the Bloom filters, both in end().[parquet-java ParquetFileWriter.end]

Statistics

Statistics has two pairs of bounds. Fields 1 and 2, max and min, are deprecated: they were “determined by signed comparison only”, which orders UTF8 strings wrongly for bytes above 0x7F. New writers fill fields 5 and 6, max_value and min_value, ordered by the column’s ColumnOrder. Both pairs are PLAIN encoded, “except that variable-length byte arrays do not include a length prefix”.[parquet.thrift: Statistics]

null_count matters for IS NULL and IS NOT NULL, and for proving that a chunk is all nulls. Its absence is not a zero: “If null_count is not present, readers MUST NOT assume null_count == 0.” The planner here drops a row group for a comparison predicate when null_count == num_values, because no null satisfies x op v.

Bounds need not be actual values. The spec allows “more compact values that do not exist on a page or column chunk”, with the example of writing "B" and "C" for "Blart Versenwald III". Fields 7 and 8, is_max_value_exact and is_min_value_exact, say whether they were shortened.

The check itself is the same for chunks and pages. Given bounds [min, max] and x op v:

// src/sim/parquet/scan.ts: rangeMayMatch, compared by the column's sort order
if (op === '=')  return min <= v && v <= max;
if (op === '<')  return min < v;
if (op === '<=') return min <= v;
if (op === '>')  return max > v;
return max >= v; // '>='

false means “cannot match” and the reader skips. true means only “may match”. Statistics never say which rows match, so the reader still evaluates the predicate on every row it decodes.

Quiz Check: statisticsAnswers are scheduled for spaced review on the Review page.

Q1. A new writer fills Statistics for a UTF8 column. Which fields should carry the bounds?

How sure are you?

Q2. A column chunk's Statistics has no null_count field. What may a reader assume?

How sure are you?

Sort orders, NaN and signed zero

FileMetaData.column_orders holds one ColumnOrder per leaf. The usual value is TYPE_ORDER, which defines the order by logical type, or by physical type when there is none: UTF8, JSON, BSON and ENUM by “unsigned byte-wise comparison”, the signed integer types by signed comparison, the unsigned ones by unsigned comparison, DECIMAL by “signed comparison of the represented value”. LIST, MAP, VARIANT and INTERVAL are “undefined”: no bounds can be trusted for them.[parquet.thrift: ColumnOrder]

Floating point is where TYPE_ORDER is ambiguous, “due to underspecified handling of NaN and -0/+0”. The spec now gives rules for each side.

When writing TYPE_ORDER float statistics:

  • “The nan_count field must be set for floating point types, even if it is zero.”
  • Min and max are computed from non-NaN values only. If every non-null value is NaN, no min or max is written.
  • “If the computed max value is zero (whether negative or positive), +0.0 should be written”. A zero min is written as -0.0.

When reading:

  • A NaN min or max “should be ignored”, because legacy files wrote them.
  • “When looking for NaN values, min and max should be ignored”, so a NaN lookup needs nan_count.
  • Without nan_count, readers “MUST assume NaNs may be present” (Statistics field 9).

The signed-zero rule makes the bounds safe for every reader. A reader that treats -0.0 < +0.0, as IEEE_754_TOTAL_ORDER does, still finds both zeros inside [-0.0, max]. The page index test checks that pyarrow writes -0.0 as a page minimum.

Two things in current writers do not match the spec. Neither Arrow C++ 26.0.0 nor parquet-java 1.17.1 writes nan_count, although the rule says it must be set. The fixture’s footer also shows that Arrow declares TYPE_ORDER for every column, not IEEE_754_TOTAL_ORDER. Without nan_count, a reader cannot skip on x = NaN, though range predicates still work, because the bounds come from non-NaN values.

Quiz Check: sort ordersAnswers are scheduled for spaced review on the Review page.

Q1. Under TYPE_ORDER, a DOUBLE page holds 0.0, 3.5 and 7.0. What does the writer put in min_value?

How sure are you?

Q2. A reader evaluates x = NaN on a TYPE_ORDER DOUBLE column. Which statements are true? (Select all.) (select all that apply)

How sure are you?

Truncated bounds

Long strings make large bounds, and the page index repeats them for every page. Writers therefore truncate. A truncated minimum is just a prefix: "Seattle-Tacoma" becomes "Sea", which is still at most every value. A maximum cannot be cut the same way, because "Sea" sorts below "Seattle-Tacoma". The writer cuts, then increments the last byte to get "Seb". parquet-java’s BinaryTruncator.truncateMax does this. For UTF8 it keeps incrementing until the bytes form valid UTF-8, and if every byte is already 0xFF it keeps the full value.[parquet-java BinaryTruncator]

parquet-java’s defaults: column index bounds are truncated to 64 bytes (DEFAULT_COLUMN_INDEX_TRUNCATE_LENGTH), and chunk statistics are not truncated (DEFAULT_STATISTICS_TRUNCATE_LENGTH = Integer.MAX_VALUE).[parquet-java ParquetProperties] A truncated bound still answers range predicates correctly. It only makes them less selective near the cut.

Quiz Check: truncationAnswers are scheduled for spaced review on the Review page.

Q1. A writer truncates the string max "Seattle-Tacoma" to 3 bytes for a column index. What can it store?

How sure are you?

The page index

Page header statistics were the first attempt at page skipping. PageIndex.md names their problem: “a reader had to process the page header to determine whether the page could be skipped”, so it “had to access all pages in a column”. The page index moves the per-page facts out of the pages, “near the footer”, so that “a reader does not have to pay the I/O and deserialization cost for reading them if it is not doing selective scans”.[PageIndex.md]

Each column chunk gets two structures:

  • OffsetIndex: one PageLocation { offset, compressed_page_size, first_row_index } per data page. The size includes the page header. “When an OffsetIndex is present, pages must begin on row boundaries (repetition_level = 0)”. That is the chapter 7 rule that lets a reader start a nested column at any indexed page.[parquet.thrift: PageLocation]
  • ColumnIndex: per page null_pages[i], min_values[i], max_values[i] and null_counts[i], plus one boundary_order of UNORDERED, ASCENDING or DESCENDING. Null pages get empty bounds “so that all lists have the same length”.[parquet.thrift: ColumnIndex]

boundary_order “allows readers to perform binary searches in both lists”. The same comment warns that readers “cannot assume that max_values[i] <= min_values[i+1], even if the lists are ordered”. Neighbouring pages of a sorted column can share a value, so a binary search must find the first and last pages that may match, not one page. parquet-java’s BoundaryOrder.ASCENDING.findBounds runs two binary searches, one for the lower edge and one for the upper.[parquet-java BoundaryOrder]

PageIndex.md also says “Readers that support ColumnIndex should not also use page statistics”. Arrow drops page header statistics when it writes a page index, and so does our writer.

From pages to row ranges

Using the page index takes two steps, and the order matters because different columns cut their pages at different rows. Writers end a page by size: Arrow C++ and parquet-java both close a page at about 1 MiB or 20,000 rows by default.[Arrow properties.h][parquet-java ParquetProperties] A wide string column therefore has more, shorter pages than an INT64 column in the same row group.

  1. Filter column to row ranges. ColumnIndexFilter.applyPredicate asks the filter column’s ColumnIndex which pages may match, then RowRanges.create turns each page into [first_row_index, next page's first_row_index - 1] and unions them.[parquet-java ColumnIndexFilter][parquet-java RowRanges.create] With several predicates, And intersects the ranges and Or unions them.
  2. Row ranges to pages of every column. filterOffsetIndex keeps each page of each projected column whose rows overlap the ranges, using that column’s own OffsetIndex. calculateOffsetRanges then adds the dictionary page, if the chunk has one, and joins pages that are adjacent in the file.[parquet-java filterOffsetIndex][parquet-java calculateOffsetRanges]
// src/sim/parquet/scan.ts (trimmed)
const pages = ci.nullPages.map((np, i) => (!np && rangeMayMatch(type, ci.mins[i], ci.maxs[i], op, v) ? i : -1)).filter((i) => i >= 0);
ranges = union(pages.map((i) => [oi[i].firstRow, lastRow(oi, i, rg.numRows)]));
for (const c of neededColumns) {
  const keep = pagesOf(c).filter((p) => overlaps(ranges, p.firstRow, p.lastRow));
  if (chunk.start < pagesOf(c)[0].offset) fetch(chunk.start, pagesOf(c)[0].offset); // dictionary page
  for (const p of keep) fetch(p.offset, p.offset + p.size);
}

In the lab file, trip_id pages hold 100 rows and user_id pages hold 50. For trip_id >= 101160, row group 2’s matching trip_id pages cover rows 100–499. The reader then fetches user_id pages 2 to 9, which cover the same rows. Inside a fetched page, the rows before the range still have to be decoded and thrown away. Spark’s vectorized reader does this in ParquetReadState, which walks the row ranges and skips the rows outside them.[Spark ParquetReadState]

The page index joins columns by row position
In row group 2 of the lab file, the trip_id predicate rules out page 0. The remaining trip_id pages cover row positions 100 through 499, so the reader fetches user_id pages 2–9. Each trip_id page covers 100 rows, while each user_id page covers 50 rows. 1. Filter trip_id >= 101160 Trip ID pages · 100 rows each 0 1 2 3 4 Skip Candidate rows 100–499 2. Find overlapping user_id pages 0 1 2 3 4 5 6 7 8 9 Skip Fetch pages 2–9 · 50 rows each
trip_id page 1 overlaps user_id pages 2 and 3. The reader checks the filter on individual rows after fetching the candidate pages.[Parquet page index]
Quiz Check: page indexAnswers are scheduled for spaced review on the Review page.

Q1. Why are ColumnIndex and OffsetIndex stored near the footer and not in the page headers?

How sure are you?

Q2. A ColumnIndex has boundary_order ASCENDING. What can the reader do with that?

How sure are you?

Q3. The filter column's pages hold 100 rows each; the projected column's pages hold 50. Page 2 of the filter column (rows 200–299) is the only match. Which pages of the projected column are read?

How sure are you?

Dictionary filtering

A dictionary-encoded chunk carries the set of its distinct values in one page. A reader can fetch that page and drop the row group if no entry satisfies the predicate. This catches values between min and max that are not in the data. In the lab, city = 'Dallas' falls between Chicago and Denver, so statistics admit it, and only the dictionary proves it absent.

The catch is fallback. Writers abandon the dictionary when it grows too large and write the rest of the chunk’s pages PLAIN, and those pages can hold values the dictionary never saw. So parquet-java’s DictionaryFilter first asks hasNonDictionaryPages. With encoding_stats (ColumnMetaData field 13, a count of pages per page type and encoding) the answer is exact. Without it, the code can only reason about the v1 PLAIN_DICTIONARY encoding. For RLE_DICTIONARY it gives up, because “for 2.0, this cannot determine whether a page fell back without page encoding stats”.[parquet-java hasNonDictionaryPages] Our writer writes encoding_stats for this reason, and the planner applies the same test.

For equality the check is !dictSet.contains(value). For <, > and the other range predicates, parquet-java scans the dictionary for any entry that satisfies them.[parquet-java DictionaryFilter.visit(Eq)]

Quiz Check: dictionary filteringAnswers are scheduled for spaced review on the Review page.

Q1. parquet-java wants to drop a row group with the dictionary of a v2-encoded column (RLE_DICTIONARY). What must the footer have for it to try?

How sure are you?

Bloom filters

Statistics fail on high-cardinality columns in random order: every row group spans nearly the whole domain. Dictionaries would help, but such columns are exactly the ones whose dictionaries get too large. BloomFilter.md is written for this case: “columns with large cardinalities and widely separated min and max”. A Bloom filter answers “definitely no” or “probably yes” and has no false negatives.[BloomFilter.md: problem statement]

Parquet defines one kind, the split block Bloom filter (SBBF). It is an array of z blocks of 256 bits, each block eight 32-bit words. A value is hashed with XXH64 (seed 0) over its PLAIN encoding, which for strings means the bytes without the length prefix. The 64-bit hash then does two jobs:

// src/sim/parquet/pushdown.ts, following BloomFilter.md's pseudocode
const SALT = [0x47b6137b, 0x44974d91, 0x8824ad5b, 0xa2b7289d, 0x705495c7, 0x2df1424b, 0x9efc4947, 0x5c6bfb31];
insert(h: bigint) {
  const i = Number(((h >> 32n) * BigInt(this.numBlocks)) >> 32n); // top 32 bits choose a block
  const x = Number(h & 0xffffffffn);                               // low 32 bits choose the bits
  for (let w = 0; w < 8; w++) {
    const y = Math.imul(x, SALT[w]) >>> 0;                         // keep the low 32 bits of the product
    this.words[i * 8 + w] |= 1 << (y >>> 27);                      // one bit in each word
  }
}
// check() computes the same 8 bits and returns true only if all are set

The top 32 bits pick a block with a multiply and shift instead of a modulo. BloomFilter.md credits the trick to Kenneth A. Ross’s 2006 IBM research report.[BloomFilter.md: technical approach] The low 32 bits, multiplied by eight odd salts, set one bit in each of the block’s eight words. Every insert or check touches one 32-byte block, so it costs one cache line. That is the point of the “split block” design, which the spec attributes to Putze et al.

A filter is stored as a Thrift BloomFilterHeader { numBytes, algorithm: BLOCK, hash: XXHASH, compression: UNCOMPRESSED } followed by the bitset. bloom_filter_length (field 15) includes the header, and writers “should write this field so readers can read the bloom filter in a single I/O”.

Sizing and folding

BloomFilter.md gives no closed form for the false-positive rate, only measured points. 1,024 blocks holding 26,214 values is 10 bits per value and about 1.26%. The table’s other points:[BloomFilter.md: sizing]

Bits per valueFalse positive rate
6.010%
10.51%
16.90.1%
26.40.01%

The Sbbf test inserts 26,214 values into 1,024 blocks and measures close to 1.26%.

Writers have to choose a size before they know how many distinct values a chunk will have. Arrow C++ asks for an ndv and an fpp, sizes the bitset with OptimalNumOfBits (m = -8·ndv / ln(1 - fpp^(1/8)), clamped and rounded up to a power of two), and defaults to fpp 0.05.[Arrow bloom_filter.h][Arrow BloomFilterOptions] If ndv is not set, it uses the row group’s maximum row count, which oversizes the filter for a column with repeats. Arrow 26 then folds the filter when it is written. It ORs adjacent blocks together, halving the number of blocks each time, as long as the estimated false-positive rate stays under the target.[Arrow FoldToTargetFpp] The fixture’s user filter was sized for ndv 100 at 5% and written at 128 bytes. The test rebuilds those exact bytes with our port.

parquet-java turns Bloom filters off by default, with fpp 0.01 and a 1 MiB cap when enabled.[parquet-java ParquetProperties] pyarrow writes none unless bloom_filter_options names columns, and its write_page_index defaults to False, although Arrow C++‘s own default is true.[Arrow DEFAULT_IS_PAGE_INDEX_ENABLED]

Quiz Check: Bloom filtersAnswers are scheduled for spaced review on the Review page.

Q1. For which predicates on a high-cardinality user_id column can a Bloom filter drop a row group? (Select all.) (select all that apply)

How sure are you?

Q2. How does a split block Bloom filter use the 64-bit XXH64 hash of a value?

How sure are you?

Q3. BloomFilter.md's table says 10.5 bits of space per inserted value give about 1% false positives. Roughly how big is a 1% filter for 1,000,000 distinct values?

How sure are you?

The reader’s order of operations

parquet-java applies the structures cheapest first. When the file is opened, RowGroupFilter.filterRowGroups runs on every row group. It tries StatisticsFilter, then DictionaryFilter, then BloomFilterImpl, and the first that proves “cannot match” drops the row group.[parquet-java RowGroupFilter] All of these are on by default in ParquetReadOptions: statistics, dictionary, column index and Bloom filters.[parquet-java ParquetReadOptions] Then, per surviving row group, readFilteredRowGroup computes row ranges from the column index and reads only the overlapping pages. It joins ranges that are adjacent in the file, across columns, into one read.[parquet-java ParquetFileReader]

The planner follows the same order. For SELECT trip_id, fare WHERE trip_id = 101234 on the lab file (78,155 bytes, four row groups of 500 rows), its reads are:

#ReadBytesWhy
1tail8footer length
2footer1,509statistics drop row groups 0, 1 and 3
3ColumnIndex, trip_id, row group 2111page 2 of 5 may match
4OffsetIndex, trip_id57rows 200–299
5OffsetIndex, fare57which fare page holds rows 200–299
6trip_id page 2820
7fare page 2788

That is 3,350 bytes in 7 requests, against 33,569 bytes for reading both columns in full. The same query with statistics alone reads 9,525 bytes. Sorting decides how much any of this helps. In trip order, user_id = 'u0042' cannot use statistics at all, and only the Bloom filter drops row groups: about 28 KiB read. After sorting the rows by user_id, statistics drop three row groups and the column index narrows the fourth to one page: about 4 KiB read. Chapters 26 and 27 build on this, with Z-order and liquid clustering.

Iceberg and Delta keep min/max per file in their own metadata, so a planner can skip whole files before opening any footer. The Parquet structures in this chapter apply one level down, inside the files that survive.

Quiz Check: the readerAnswers are scheduled for spaced review on the Review page.

Q1. In what order does parquet-java's RowGroupFilter try to drop a row group?

How sure are you?

Q2. In the lab, user_id = 'u0042' reads about 28 KiB on a file in trip order and about 4 KiB on the same rows sorted by user_id. Why?

How sure are you?

Pushdown in Spark

spark.sql.parquet.filterPushdown defaults to true.[Spark SQLConf] In ParquetFileFormat, Spark converts the data filters it can express with ParquetFilters.createFilter. Those that convert are ANDed into a parquet-java FilterPredicate and set with ParquetInputFormat.setFilterPredicate. The code’s own comment says “This push-down is RowGroups level, not individual records”.[Spark ParquetFileFormat] The vectorized reader gets its row groups through readNextFilteredRowGroup, so it also uses the column index.[Spark SpecificParquetRecordReaderBase]

The rows that come back can still fail the predicate. parquet-java can filter records itself, but spark.sql.parquet.recordLevelFilter.enabled is false by default, so Spark keeps its own Filter operator above the scan. In EXPLAIN, PushedFilters: [IsNotNull(fare), GreaterThan(fare,64.5)] on the scan means those filters were handed to the reader. It does not mean the Filter above the scan was removed.

Quiz Check: SparkAnswers are scheduled for spaced review on the Review page.

Q1. Spark pushes fare > 64.5 into the Parquet reader. Why does the plan still have a Filter above the scan?

How sure are you?

Try it

The lab writes 2,000 trips with the book’s writer: trip_id rising, user_id random with about 1,000 values, city in blocks, and fare with some nulls. The file has four row groups of 500 rows, 100-row pages, and 50-row pages for user_id. The lab then runs the planner on it. Every box is a real page; green ones were fetched. Things to try:

  • one trip by id with only statistics on, then with the column index too.
  • a user who does not exist with Bloom filters on and off. Statistics cannot help: 'u0500x' sorts inside every row group’s range.
  • a city that is not there with dictionary encoding on in the writer.
  • one user, then sort the file by user_id.
  • expensive trips in trip order, then sorted by fare.
Query

SELECT trip_id, fare WHERE

Writer
Reader
3.3 KiBread of 76.3 KiB (4.3%)
7GET requests
100rows decoded
1rows match
Row group 0 rows 0–499skipped by statistics
  1. Statistics: cannot match. Trip_id is in [100000, 100499], so no value is = 101234.
trip_id
user_id
city
fare
Row group 1 rows 500–999skipped by statistics
  1. Statistics: cannot match. Trip_id is in [100500, 100999], so no value is = 101234.
trip_id
user_id
city
fare
Row group 2 rows 1000–1499read
  1. Statistics: may match. Trip_id is in [101000, 101499].
  2. Dictionary: not usable. The chunk has no dictionary.
  3. Bloom filter: not usable. The chunk has no Bloom filter.
  4. Page index: may match. 1 of 5 pages may match (index is ASCENDING): 100 of 500 rows.
trip_id
user_id
city
fare
Row group 3 rows 1500–1999skipped by statistics
  1. Statistics: cannot match. Trip_id is in [101500, 101999], so no value is = 101234.
trip_id
user_id
city
fare

page fetched page not fetched Grey column names are not needed by the query.

Result: (101234, 62.34)

Summary

  • Chunk statistics in the footer are free once the footer is read. Use min_value/max_value, ordered by the column’s ColumnOrder. A missing null_count is not zero.
  • For floats under TYPE_ORDER, bounds come from non-NaN values, a zero min is written as -0.0 and a zero max as +0.0, and NaN lookups need nan_count, which current Arrow and parquet-java do not write.
  • Truncated bounds stay correct: a min is cut, a max is cut and then incremented.
  • The page index puts per-page bounds and page locations near the footer. The filter column’s ColumnIndex gives row ranges, and each projected column’s OffsetIndex turns those ranges into pages, because pages do not line up across columns.
  • Dictionary filtering drops values inside [min, max] that are absent, but only when encoding_stats prove no page fell back to PLAIN.
  • An SBBF picks a 256-bit block with the top 32 bits of XXH64 and sets one bit per word with the low 32. About 10 bits per value gives about 1% false positives. It helps only equality and IN.
  • parquet-java applies statistics, then the dictionary, then the Bloom filter per row group, then the column index per page. Spark pushes filters into it but keeps its own Filter.

Concepts in this chapter

Explained here

See how the book's concepts connect →

Primary sources

Review this chapter

This chapter has 15 quiz questions.

Review this chapter's cards → Review all due cards