Skip to content
Draft
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

63 changes: 63 additions & 0 deletions datafusion/common/src/pruning.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,47 @@ pub trait PruningStatistics {
column: &Column,
values: &HashSet<ScalarValue>,
) -> Option<BooleanArray>;

/// Return the minimum values for the struct field reached from `column`
/// by `path`, if known.
///
/// For example, `get_field(s, 'a', 'b')` has `column` `s` and `path`
/// `["a", "b"]`. The path is never empty. The contract matches
/// [`Self::min_values`].
///
/// The default returns `None`, so pruning keeps every container.
fn min_values_for_field(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Open question: should this take an expression instead of a column + path?

An expression would also cover lower(col) backed by a precomputed column, or variant_get. A path only covers struct fields.

I used a path because PruningStatistics lives in datafusion-common, which cannot name PhysicalExpr (physical-expr-common depends on common). An expression-keyed API means moving this trait (and PrunableStatistics / CompositePruningStatistics) to physical-expr-common, with a re-export here.

A path can be widened later: expression methods with a default that maps get_field(col, ...) to these path methods. Should we move the trait now instead?

&self,
_column: &Column,
_path: &[String],
) -> Option<ArrayRef> {
None
}

/// Return the maximum values for a struct field.
///
/// See [`Self::min_values_for_field`].
fn max_values_for_field(
&self,
_column: &Column,
_path: &[String],
) -> Option<ArrayRef> {
None
}

/// Return the null counts for a struct field.
///
/// A row counts as null when the field or any of its ancestors is null,
/// because `get_field` returns null in both cases.
///
/// See [`Self::min_values_for_field`].
fn null_counts_for_field(
&self,
_column: &Column,
_path: &[String],
) -> Option<ArrayRef> {
None
}
}

/// Prune files based on their partition values.
Expand Down Expand Up @@ -519,6 +560,28 @@ impl PruningStatistics for CompositePruningStatistics {
}
None
}

fn min_values_for_field(&self, column: &Column, path: &[String]) -> Option<ArrayRef> {
self.statistics
.iter()
.find_map(|stats| stats.min_values_for_field(column, path))
}

fn max_values_for_field(&self, column: &Column, path: &[String]) -> Option<ArrayRef> {
self.statistics
.iter()
.find_map(|stats| stats.max_values_for_field(column, path))
}

fn null_counts_for_field(
&self,
column: &Column,
path: &[String],
) -> Option<ArrayRef> {
self.statistics
.iter()
.find_map(|stats| stats.null_counts_for_field(column, path))
}
}

#[cfg(test)]
Expand Down
33 changes: 32 additions & 1 deletion datafusion/datasource-parquet/src/leaf_resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

//! O(1) resolution of an Arrow field name to its Parquet leaf column index.

use arrow::datatypes::Schema;
use arrow::datatypes::{DataType, Field, Schema};
use datafusion_common::HashMap;
use parquet::arrow::arrow_reader::statistics::StatisticsConverter;
use parquet::schema::types::SchemaDescriptor;
Expand Down Expand Up @@ -99,6 +99,37 @@ impl<'a> LeafResolver<'a> {
}
}

/// The Parquet leaf column index and Arrow field of the struct field reached
/// from the root column `column` by `path`.
///
/// Returns `None` unless every step is a struct field, the leaf is a
/// primitive, and no ancestor is repeated. A field below a list or map has
/// statistics per element, not per row.
pub(crate) fn struct_field_leaf<'a>(
arrow_schema: &'a Schema,
parquet_schema: &SchemaDescriptor,
column: &str,
path: &[String],
) -> Option<(usize, &'a Field)> {
let mut field = arrow_schema.field_with_name(column).ok()?;
for name in path {
let DataType::Struct(fields) = field.data_type() else {
return None;
};
field = fields.iter().find(|f| f.name() == name)?;
}
if field.data_type().is_nested() {
return None;
}
let leaf = parquet_schema.columns().iter().position(|descr| {
let parts = descr.path().parts();
parts.len() == path.len() + 1
&& parts[0] == column
&& parts[1..].iter().zip(path).all(|(a, b)| a == b)
})?;
(parquet_schema.column(leaf).max_rep_level() == 0).then_some((leaf, field))
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
20 changes: 9 additions & 11 deletions datafusion/datasource-parquet/src/opener/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1479,17 +1479,15 @@ impl RowGroupsPrunedParquetOpen {
// page index exists before attempting to read it.
let arrow_schema = &self.prepared.loaded.prepared.physical_file_schema;
let parquet_schema = parquet_metadata.file_metadata().schema_descr();
Ok(page_pruning_predicate.predicate_column_names().any(|name| {
let Some((leaf_idx, _)) = parquet_column(parquet_schema, arrow_schema, name)
else {
return false;
};
row_groups.row_group_indexes().any(|rg_idx| {
let column = parquet_metadata.row_group(rg_idx).column(leaf_idx);
column.column_index_offset().is_some()
&& column.offset_index_offset().is_some()
})
}))
Ok(page_pruning_predicate
.predicate_leaf_indexes(arrow_schema, parquet_schema)
.any(|leaf_idx| {
row_groups.row_group_indexes().any(|rg_idx| {
let column = parquet_metadata.row_group(rg_idx).column(leaf_idx);
column.column_index_offset().is_some()
&& column.offset_index_offset().is_some()
})
}))
}

/// Load the page index if pruning requires it and metadata did not include it.
Expand Down
79 changes: 67 additions & 12 deletions datafusion/datasource-parquet/src/page_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

//! Contains code to filter entire pages

use crate::leaf_resolver::struct_field_leaf;
use std::collections::HashSet;
use std::sync::Arc;

Expand Down Expand Up @@ -170,7 +171,7 @@ impl PagePruningAccessPlanFilter {
continue;
}

if pp.required_columns().single_column().is_none() {
if pp.required_columns().single_field().is_none() {
debug!("Ignoring multi-column page pruning predicate: {predicate}");
all_predicates_supported = false;
continue;
Expand Down Expand Up @@ -256,7 +257,7 @@ impl PagePruningAccessPlanFilter {
let inverted = build_inverted_predicate(predicate, arrow_schema)?;
inverted
.required_columns()
.single_column()
.single_field()
.is_some()
.then_some(inverted)
})
Expand Down Expand Up @@ -471,14 +472,20 @@ impl PagePruningAccessPlanFilter {
self.predicates.len()
}

/// Returns the names of the columns referenced by the page pruning
/// predicates (each predicate references exactly one column, see
/// [`Self::new`]).
pub(crate) fn predicate_column_names(&self) -> impl Iterator<Item = &str> {
self.predicates
.iter()
.filter_map(|p| p.required_columns().single_column())
.map(|c| c.name())
/// Returns the Parquet leaf column indexes read by the page pruning
/// predicates (each predicate reads exactly one column or struct field,
/// see [`Self::new`]).
pub(crate) fn predicate_leaf_indexes<'a>(
&'a self,
arrow_schema: &'a Schema,
parquet_schema: &'a SchemaDescriptor,
) -> impl Iterator<Item = usize> + 'a {
self.predicates.iter().filter_map(move |p| {
let (column, path) = p.required_columns().single_field()?;
field_converter(column.name(), path, arrow_schema, parquet_schema)
.ok()?
.parquet_column_index()
})
}
}

Expand Down Expand Up @@ -605,9 +612,9 @@ fn prune_pages_for_predicate(
#[cfg(test)]
tests::PAGE_PREDICATE_CALLS.set(tests::PAGE_PREDICATE_CALLS.get() + 1);

let column = predicate.required_columns().single_column()?;
let (column, path) = predicate.required_columns().single_field()?;
let converter =
match StatisticsConverter::try_new(column.name(), arrow_schema, parquet_schema) {
match field_converter(column.name(), path, arrow_schema, parquet_schema) {
Ok(converter) => converter,
Err(e) => {
debug!(
Expand All @@ -627,6 +634,28 @@ fn prune_pages_for_predicate(
)
}

/// A [`StatisticsConverter`] for `column`, or for the struct field reached
/// from it by `path` when `path` is not empty.
fn field_converter<'a>(
column: &str,
path: &[String],
arrow_schema: &'a Schema,
parquet_schema: &'a SchemaDescriptor,
) -> parquet::errors::Result<StatisticsConverter<'a>> {
if path.is_empty() {
return StatisticsConverter::try_new(column, arrow_schema, parquet_schema);
}
let Some((leaf, field)) =
struct_field_leaf(arrow_schema, parquet_schema, column, path)
else {
return Err(parquet::errors::ParquetError::General(format!(
"No Parquet leaf for struct field {column}.{}",
path.join(".")
)));
};
StatisticsConverter::from_column_index(leaf, field, parquet_schema)
}

/// Returns a [`RowSelection`] for the rows in this row group to scan, in addition to a vec of
/// booleans that state if each page was matched (true) or not (false).
///
Expand Down Expand Up @@ -818,6 +847,32 @@ impl PruningStatistics for PagesPruningStatistics<'_> {
self.page_offsets.len()
}

// One converter reads one leaf, so the struct field methods return the
// same statistics as the column methods.
fn min_values_for_field(
&self,
column: &datafusion_common::Column,
_path: &[String],
) -> Option<ArrayRef> {
self.min_values(column)
}

fn max_values_for_field(
&self,
column: &datafusion_common::Column,
_path: &[String],
) -> Option<ArrayRef> {
self.max_values(column)
}

fn null_counts_for_field(
&self,
column: &datafusion_common::Column,
_path: &[String],
) -> Option<ArrayRef> {
self.null_counts(column)
}

fn null_counts(&self, _column: &datafusion_common::Column) -> Option<ArrayRef> {
match self
.converter
Expand Down
57 changes: 57 additions & 0 deletions datafusion/datasource-parquet/src/row_group_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use std::sync::Arc;

use super::{ParquetAccessPlan, ParquetFileMetrics, RowGroupAccess};
use crate::bloom_filter::BloomFilterStatistics;
use crate::leaf_resolver::struct_field_leaf;
use crate::metadata::{has_untrusted_byte_array_stats, has_untrusted_min_max_order};
use crate::pruning::build_inverted_predicate;
use arrow::array::{ArrayRef, BooleanArray, UInt64Array};
Expand Down Expand Up @@ -544,6 +545,40 @@ impl<'a> RowGroupPruningStatistics<'a> {
Some(converter)
}

/// A converter for the Parquet leaf below `column` at struct field `path`.
/// See [`struct_field_leaf`] for which paths resolve.
fn field_statistics_converter(
&self,
column: &Column,
path: &[String],
) -> Option<StatisticsConverter<'a>> {
let (leaf, field) = struct_field_leaf(
self.arrow_schema,
self.parquet_schema,
&column.name,
path,
)?;
Some(
StatisticsConverter::from_column_index(leaf, field, self.parquet_schema)
.ok()?
// Missing counts cannot rule out nulls.
.with_missing_null_counts_as_zero(false),
)
}

fn field_min_max_statistics_converter(
&self,
column: &Column,
path: &[String],
) -> Option<StatisticsConverter<'a>> {
let converter = self.field_statistics_converter(column, path)?;
let index = converter.parquet_column_index()?;
if has_untrusted_min_max_order(self.parquet_schema, self.column_orders, index) {
return None;
}
Some(converter)
}

fn mask_untrusted_byte_array_stats(
&self,
parquet_index: Option<usize>,
Expand Down Expand Up @@ -605,6 +640,28 @@ impl PruningStatistics for RowGroupPruningStatistics<'_> {
) -> Option<BooleanArray> {
None
}

fn min_values_for_field(&self, column: &Column, path: &[String]) -> Option<ArrayRef> {
let converter = self.field_min_max_statistics_converter(column, path)?;
let values = converter.row_group_mins(self.metadata_iter()).ok()?;
self.mask_untrusted_byte_array_stats(converter.parquet_column_index(), values)
}

fn max_values_for_field(&self, column: &Column, path: &[String]) -> Option<ArrayRef> {
let converter = self.field_min_max_statistics_converter(column, path)?;
let values = converter.row_group_maxes(self.metadata_iter()).ok()?;
self.mask_untrusted_byte_array_stats(converter.parquet_column_index(), values)
}

fn null_counts_for_field(
&self,
column: &Column,
path: &[String],
) -> Option<ArrayRef> {
let converter = self.field_statistics_converter(column, path)?;
let counts = converter.row_group_null_counts(self.metadata_iter()).ok()?;
Some(Arc::new(counts) as ArrayRef)
}
}

#[cfg(test)]
Expand Down
1 change: 1 addition & 0 deletions datafusion/pruning/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ log = { workspace = true }
[dev-dependencies]
criterion = { workspace = true }
datafusion-expr = { workspace = true }
datafusion-functions = { workspace = true }
datafusion-functions-nested = { workspace = true }
insta = { workspace = true }
itertools = { workspace = true }
Expand Down
Loading