Repository navigation
Add PageIndexBuilder and PageIndexProvider for Parquet page indexes
#10842
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
86 commits
Select commit
Hold shift + click to select a range
1f5d629
convert page indexes to Vec<Vec<Option<T>>>
etseidl 250644d
remove the NONE variant from ColumnIndexMetaData
etseidl 511ffba
doc fix
etseidl 03cbefc
Merge branch 'main' into opt_page_index
etseidl 2a93a11
Merge remote-tracking branch 'origin/main' into opt_page_index
etseidl 6a45480
Merge remote-tracking branch 'origin/main' into opt_page_index
etseidl 158ab8f
clippy
etseidl 965c6a0
checkpoint
etseidl 80a16ad
checkpoint
etseidl b410401
basic tests pass
etseidl 1794e41
fix test
etseidl b971e38
fix benches and bin
etseidl 78d869a
fix more tests
etseidl a7e424a
fix doc test
etseidl b9bf6e2
fix test for missing col idx
etseidl 39469db
clippy
etseidl c76b016
doc fixes
etseidl c47386d
remove fixmes
etseidl 7f47fac
clippy
etseidl c6edf24
claude some documentation
etseidl 4315c9f
fix test todo
etseidl ae3d0d2
add PageIndex::is_complete per review suggestion
etseidl 50041c8
Merge branch 'main' into new_page_index
etseidl 04b8f67
fix merge
etseidl a4b7303
reword docs to be less implementation specific
etseidl beda053
Merge branch 'main' into new_page_index
etseidl f236ad9
Merge remote-tracking branch 'origin/main' into new_page_index
etseidl 5f1b746
add page index builder
etseidl fc465f6
experiment with selective index population
etseidl 10a5eb2
fix docs
etseidl c28875c
enforce required for offset index only
etseidl 0d62cce
make builder public
etseidl 2cd8a9d
PageIndexBuilder::new_with_policy only needs references to the index …
etseidl d0525fd
hide some clones
etseidl 2d9d0d6
Merge branch 'main' into page_index_builder
alamb 3111119
add example written by @alamb to PageIndex docs
etseidl 56f8e36
claude generated provider interface
etseidl 65416bb
add default impls for some functions
etseidl 5822fe5
rearrange docs
etseidl 20114ff
per-rowgroup access through provider
etseidl 6e1c841
remove changes to PageIndexPolicy for now
etseidl 99fec37
fix test comment
etseidl f6bec25
clippy
etseidl d64a2ee
fix doc errors
etseidl 8e15a5c
Merge remote-tracking branch 'origin/main' into page_index_provider
etseidl d556e2c
a few cleanups
etseidl 25349e8
remove HeapSize from PageIndexProvider
etseidl b9e01dc
add example of custom provider
etseidl 721c9c0
fix comments
etseidl 703f5ec
fix index population
etseidl b894ca2
clippy
etseidl fa56a3d
typo
etseidl a8c0541
add example to Cargo.toml and gate on arrow
etseidl 149c802
Merge remote-tracking branch 'origin/main' into page_index_provider
etseidl 6630f3f
gate InMemoryPageIterator on arrow
etseidl f0ccd3c
Merge branch 'page_index_provider' of github.com:etseidl/arrow-rs int…
etseidl 3169f7d
a few example fixes
etseidl 79110a1
clean up the example some
etseidl 9dff481
hide some of the boilerplate code in an example
etseidl 1f7caec
link to page index docs on parquet.apache.org
etseidl 4daed3d
clippy
etseidl 26706bd
add docs
etseidl 75fa6ff
move page indexes to their own module
etseidl 80be34d
replace new_with_policy with new_from_parts and make it pub(crate)
etseidl b6a4463
rework creating a partially populated PageIndexBuilder
etseidl 73a362d
change function names and claude some better documentation
etseidl da2981e
Merge branch 'main' into page_index_provider
etseidl 950d53d
tiny refactor
etseidl 6954edf
fix broken doc refs
etseidl d1bcc41
Merge remote-tracking branch 'origin/main' into page_index_provider
etseidl 5640705
rework example to be more realistic
etseidl 6806d69
Merge remote-tracking branch 'origin/main' into page_index_provider
etseidl 0caa8b4
refactor and add comments per review suggestion
etseidl 3e382e5
fix memory_size calculation
etseidl d562697
add TODO
etseidl 690907c
add warning and todo re serialization limited to PageIndex
etseidl 39c5828
add some clarification to docs for PageIndexProvider::has_XXX_indexes
etseidl 36ec3a1
add some sugar to obtain RowGroupPageIndexes
etseidl 410975a
Merge branch 'page_index_provider' of github.com:etseidl/arrow-rs int…
etseidl 28009fa
clippy
etseidl ea6eb07
Merge remote-tracking branch 'origin/main' into page_index_provider
etseidl 79dbf5a
spelling
etseidl 06a8bdd
Update link to filed issue
alamb 3a906c4
add comments / update todo
alamb 4c7adb6
Merge remote-tracking branch 'apache/main' into page_index_provider
alamb bc8fa39
Clean up docs example, test names, urls
alamb File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,316 @@ | ||
| // Licensed to the Apache Software Foundation (ASF) under one | ||
| // or more contributor license agreements. See the NOTICE file | ||
| // distributed with this work for additional information | ||
| // regarding copyright ownership. The ASF licenses this file | ||
| // to you under the Apache License, Version 2.0 (the | ||
| // "License"); you may not use this file except in compliance | ||
| // with the License. You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, | ||
| // software distributed under the License is distributed on an | ||
| // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| // KIND, either express or implied. See the License for the | ||
| // specific language governing permissions and limitations | ||
| // under the License. | ||
|
|
||
| //! Example of implementing a custom PageIndexProvider | ||
| //! | ||
| //! This example demonstrates how to create a custom page index provider that: | ||
| //! - Only stores page indexes for specified columns (selective storage) | ||
| //! - Uses nested HashMaps for efficient storage and lookup | ||
| //! - Implements all required PageIndexProvider trait methods | ||
| //! | ||
| //! This approach can significantly reduce memory usage and reduce load time | ||
| //! when working with wide tables where only a few columns need page-level statistics. | ||
| //! This is particularly important for queries that filter on a predicate column | ||
| //! and project a small subset of columns. | ||
|
|
||
| use bytes::Bytes; | ||
| use parquet::DecodeResult; | ||
| use parquet::errors::{ParquetError, Result}; | ||
| use parquet::file::metadata::page_index::PageIndexProvider; | ||
| use parquet::file::metadata::{PageIndexPolicy, ParquetMetaData, ParquetMetaDataPushDecoder}; | ||
| use parquet::file::page_index::column_index::ColumnIndexMetaData; | ||
| use parquet::file::page_index::index_reader::{decode_column_index, decode_offset_index}; | ||
| use parquet::file::page_index::offset_index::OffsetIndexMetaData; | ||
| use std::collections::HashMap; | ||
| use std::collections::hash_map::Entry; | ||
| use std::fs::File; | ||
| use std::path::PathBuf; | ||
| use std::sync::Arc; | ||
| use tempfile::TempDir; | ||
|
|
||
| // A custom PageIndexProvider that only stores indexes for a subset of columns | ||
| // | ||
| // This provider contains the parsed footer metadata and the entire contents of a | ||
| // Parquet file. Indexes are lazily populated as they are requested. | ||
| #[derive(Debug, Clone)] | ||
| pub struct OnDemandPageIndexProvider { | ||
| metadata: ParquetMetaData, | ||
| file_bytes: Bytes, | ||
| // indexes are accessed first by row_group index and then by column index | ||
| column_indexes: Option<HashMap<usize, HashMap<usize, ColumnIndexMetaData>>>, | ||
|
alamb marked this conversation as resolved.
Resolved
|
||
| offset_indexes: Option<HashMap<usize, HashMap<usize, OffsetIndexMetaData>>>, | ||
| } | ||
|
|
||
| impl OnDemandPageIndexProvider { | ||
| fn new(metadata: ParquetMetaData, file_bytes: Bytes) -> Self { | ||
| Self { | ||
| metadata, | ||
| file_bytes, | ||
| column_indexes: None, | ||
| offset_indexes: None, | ||
| } | ||
| } | ||
|
|
||
| // fetches the bytes for and parses the column index for the given row group and | ||
| // column. If already fetched, this does nothing. | ||
| fn fetch_column_index(&mut self, row_group_idx: usize, column_idx: usize) -> Result<()> { | ||
| let map = self.column_indexes.get_or_insert_with(HashMap::new); | ||
| let rg = map.entry(row_group_idx).or_default(); | ||
| if let Entry::Vacant(e) = rg.entry(column_idx) { | ||
| // get the `ColumnIndexMetaData` for the requested row group and column... | ||
| let column = self.metadata.row_group(row_group_idx).column(column_idx); | ||
| // and get the location of the column index for this chunk | ||
| let range = column.column_index_range(); | ||
|
alamb marked this conversation as resolved.
Resolved
|
||
| if let Some(range) = range { | ||
| let idx_bytes = self | ||
| .file_bytes | ||
| .slice(range.start as usize..range.end as usize); | ||
| let idx = decode_column_index(&idx_bytes, column.column_type())?; | ||
| e.insert(idx); | ||
| } | ||
| } | ||
| Ok(()) | ||
| } | ||
|
|
||
| // fetches the bytes for and parses the offset index for the given row group and | ||
| // column. If already fetched, this does nothing. | ||
| fn fetch_offset_index(&mut self, row_group_idx: usize, column_idx: usize) -> Result<()> { | ||
| let map = self.offset_indexes.get_or_insert_with(HashMap::new); | ||
| let rg = map.entry(row_group_idx).or_default(); | ||
| if let Entry::Vacant(e) = rg.entry(column_idx) { | ||
| // get the `ColumnIndexMetaData` for the requested row group and column... | ||
| let column = self.metadata.row_group(row_group_idx).column(column_idx); | ||
| // and get the location of the offset index for this chunk | ||
| let range = column.offset_index_range(); | ||
|
alamb marked this conversation as resolved.
Resolved
|
||
| if let Some(range) = range { | ||
| let idx_bytes = self | ||
| .file_bytes | ||
| .slice(range.start as usize..range.end as usize); | ||
| let idx = decode_offset_index(&idx_bytes)?; | ||
| e.insert(idx); | ||
| } | ||
| } | ||
| Ok(()) | ||
| } | ||
| } | ||
|
|
||
| // Custom providers must implement the `PageIndexProvider` trait. | ||
| impl PageIndexProvider for OnDemandPageIndexProvider { | ||
| fn has_offset_indexes(&self) -> bool { | ||
| self.offset_indexes.is_some() | ||
| } | ||
|
|
||
| fn has_column_indexes(&self) -> bool { | ||
| self.column_indexes.is_some() | ||
| } | ||
|
|
||
| fn column_index( | ||
| &self, | ||
| row_group_idx: usize, | ||
| column_idx: usize, | ||
| ) -> Option<&ColumnIndexMetaData> { | ||
| self.column_indexes | ||
| .as_ref()? | ||
| .get(&row_group_idx)? | ||
| .get(&column_idx) | ||
| } | ||
|
|
||
| fn offset_index( | ||
| &self, | ||
| row_group_idx: usize, | ||
| column_idx: usize, | ||
| ) -> Option<&OffsetIndexMetaData> { | ||
| self.offset_indexes | ||
| .as_ref()? | ||
| .get(&row_group_idx)? | ||
| .get(&column_idx) | ||
| } | ||
|
|
||
| fn as_any(&self) -> &dyn std::any::Any { | ||
| self | ||
| } | ||
| } | ||
|
|
||
| fn main() -> Result<()> { | ||
| // Create a sample parquet file with page indexes for this example | ||
| let tempdir = TempDir::new().unwrap(); | ||
| let temp_path = tempdir.path().join("custom_page_index_example.parquet"); | ||
| create_sample_file(&temp_path)?; | ||
| println!("Sample file created with page indexes\n"); | ||
|
|
||
| // Example 1: Use the standard PageIndex provider (all columns accessible) | ||
| println!("=== Example 1: Standard PageIndex (all columns) ==="); | ||
|
|
||
| let file_bytes = Bytes::from(std::fs::read(temp_path)?); | ||
| let file_len = file_bytes.len() as u64; | ||
| let mut decoder = ParquetMetaDataPushDecoder::try_new(file_len)? | ||
| .with_page_index_policy(PageIndexPolicy::Required); | ||
| #[expect(clippy::single_range_in_vec_init)] | ||
| decoder.push_ranges(vec![0..file_len], vec![file_bytes.clone()])?; | ||
| let metadata = match decoder.try_decode() { | ||
| Ok(DecodeResult::Data(metadata)) => metadata, // decode successful | ||
| other => { | ||
| panic!("expected DecodeResult::Data, got: {other:?}") | ||
| } | ||
| }; | ||
|
|
||
| let num_columns = metadata.file_metadata().schema_descr().num_columns(); | ||
| println!("Number of row groups: {}", metadata.num_row_groups()); | ||
| println!("Number of columns: {num_columns}"); | ||
| println!(); | ||
|
|
||
| println!("== All indexes should be populated"); | ||
| print_page_index(&metadata, 0)?; | ||
| print_page_index(&metadata, 1)?; | ||
|
|
||
| // Example 2: Read metadata and then add custom PageIndexProvider | ||
| println!("=== Example 2: Selective PageIndex (columns 0, 1, 4 only) ==="); | ||
|
|
||
| // first read the metadata without page indexes | ||
| decoder = ParquetMetaDataPushDecoder::try_new(file_len)? | ||
| .with_page_index_policy(PageIndexPolicy::Skip); | ||
| #[expect(clippy::single_range_in_vec_init)] | ||
| decoder.push_ranges(vec![0..file_len], vec![file_bytes.clone()])?; | ||
| let metadata = match decoder.try_decode() { | ||
| Ok(DecodeResult::Data(metadata)) => metadata, // decode successful | ||
| other => { | ||
| panic!("expected DecodeResult::Data, got: {other:?}") | ||
| } | ||
| }; | ||
|
|
||
| // In this scenario, a query is performed which projects columns 0, 1, and 4 | ||
| // after applying a predicate to column 0. Chunk level statistics on column 0 | ||
| // have already indicated only row group 0 satisfies the predicate. We now wish | ||
| // to do page level filtering. We only fetch the Column Index (min/max statistics) | ||
| // for the predicate column 0, and only fetch the Offset Index (page locations) | ||
| // for the projected columns 0, 1, and 4. Both indexes are only fetched for | ||
| // row group 0. | ||
| let mut provider = OnDemandPageIndexProvider::new(metadata.clone(), file_bytes); | ||
| let row_group_idx = 0; | ||
| provider.fetch_column_index(row_group_idx, 0)?; | ||
| provider.fetch_offset_index(row_group_idx, 0)?; | ||
| provider.fetch_offset_index(row_group_idx, 1)?; | ||
| provider.fetch_offset_index(row_group_idx, 4)?; | ||
|
|
||
| // convert the retrieved metadata into a `ParquetMetaDataBuilder` | ||
| let mut builder = metadata.into_builder(); | ||
|
|
||
| // and add the provider to the metadata | ||
| builder = builder.set_page_index(Some(Arc::new(provider))); | ||
|
|
||
| let metadata = builder.build(); | ||
| println!("== Indexes should be partially populated"); | ||
| print_page_index(&metadata, 0)?; | ||
| println!("== Indexes should be unpopulated"); | ||
| print_page_index(&metadata, 1)?; | ||
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
| ////////////////////////////////////////////// | ||
| // helper functions | ||
|
|
||
| fn print_page_index(metadata: &ParquetMetaData, row_group_idx: usize) -> Result<()> { | ||
| if let Some(page_index) = metadata.page_index() { | ||
| let num_columns = metadata.file_metadata().schema_descr().num_columns(); | ||
|
|
||
| println!("\nIndexes for row group {row_group_idx}:"); | ||
| for col_idx in 0..num_columns { | ||
| println!( | ||
| " Column {col_idx}: has offset idx {}, has column idx {}", | ||
| page_index.offset_index(row_group_idx, col_idx).is_some(), | ||
| page_index.column_index(row_group_idx, col_idx).is_some() | ||
| ); | ||
| } | ||
| println!(); | ||
| } else { | ||
| println!("No page index in metadata"); | ||
| println!("Note: This example requires a file with page indexes."); | ||
| println!("Try using alltypes_tiny_pages.parquet or another file with page indexes."); | ||
| return Err(ParquetError::General("no page index".to_string())); | ||
| } | ||
| Ok(()) | ||
| } | ||
|
|
||
| fn create_sample_file(temp_path: &PathBuf) -> Result<()> { | ||
| use arrow::array::{Int32Array, StringArray}; | ||
| use arrow::datatypes::{DataType, Field, Schema}; | ||
| use arrow::record_batch::RecordBatch; | ||
| use parquet::arrow::ArrowWriter; | ||
| use parquet::file::properties::{EnabledStatistics, WriterProperties}; | ||
|
|
||
| println!("Creating sample file: {}", temp_path.display()); | ||
|
|
||
| // Create a sample dataset with multiple columns | ||
| let schema = Arc::new(Schema::new(vec![ | ||
| Field::new("id", DataType::Int32, false), | ||
| Field::new("value", DataType::Int32, false), | ||
| Field::new("name", DataType::Utf8, false), | ||
| Field::new("score", DataType::Int32, false), | ||
| Field::new("category", DataType::Utf8, false), | ||
| Field::new("amount", DataType::Int32, false), | ||
| ])); | ||
|
|
||
| // Create multiple row groups with multiple pages | ||
| let file = File::create(temp_path)?; | ||
| let props = WriterProperties::builder() | ||
| .set_statistics_enabled(EnabledStatistics::Page) | ||
| .set_data_page_size_limit(100) // Small pages for demonstration | ||
| .set_write_batch_size(10) | ||
| .build(); | ||
|
|
||
| let mut writer = ArrowWriter::try_new(file, schema.clone(), Some(props))?; | ||
|
|
||
| // Write several row groups | ||
| for row_group in 0..3 { | ||
| for batch_num in 0..5 { | ||
| let offset = (row_group * 50) + (batch_num * 10); | ||
| let batch = RecordBatch::try_new( | ||
| schema.clone(), | ||
| vec![ | ||
| Arc::new(Int32Array::from( | ||
| (offset..offset + 10).collect::<Vec<i32>>(), | ||
| )), | ||
| Arc::new(Int32Array::from( | ||
| (offset..offset + 10).map(|x| x * 2).collect::<Vec<i32>>(), | ||
| )), | ||
| Arc::new(StringArray::from( | ||
| (offset..offset + 10) | ||
| .map(|x| format!("name{x}")) | ||
| .collect::<Vec<String>>(), | ||
| )), | ||
| Arc::new(Int32Array::from( | ||
| (offset..offset + 10).map(|x| x * 3).collect::<Vec<i32>>(), | ||
| )), | ||
| Arc::new(StringArray::from( | ||
| (offset..offset + 10) | ||
| .map(|x| if x % 2 == 0 { "even" } else { "odd" }) | ||
| .collect::<Vec<&str>>(), | ||
| )), | ||
| Arc::new(Int32Array::from( | ||
| (offset..offset + 10).map(|x| x * 4).collect::<Vec<i32>>(), | ||
| )), | ||
| ], | ||
| )?; | ||
| writer.write(&batch)?; | ||
| } | ||
| writer.flush()?; | ||
| } | ||
|
|
||
| writer.close()?; | ||
| Ok(()) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice