From b554ef0caad41dd78e53c8f3fc67988a9a69e89d Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Mon, 30 Nov 2026 23:59:07 -0800 Subject: [PATCH 1/6] refactor: move the single column check into page pruning `RequiredColumns::single_column()` has one caller outside the pruning crate: Parquet page pruning. The check only makes sense there. The pages of each column have their own row boundaries, so page pruning can evaluate a predicate only on the pages of one column. Row group and file pruning have no such limit. This commit adds `RequiredColumns::columns()`, which yields the column of each required statistic. It deprecates `RequiredColumns::single_column()` and adds a private `single_column` function in `page_filter.rs` that uses `columns()`. Behavior does not change. Co-Authored-By: Claude Fable 5.2 --- .../datasource-parquet/src/page_filter.rs | 62 ++++++++++++++++--- datafusion/pruning/src/pruning_predicate.rs | 42 +++++++++++-- 2 files changed, 91 insertions(+), 13 deletions(-) diff --git a/datafusion/datasource-parquet/src/page_filter.rs b/datafusion/datasource-parquet/src/page_filter.rs index f93f84fb0d230..ef998b0e0beed 100644 --- a/datafusion/datasource-parquet/src/page_filter.rs +++ b/datafusion/datasource-parquet/src/page_filter.rs @@ -18,6 +18,7 @@ use arrow::{ }; use datafusion_common::ScalarValue; use datafusion_common::pruning::PruningStatistics; +use datafusion_physical_expr::expressions::Column; use datafusion_physical_expr::{PhysicalExpr, split_conjunction}; use datafusion_pruning::{MAX_IN_LIST_SIZE, PruningPredicate, PruningPredicateBuilder}; @@ -169,7 +170,7 @@ impl PagePruningAccessPlanFilter { continue; } - if pp.required_columns().single_column().is_none() { + if single_column(&pp).is_none() { debug!("Ignoring multi-column page pruning predicate: {predicate}"); all_predicates_supported = false; continue; @@ -258,11 +259,7 @@ impl PagePruningAccessPlanFilter { .try_build_inverse(Arc::clone(predicate.orig_expr())) .ok() .flatten()?; - inverted - .required_columns() - .single_column() - .is_some() - .then_some(inverted) + single_column(&inverted).is_some().then_some(inverted) }) .collect() } else { @@ -481,11 +478,22 @@ impl PagePruningAccessPlanFilter { pub(crate) fn predicate_column_names(&self) -> impl Iterator { self.predicates .iter() - .filter_map(|p| p.required_columns().single_column()) + .filter_map(single_column) .map(|c| c.name()) } } +/// Returns the column if every statistic that `predicate` requires is of that +/// column. Returns `None` if the predicate reads several columns or none. +/// +/// The pages of each column have their own row boundaries. So page pruning can +/// evaluate a predicate only on the pages of one column. +fn single_column(predicate: &PruningPredicate) -> Option<&Column> { + let mut columns = predicate.required_columns().columns(); + let first = columns.next()?; + columns.all(|c| c == first).then_some(first) +} + fn update_selection( current_selection: Option, row_selection: RowSelection, @@ -609,7 +617,7 @@ 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 = single_column(predicate)?; let converter = match StatisticsConverter::try_new(column.name(), arrow_schema, parquet_schema) { Ok(converter) => converter, @@ -866,7 +874,7 @@ mod tests { use arrow::record_batch::RecordBatch; use bytes::Bytes; use datafusion_expr::Operator; - use datafusion_physical_expr::expressions::{BinaryExpr, Column, lit}; + use datafusion_physical_expr::expressions::{BinaryExpr, lit}; use datafusion_physical_plan::metrics::ExecutionPlanMetricsSet; use parquet::arrow::ArrowWriter; use parquet::arrow::arrow_reader::{ @@ -881,6 +889,42 @@ mod tests { pub(super) static PAGE_PREDICATE_CALLS: std::cell::Cell = const { std::cell::Cell::new(0) }; } + #[test] + fn single_column_requires_one_column() { + let schema = Arc::new(Schema::new(vec![ + Field::new("a", DataType::Int32, true), + Field::new("b", DataType::Int32, true), + ])); + let cmp = |name: &str, idx, op| -> Arc { + Arc::new(BinaryExpr::new( + Arc::new(Column::new(name, idx)), + op, + lit(1), + )) + }; + let one: Arc = Arc::new(BinaryExpr::new( + cmp("a", 0, Operator::Gt), + Operator::And, + cmp("a", 0, Operator::Lt), + )); + let pp = PruningPredicateBuilder::new() + .with_file_schema(Arc::clone(&schema)) + .try_build(one) + .unwrap(); + assert_eq!(single_column(&pp), Some(&Column::new("a", 0))); + + let two: Arc = Arc::new(BinaryExpr::new( + cmp("a", 0, Operator::Gt), + Operator::And, + cmp("b", 1, Operator::Lt), + )); + let pp = PruningPredicateBuilder::new() + .with_file_schema(schema) + .try_build(two) + .unwrap(); + assert_eq!(single_column(&pp), None); + } + #[test] fn inverse_pruning_short_circuits() { // Each row group has three two-row pages. Only the middle page can diff --git a/datafusion/pruning/src/pruning_predicate.rs b/datafusion/pruning/src/pruning_predicate.rs index c064193872516..4d1bcea1c396e 100644 --- a/datafusion/pruning/src/pruning_predicate.rs +++ b/datafusion/pruning/src/pruning_predicate.rs @@ -950,6 +950,14 @@ impl RequiredColumns { Self::default() } + /// Returns the column of each statistic that the predicate requires, in order. + /// + /// A column appears once for each of its statistics. For example, if the + /// predicate requires the min and the max of `a`, `a` appears twice. + pub fn columns(&self) -> impl Iterator { + self.columns.iter().map(|(column, _, _)| column) + } + /// Returns Some(column) if this is a single column predicate. /// /// Returns None if this is a multi-column predicate. @@ -958,6 +966,10 @@ impl RequiredColumns { /// * `a > 5 OR a < 10` returns `Some(a)` /// * `a > 5 OR b < 10` returns `None` /// * `true` returns None + #[deprecated( + since = "57.0.0", + note = "use `RequiredColumns::columns` and compare the columns instead" + )] pub fn single_column(&self) -> Option<&phys_expr::Column> { if self.columns.windows(2).all(|w| { // check if all columns are the same (ignoring statistics and field) @@ -4413,6 +4425,26 @@ mod tests { Ok(()) } + #[test] + fn required_columns_lists_each_statistic_column() { + let schema = Arc::new(Schema::new(vec![ + Field::new("a", DataType::Int32, true), + Field::new("b", DataType::Int32, true), + ])); + let expr = col("a").gt(lit(1)).and(col("b").lt(lit(2))); + let expr = logical2physical(&expr, &schema); + let predicate = PruningPredicateBuilder::new() + .with_file_schema(schema) + .try_build(expr) + .unwrap(); + let names: Vec<_> = predicate + .required_columns() + .columns() + .map(|c| c.name()) + .collect(); + assert_eq!(names, ["a", "a", "a", "b", "b"]); + } + #[test] fn large_string_in_list_prunes_exact_intervals() -> Result<()> { let types = [ @@ -4492,10 +4524,12 @@ mod tests { assert!(Arc::ptr_eq(predicate.orig_expr(), &expr)); assert_eq!(predicate.literal_guarantees().len(), 1); assert_eq!(predicate.literal_guarantees()[0].literals.len(), count); - assert_eq!( - predicate.required_columns().single_column().unwrap().name(), - "c1" - ); + let names: HashSet<_> = predicate + .required_columns() + .columns() + .map(|c| c.name()) + .collect(); + assert_eq!(names, HashSet::from(["c1"])); if count > MAX_IN_LIST_SIZE { // The expression and statistics schema do not grow with the domain. assert_eq!(predicate.required_columns.columns.len(), 4); From 8ec7a1040c15f3078b3b04bef0c764f940b6739e Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:41:09 -0800 Subject: [PATCH 2/6] test: add struct field pruning tests Predicates on struct fields such as `s['a'] > 5` do not prune Parquet row groups or pages today. These tests record that behavior. A later change adds the pruning and updates the expected output, so its diff shows the effect. The tests add a sqllogictest file with EXPLAIN ANALYZE pruning metrics. They also add a core integration test for a struct field without a null count statistic. Co-Authored-By: Claude Fable 5.2 --- datafusion/core/tests/parquet/mod.rs | 1 + .../tests/parquet/struct_field_pruning.rs | 98 ++++ .../parquet_struct_field_pruning.slt | 498 ++++++++++++++++++ 3 files changed, 597 insertions(+) create mode 100644 datafusion/core/tests/parquet/struct_field_pruning.rs create mode 100644 datafusion/sqllogictest/test_files/parquet_struct_field_pruning.slt diff --git a/datafusion/core/tests/parquet/mod.rs b/datafusion/core/tests/parquet/mod.rs index 54482eaa5d02d..a76e742e8ecd7 100644 --- a/datafusion/core/tests/parquet/mod.rs +++ b/datafusion/core/tests/parquet/mod.rs @@ -47,6 +47,7 @@ mod row_group_pruning; mod schema; mod schema_coercion; mod string_in_list_pruning; +mod struct_field_pruning; mod utils; #[cfg(test)] diff --git a/datafusion/core/tests/parquet/struct_field_pruning.rs b/datafusion/core/tests/parquet/struct_field_pruning.rs new file mode 100644 index 0000000000000..d24809ef7ed2d --- /dev/null +++ b/datafusion/core/tests/parquet/struct_field_pruning.rs @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +//! Pruning on struct fields, for files that SQL cannot write. + +use std::io::Write; +use std::sync::Arc; + +use arrow::array::{ArrayRef, Int64Array, RecordBatch, StructArray}; +use arrow::datatypes::{DataType, Field, Fields, Schema}; +use datafusion::prelude::{ParquetReadOptions, SessionContext}; +use datafusion_common::ScalarValue; +use parquet::arrow::ArrowWriter; +use parquet::file::metadata::{ParquetMetaData, ParquetMetaDataWriter}; +use parquet::file::statistics::Statistics; +use parquet::file::writer::TrackedWrite; +use tempfile::NamedTempFile; + +/// Writes `s: {a: Int64}` with rows `{a: 1}` and `{a: null}` in one row +/// group. The footer keeps the min and max of `s.a`, but not its null count. +fn struct_file_without_null_count() -> NamedTempFile { + let a = Field::new("a", DataType::Int64, true); + let schema = Arc::new(Schema::new(vec![Field::new( + "s", + DataType::Struct(Fields::from(vec![a.clone()])), + true, + )])); + let values: ArrayRef = Arc::new(Int64Array::from(vec![Some(1), None])); + let s = StructArray::new(Fields::from(vec![a]), vec![values], None); + let batch = RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(s)]).unwrap(); + let mut bytes = Vec::new(); + let mut writer = ArrowWriter::try_new(&mut bytes, schema, None).unwrap(); + writer.write(&batch).unwrap(); + let metadata = writer.close().unwrap(); + + let group = &metadata.row_groups()[0]; + let column = group.column(0).clone(); + let Statistics::Int64(stats) = column.statistics().unwrap() else { + panic!("expected Int64 statistics"); + }; + let stats = Statistics::int64( + stats.min_opt().copied(), + stats.max_opt().copied(), + None, + None, + false, + ); + let column = column.into_builder().set_statistics(stats).build().unwrap(); + let group = group + .clone() + .into_builder() + .set_column_metadata(vec![column]) + .build() + .unwrap(); + let metadata = ParquetMetaData::new(metadata.file_metadata().clone(), vec![group]); + + // Replace the footer. The encoded rows and their offsets do not change. + let footer_len = + u32::from_le_bytes(bytes[bytes.len() - 8..bytes.len() - 4].try_into().unwrap()); + bytes.truncate(bytes.len() - 8 - footer_len as usize); + let mut file = tempfile::Builder::new() + .suffix(".parquet") + .tempfile() + .unwrap(); + let mut output = TrackedWrite::new(file.as_file_mut()); + output.write_all(&bytes).unwrap(); + ParquetMetaDataWriter::new_with_tracked(output, &metadata) + .finish() + .unwrap(); + file +} + +#[tokio::test] +async fn missing_struct_field_null_count_keeps_row_group() { + // A missing null count is unknown, not zero. `s['a'] IS NULL` must not + // prune the row group. + let file = struct_file_without_null_count(); + let ctx = SessionContext::new(); + ctx.register_parquet( + "t", + file.path().to_str().unwrap(), + ParquetReadOptions::default(), + ) + .await + .unwrap(); + let batches = ctx + .sql("SELECT count(*) FROM t WHERE s['a'] IS NULL") + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!( + ScalarValue::try_from_array(batches[0].column(0), 0).unwrap(), + ScalarValue::Int64(Some(1)), + ); +} diff --git a/datafusion/sqllogictest/test_files/parquet_struct_field_pruning.slt b/datafusion/sqllogictest/test_files/parquet_struct_field_pruning.slt new file mode 100644 index 0000000000000..26fe96be89e48 --- /dev/null +++ b/datafusion/sqllogictest/test_files/parquet_struct_field_pruning.slt @@ -0,0 +1,498 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +# SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +# Row group pruning with statistics for predicates on struct fields +# (`get_field(s, 'a')`, written `s['a']`). + +statement ok +CREATE TABLE src AS VALUES +-- ***** Row Group 0: a in [1, 3] ***** + (1, 100), + (2, 200), + (3, 300), +-- ***** Row Group 1: a in [10, 12] ***** + (10, 100), + (11, 200), + (12, 300), +-- ***** Row Group 2: null struct, a = 20, null a ***** + (NULL, NULL), + (20, 400), + (-1, 500), +-- ***** Row Group 3: a in [30, 32] ***** + (30, 100), + (31, 200), + (32, 300); + +# Row 7 (column1 = NULL) is a null struct. Row 9 (column1 = -1) is a non-null +# struct with a null `a`. +statement ok +COPY ( + SELECT + CASE + WHEN column1 IS NULL THEN NULL + WHEN column1 = -1 THEN named_struct('a', CAST(NULL AS INT), 'b', column2) + ELSE named_struct('a', column1, 'b', column2) + END AS s, + column1 AS id + FROM src +) +TO 'test_files/scratch/parquet_struct_field_pruning/data.parquet' +STORED AS PARQUET +OPTIONS ('format.max_row_group_size' '3'); + +statement ok +DROP TABLE src; + +statement ok +CREATE EXTERNAL TABLE t +STORED AS PARQUET +LOCATION 'test_files/scratch/parquet_struct_field_pruning/data.parquet'; + +statement ok +set datafusion.explain.analyze_level = summary; + +statement ok +set datafusion.explain.analyze_categories = 'rows'; + +# Results are correct. +query ?I rowsort +SELECT s, id FROM t WHERE s['a'] > 15; +---- +{a: 20, b: 400} 20 +{a: 30, b: 100} 30 +{a: 31, b: 200} 31 +{a: 32, b: 300} 32 + +query I rowsort +SELECT id FROM t WHERE s['a'] IS NULL; +---- +-1 +NULL + +# Row groups 0 and 1 are pruned. +query TT +EXPLAIN ANALYZE SELECT * FROM t WHERE s['a'] > 15; +---- +Plan with Metrics +01)FilterExec: __datafusion_extracted_1@0 > 15, projection=[s@1, id@2], metrics=[output_rows=4, selectivity=33.33% (4/12)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=12] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s, id], file_type=parquet, predicate=get_field(s@0, a) > 15, metrics=[output_rows=12, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 4 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=27.52% (926/3.37 K)] + +# Only row group 0 matches. +query TT +EXPLAIN ANALYZE SELECT * FROM t WHERE s['a'] <= 2; +---- +Plan with Metrics +01)FilterExec: __datafusion_extracted_1@0 <= 2, projection=[s@1, id@2], metrics=[output_rows=2, selectivity=16.67% (2/12)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=12] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s, id], file_type=parquet, predicate=get_field(s@0, a) <= 2, metrics=[output_rows=12, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 4 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=27.52% (926/3.37 K)] + +# Equality, with the literal on the left. +query TT +EXPLAIN ANALYZE SELECT * FROM t WHERE 11 = s['a']; +---- +Plan with Metrics +01)FilterExec: __datafusion_extracted_1@0 = 11, projection=[s@1, id@2], metrics=[output_rows=1, selectivity=8.33% (1/12)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=12] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s, id], file_type=parquet, predicate=get_field(s@0, a) = 11, metrics=[output_rows=12, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 4 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=27.52% (926/3.37 K)] + +# Row group 2 holds only one non-null `a`, so `s['a'] = 20` keeps it. +query TT +EXPLAIN ANALYZE SELECT * FROM t WHERE s['a'] = 20; +---- +Plan with Metrics +01)FilterExec: __datafusion_extracted_1@0 = 20, projection=[s@1, id@2], metrics=[output_rows=1, selectivity=8.33% (1/12)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=12] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s, id], file_type=parquet, predicate=get_field(s@0, a) = 20, metrics=[output_rows=12, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 4 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=27.52% (926/3.37 K)] + +# Two different struct fields in one comparison are not prunable. +query TT +EXPLAIN ANALYZE SELECT * FROM t WHERE s['a'] > s['b']; +---- +Plan with Metrics +01)FilterExec: __datafusion_extracted_2@1 < __datafusion_extracted_1@0, projection=[s@2, id@3], metrics=[output_rows=0, selectivity=0% (0/12)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=12] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, get_field(s@0, b) as __datafusion_extracted_2, s, id], file_type=parquet, predicate=get_field(s@0, b) < get_field(s@0, a), metrics=[output_rows=12, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 4 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=27.52% (926/3.37 K)] + +# A struct field combined with a plain column in OR. +query TT +EXPLAIN ANALYZE SELECT * FROM t WHERE s['a'] > 25 OR id < 2; +---- +Plan with Metrics +01)FilterExec: __datafusion_extracted_1@0 > 25 OR id@2 < 2, projection=[s@1, id@2], metrics=[output_rows=5, selectivity=41.67% (5/12)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=12] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s, id], file_type=parquet, predicate=get_field(s@0, a) > 25 OR id@1 < 2, metrics=[output_rows=12, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 4 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=27.52% (926/3.37 K)] + +# An IN list longer than 20 values uses the compact form, when the limit +# allows it. Only row group 3 (`a` in [30, 32]) can match. A table reads +# the limit when it is created, so `t_in` is created after the `set`. +statement ok +set datafusion.execution.parquet.max_in_list_size = 100; + +statement ok +CREATE EXTERNAL TABLE t_in +STORED AS PARQUET +LOCATION 'test_files/scratch/parquet_struct_field_pruning/data.parquet'; + +query TT +EXPLAIN ANALYZE SELECT * FROM t_in WHERE s['a'] IN (30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50); +---- +Plan with Metrics +01)FilterExec: __datafusion_extracted_1@0 IN (SET) ([30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]), projection=[s@1, id@2], metrics=[output_rows=3, selectivity=25% (3/12)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=12] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s, id], file_type=parquet, predicate=get_field(s@0, a) IN (SET) ([30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]), metrics=[output_rows=12, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 4 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=27.52% (926/3.37 K)] + +statement ok +DROP TABLE t_in; + +statement ok +reset datafusion.execution.parquet.max_in_list_size; + +statement ok +DROP TABLE t; + +# Two files with one row group each. The row group of the file with +# `a` in [30, 32] is pruned by statistics, so the scan reads no data pages +# from it. File-level pruning (`files_ranges_pruned_statistics`) is not +# covered: it reads `Statistics`, which has no struct field statistics. +statement ok +COPY (SELECT named_struct('a', column1) AS s FROM (VALUES (1), (2), (3))) +TO 'test_files/scratch/parquet_struct_field_pruning/two_files/low.parquet' +STORED AS PARQUET; + +statement ok +COPY (SELECT named_struct('a', column1) AS s FROM (VALUES (30), (31), (32))) +TO 'test_files/scratch/parquet_struct_field_pruning/two_files/high.parquet' +STORED AS PARQUET; + +statement ok +CREATE EXTERNAL TABLE two_files +STORED AS PARQUET +LOCATION 'test_files/scratch/parquet_struct_field_pruning/two_files/'; + +query ? +SELECT s FROM two_files WHERE s['a'] < 10 ORDER BY s['a']; +---- +{a: 1} +{a: 2} +{a: 3} + +query TT +EXPLAIN ANALYZE SELECT * FROM two_files WHERE s['a'] < 10; +---- +Plan with Metrics +01)FilterExec: __datafusion_extracted_1@0 < 10, projection=[s@1], metrics=[output_rows=3, selectivity=50% (3/6)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=2, metrics=[output_rows=6] +03)----DataSourceExec: file_groups={2 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/two_files/high.parquet], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/two_files/low.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s], file_type=parquet, predicate=get_field(s@0, a) < 10, metrics=[output_rows=6, files_ranges_pruned_statistics=2 total → 2 matched, row_groups_pruned_statistics=2 total → 2 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=26.69% (158/592)] + +statement ok +DROP TABLE two_files; + +# One row group with 10 pages of 10 rows each. Page i holds `a` in +# [10 * i, 10 * i + 9], so `s['a'] >= 85` can skip 8 of the 10 pages. +statement ok +COPY (SELECT named_struct('a', value) AS s FROM generate_series(0, 99)) +TO 'test_files/scratch/parquet_struct_field_pruning/pages.parquet' +STORED AS PARQUET +OPTIONS ( + 'format.max_row_group_size' '100', + 'format.data_page_row_count_limit' '10', + 'format.write_batch_size' '10' +); + +statement ok +CREATE EXTERNAL TABLE pages +STORED AS PARQUET +LOCATION 'test_files/scratch/parquet_struct_field_pruning/pages.parquet'; + +query I +SELECT count(*) FROM pages WHERE s['a'] >= 85; +---- +15 + +query TT +EXPLAIN ANALYZE SELECT * FROM pages WHERE s['a'] >= 85; +---- +Plan with Metrics +01)FilterExec: __datafusion_extracted_1@0 >= 85, projection=[s@1], metrics=[output_rows=15, selectivity=15% (15/100)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=100] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/pages.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s], file_type=parquet, predicate=get_field(s@0, a) >= 85, metrics=[output_rows=100, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=1 total → 1 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=43.97% (624/1.42 K)] + +statement ok +DROP TABLE pages; + +# Dynamic TopK: 5 row groups of 3 rows, `s['a']` = 14 down to 0, so the +# first row group holds the top 3. After it, the TopK filter +# `s['a'] IS NULL OR s['a'] > 12` can skip the other 4 row groups. +statement ok +COPY (SELECT named_struct('a', 14 - value) AS s, 14 - value AS v FROM generate_series(0, 14)) +TO 'test_files/scratch/parquet_struct_field_pruning/topk.parquet' +STORED AS PARQUET +OPTIONS ('format.max_row_group_size' '3'); + +statement ok +CREATE EXTERNAL TABLE topk +STORED AS PARQUET +LOCATION 'test_files/scratch/parquet_struct_field_pruning/topk.parquet'; + +statement ok +set datafusion.execution.parquet.pushdown_filters = true; + +statement ok +set datafusion.execution.target_partitions = 1; + +# `row_groups_pruned_dynamic_filter` is an uncategorized metric. +statement ok +set datafusion.explain.analyze_categories = 'rows,uncategorized'; + +query I +SELECT s['a'] FROM topk ORDER BY s['a'] DESC LIMIT 3; +---- +14 +13 +12 + +# The same query on a plain column, for comparison. +query TT +EXPLAIN ANALYZE SELECT v FROM topk ORDER BY v DESC LIMIT 3; +---- +Plan with Metrics +01)SortExec: TopK(fetch=3), expr=[v@0 DESC], preserve_partitioning=[false], filter=[v@0 IS NULL OR v@0 > 12], metrics=[output_rows=3] +02)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/topk.parquet]]}, projection=[v], file_type=parquet, predicate=DynamicFilter [ v@1 IS NULL OR v@1 > 12 ], sort_order_for_reorder=[v@0 DESC], reverse_row_groups=true, dynamic_rg_pruning=eligible, pruning_predicate=v_null_count@0 > 0 OR v_null_count@0 != row_count@2 AND v_max@1 > 12, required_guarantees=[], metrics=[output_rows=3, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=5 total → 5 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, row_groups_pruned_dynamic_filter=4, scan_efficiency_ratio=2.66% (73/2.75 K)] + +query TT +EXPLAIN ANALYZE SELECT s['a'] FROM topk ORDER BY s['a'] DESC LIMIT 3; +---- +Plan with Metrics +01)SortExec: TopK(fetch=3), expr=[topk.s[a]@0 DESC], preserve_partitioning=[false], filter=[topk.s[a]@0 IS NULL OR topk.s[a]@0 > 12], metrics=[output_rows=3] +02)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/topk.parquet]]}, projection=[get_field(s@0, a) as topk.s[a]], file_type=parquet, predicate=DynamicFilter [ get_field(s@0, a) IS NULL OR get_field(s@0, a) > 12 ], dynamic_rg_pruning=eligible, metrics=[output_rows=3, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=5 total → 5 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, row_groups_pruned_dynamic_filter=0, scan_efficiency_ratio=14.08% (387/2.75 K)] + +statement ok +reset datafusion.execution.parquet.pushdown_filters; + +statement ok +set datafusion.execution.target_partitions = 4; + +statement ok +set datafusion.explain.analyze_categories = 'rows'; + +statement ok +DROP TABLE topk; + +# Struct type drift: the file stores `s.a` as INT, the table declares +# DOUBLE. The schema adapter rewrites `s['a']` to +# `CAST(get_field(s, 'a') AS DOUBLE)` for this file. Comparing with 6.5 +# keeps the cast, because 6.5 has no INT equivalent. +statement ok +COPY (SELECT named_struct('a', CAST(value AS INT)) AS s FROM generate_series(0, 8)) +TO 'test_files/scratch/parquet_struct_field_pruning/drift/data.parquet' +STORED AS PARQUET +OPTIONS ('format.max_row_group_size' '3'); + +statement ok +CREATE EXTERNAL TABLE drift (s STRUCT) +STORED AS PARQUET +LOCATION 'test_files/scratch/parquet_struct_field_pruning/drift/'; + +query R +SELECT s['a'] FROM drift WHERE s['a'] > 6.5 ORDER BY s['a']; +---- +7 +8 + +# Row groups 0 and 1 (`a` in [0, 5]) can be pruned. +query TT +EXPLAIN ANALYZE SELECT * FROM drift WHERE s['a'] > 6.5; +---- +Plan with Metrics +01)FilterExec: __datafusion_extracted_1@0 > 6.5, projection=[s@1], metrics=[output_rows=2, selectivity=22.22% (2/9)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=9] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/drift/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s], file_type=parquet, predicate=get_field(s@0, a) > 6.5, metrics=[output_rows=9, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=3 total → 3 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=21.39% (213/996)] + +statement ok +DROP TABLE drift; + +# Bloom filters on struct fields. Each row group spans a wide range, so +# min/max cannot rule out `s['a'] = 50`, but the bloom filters can. +# +# | Row group | s.a | s.i8 | s.d | s.dec | +# |-----------|---------|--------|---------------------------|--------------| +# | 0 | 1, 100 | 1, 100 | 2024-01-01, 2024-04-09 | 1.00, 100.00 | +# | 1 | 2, 99 | 2, 99 | 2024-01-02, 2024-04-08 | 2.00, 99.00 | +statement ok +COPY ( + SELECT named_struct( + 'a', column1, + 'i8', CAST(column1 AS TINYINT), + 'd', CAST('2024-01-01' AS DATE) + CAST(column1 - 1 AS INT), + 'dec', CAST(column1 AS DECIMAL(10, 2)) + ) AS s + FROM (VALUES (1), (100), (2), (99)) +) +TO 'test_files/scratch/parquet_struct_field_pruning/bloom.parquet' +STORED AS PARQUET +OPTIONS ( + 'format.max_row_group_size' '2', + 'format.bloom_filter_on_write' 'true' +); + +statement ok +CREATE EXTERNAL TABLE bloom +STORED AS PARQUET +LOCATION 'test_files/scratch/parquet_struct_field_pruning/bloom.parquet'; + +# Both row groups can be skipped by their bloom filters. +query TT +EXPLAIN ANALYZE SELECT * FROM bloom WHERE s['a'] = 50; +---- +Plan with Metrics +01)FilterExec: __datafusion_extracted_1@0 = 50, projection=[s@1], metrics=[output_rows=0, selectivity=0% (0/4)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=4] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/bloom.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s], file_type=parquet, predicate=get_field(s@0, a) = 50, metrics=[output_rows=4, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=2 total → 2 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=20.1% (560/2.79 K)] + +# `!=` can never be proven false by a bloom filter. +query I +SELECT count(*) FROM bloom WHERE s['a'] != 50; +---- +4 + +# Values that are present are found for every field type. +query I +SELECT count(*) FROM bloom WHERE s['a'] = 99; +---- +1 + +query I +SELECT count(*) FROM bloom WHERE s['i8'] = 99; +---- +1 + +query I +SELECT count(*) FROM bloom WHERE s['d'] = DATE '2024-04-08'; +---- +1 + +query I +SELECT count(*) FROM bloom WHERE s['dec'] = 99.00; +---- +1 + +statement ok +DROP TABLE bloom; + +# Hash join dynamic filter. The build side `u` has ids 0, 5000 and 9999, so +# its bounds [0, 9999] cover all 10 row groups of `hj`, but its key bitmap +# only reaches row groups 0, 5 and 9. A hash-lookup filter (forced by an +# IN-list limit of 0) carries that bitmap to the probe-side scan. +statement ok +COPY (SELECT named_struct('a', value) AS s, value AS v FROM generate_series(0, 9999) ORDER BY value) +TO 'test_files/scratch/parquet_struct_field_pruning/hj.parquet' +STORED AS PARQUET +OPTIONS ('format.max_row_group_size' '1000'); + +statement ok +CREATE EXTERNAL TABLE hj +STORED AS PARQUET +LOCATION 'test_files/scratch/parquet_struct_field_pruning/hj.parquet'; + +statement ok +CREATE TABLE u(id BIGINT) AS VALUES (0), (5000), (9999); + +statement ok +set datafusion.execution.target_partitions = 1; + +statement ok +set datafusion.optimizer.hash_join_inlist_pushdown_max_size = 0; + +statement ok +set datafusion.optimizer.hash_join_inlist_pushdown_max_distinct_values = 0; + +query I +SELECT hj.v FROM u JOIN hj ON hj.s['a'] = u.id ORDER BY hj.v; +---- +0 +5000 +9999 + +# The same join on a plain column, for comparison. +query TT +EXPLAIN ANALYZE SELECT hj.v FROM u JOIN hj ON hj.v = u.id; +---- +Plan with Metrics +01)HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(id@0, v@0)], projection=[v@1], metrics=[output_rows=3, avg_fanout=100% (3/3), probe_hit_rate=0.1% (3/3.00 K)] +02)--DataSourceExec: partitions=1, partition_sizes=[1], metrics=[] +03)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/hj.parquet]]}, projection=[v], output_ordering=[v@0 ASC NULLS LAST], file_type=parquet, predicate=DynamicFilter [ v@1 >= 0 AND v@1 <= 9999 AND hash_lookup ], dynamic_rg_pruning=eligible, pruning_predicate=v_null_count@1 != row_count@2 AND v_max@0 >= 0 AND v_null_count@1 != row_count@2 AND v_min@3 <= 9999 AND v_null_count@1 != row_count@2 AND KEY_RANGE_BITMAP(v_min@3, v_max@0, 3/16384 buckets), required_guarantees=[], metrics=[output_rows=3.00 K, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=10 total → 3 matched, page_index_pages_pruned=3 total → 3 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=14.55% (7.59 K/52.19 K)] + +query TT +EXPLAIN ANALYZE SELECT hj.v FROM u JOIN hj ON hj.s['a'] = u.id; +---- +Plan with Metrics +01)HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(id@0, __datafusion_extracted_1@0)], projection=[v@2], metrics=[output_rows=3, avg_fanout=100% (3/3), probe_hit_rate=0.03% (3/10.00 K)] +02)--DataSourceExec: partitions=1, partition_sizes=[1], metrics=[] +03)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/hj.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, v], output_ordering=[v@1 ASC NULLS LAST], file_type=parquet, predicate=DynamicFilter [ get_field(s@0, a) >= 0 AND get_field(s@0, a) <= 9999 AND hash_lookup ], dynamic_rg_pruning=eligible, metrics=[output_rows=10.00 K, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=10 total → 10 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=92.57% (48.31 K/52.19 K)] + +statement ok +reset datafusion.optimizer.hash_join_inlist_pushdown_max_size; + +statement ok +reset datafusion.optimizer.hash_join_inlist_pushdown_max_distinct_values; + +statement ok +set datafusion.execution.target_partitions = 4; + +statement ok +DROP TABLE u; + +statement ok +DROP TABLE hj; + +statement ok +reset datafusion.explain.analyze_level; + +statement ok +reset datafusion.explain.analyze_categories; + +# A struct field can be NULL when the struct column itself is not +# nullable. A row group is fully matched only if the field has no nulls. +statement ok +COPY (SELECT named_struct('a', column1) AS s, column2 AS id FROM (VALUES (1, 1), (CAST(NULL AS INT), 2), (3, 3))) +TO 'test_files/scratch/parquet_struct_field_pruning/full_match/f.parquet' +STORED AS PARQUET; + +statement ok +CREATE EXTERNAL TABLE full_match STORED AS PARQUET +LOCATION 'test_files/scratch/parquet_struct_field_pruning/full_match/f.parquet'; + +statement ok +set datafusion.execution.parquet.pushdown_filters = true; + +query I +SELECT id FROM full_match WHERE s['a'] <= 5 ORDER BY id; +---- +1 +3 + +statement ok +set datafusion.execution.parquet.pushdown_filters = false; + +# A real column whose name looks like a statistics placeholder must not +# take the bloom filter guarantees of a struct field. +statement ok +COPY (SELECT column1 AS "__datafusion_pruning_stats_expr_0", named_struct('a', column2) AS s FROM (VALUES (99, 7), (6, 8))) +TO 'test_files/scratch/parquet_struct_field_pruning/placeholder/f.parquet' +STORED AS PARQUET OPTIONS ('format.bloom_filter_on_write' 'true'); + +statement ok +CREATE EXTERNAL TABLE placeholder STORED AS PARQUET +LOCATION 'test_files/scratch/parquet_struct_field_pruning/placeholder/f.parquet'; + +query I +SELECT count(*) FROM placeholder WHERE "__datafusion_pruning_stats_expr_0" = 99 AND s['a'] > 0; +---- +1 + +query I +SELECT count(*) FROM placeholder WHERE s['a'] > 0 AND "__datafusion_pruning_stats_expr_0" IN (99, 100); +---- +1 From 63c517503a90823c32221752fe84729d0f68aa5d Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:49:33 -0800 Subject: [PATCH 3/6] feat: analyze literal guarantees on expressions LiteralGuarantee::analyze finds guarantees for columns only. Pruning on the statistics of other expressions, such as a struct field, needs the same analysis for those expressions. Add ExprLiteralGuarantee. Its analyze function takes a function that returns a target of type T for each expression that can have a guarantee, and each guarantee keeps its target. The caller decides once whether an expression is usable and what names its statistics. LiteralGuarantee::analyze is this analysis for columns. Its results do not change. Co-Authored-By: Claude Fable 5.2 --- .../physical-expr/src/utils/guarantee.rs | 300 ++++++++++++------ datafusion/physical-expr/src/utils/mod.rs | 2 +- 2 files changed, 212 insertions(+), 90 deletions(-) diff --git a/datafusion/physical-expr/src/utils/guarantee.rs b/datafusion/physical-expr/src/utils/guarantee.rs index 6da8ffbf9017c..6acfd74426bd4 100644 --- a/datafusion/physical-expr/src/utils/guarantee.rs +++ b/datafusion/physical-expr/src/utils/guarantee.rs @@ -77,62 +77,93 @@ pub enum Guarantee { NotIn, } -impl LiteralGuarantee { +/// A [`LiteralGuarantee`] on an expression instead of a column. +/// +/// Create it with [`ExprLiteralGuarantee::analyze`]. The caller of `analyze` +/// decides which expressions can have a guarantee, and gives each one a +/// target of type `T`. +#[derive(Debug, Clone)] +pub struct ExprLiteralGuarantee { + /// The expression that the guarantee is about. + pub expr: Arc, + /// The target that the caller of [`ExprLiteralGuarantee::analyze`] gave + /// to `expr`. + pub target: T, + /// Whether `expr` must, or must not, be one of `literals`. + pub guarantee: Guarantee, + /// The values. + pub literals: HashSet, +} + +impl ExprLiteralGuarantee { /// Create a new instance of the guarantee if the provided operator is - /// supported. Returns None otherwise. See [`LiteralGuarantee::analyze`] to - /// create these structures from an predicate (boolean expression). + /// supported. Returns None otherwise. See [`ExprLiteralGuarantee::analyze`] + /// to create these structures from an predicate (boolean expression). #[allow(clippy::allow_attributes, clippy::mutable_key_type)] // ScalarValue has interior mutability but is intentionally used as hash key fn new<'a>( - column_name: impl Into, + expr: Arc, + target: T, guarantee: Guarantee, literals: impl IntoIterator, ) -> Self { let literals: HashSet<_> = literals.into_iter().cloned().collect(); Self { - column: Column::from_name(column_name), + expr, + target, guarantee, literals, } } - /// Return a list of [`LiteralGuarantee`]s that must be satisfied for `expr` + /// Return a list of [`ExprLiteralGuarantee`]s that must be satisfied for `expr` /// to evaluate to `true`. /// - /// If more than one `LiteralGuarantee` is returned, they must **all** hold + /// If more than one `ExprLiteralGuarantee` is returned, they must **all** hold /// for the expression to possibly be `true`. If any is not satisfied, the /// expression is guaranteed to be `null` or `false`. /// /// # Notes: /// 1. `expr` must be a boolean expression or inlist expression. /// 2. `expr` is not simplified prior to analysis. - pub fn analyze(expr: &Arc) -> Vec { + /// 3. Only the expressions that `resolve` gives a target get a guarantee. + /// The guarantee keeps the target. + pub fn analyze( + expr: &Arc, + resolve: impl Fn(&Arc) -> Option, + ) -> Vec { + let resolve: Resolve = &resolve; // split conjunction: AND AND ... split_conjunction(expr) .into_iter() // for an `AND` conjunction to be true, all terms individually must be true .fold(GuaranteeBuilder::new(), |builder, expr| { - if let Some(cel) = ColOpLit::try_new(expr) { + if let Some(cel) = ColOpLit::try_new(expr, resolve) { builder.aggregate_conjunct(&cel) } else if let Some(inlist) = expr.downcast_ref::() { - if let Some(inlist) = ColInList::try_new(inlist) { + if let Some(inlist) = ColInList::try_new(inlist, resolve) { builder.aggregate_multi_conjunct( inlist.col, + inlist.target, inlist.guarantee, inlist.list.iter().map(|lit| lit.value()), ) - } else if let Some(projected) = project_struct_in_list(inlist) { - projected - .into_iter() - .fold(builder, |builder, (col, values)| { + } else if let Some(projected) = + project_struct_in_list(inlist, resolve) + { + projected.into_iter().fold( + builder, + |builder, (col, target, values)| { builder.aggregate_multi_conjunct( col, + target, Guarantee::In, &values, ) - }) + }, + ) } else { builder } @@ -159,7 +190,7 @@ impl LiteralGuarantee { // than zero. let terms = disjunctions .iter() - .filter_map(|expr| ColOpLit::try_new(expr)) + .filter_map(|expr| ColOpLit::try_new(expr, resolve)) .collect::>(); // if all terms are 'col literal' with the same column @@ -175,12 +206,13 @@ impl LiteralGuarantee { if !terms.is_empty() && terms.len() == disjunctions.len() && terms.iter().all(|term| { - term.col.name() == first_term.unwrap().col.name() + term.col == first_term.unwrap().col && term.guarantee == Guarantee::In }) { builder.aggregate_multi_conjunct( first_term.unwrap().col, + first_term.unwrap().target.clone(), Guarantee::In, terms.iter().map(|term| term.lit.value()), ) @@ -191,12 +223,14 @@ impl LiteralGuarantee { // we can infer a guarantee for the column // e.g. (a = 1 AND b = 2) OR (a = 2 AND b = 3) is `a IN (1, 2) AND b IN (2, 3)` // otherwise, we can't infer a guarantee - let termsets: Vec> = disjunctions + let termsets: Vec>> = disjunctions .iter() .map(|expr| { split_conjunction(expr) .into_iter() - .filter_map(ColOpLitOrInList::try_new) + .filter_map(|expr| { + ColOpLitOrInList::try_new(expr, resolve) + }) .filter(|term| term.guarantee() == Guarantee::In) .collect() }) @@ -215,7 +249,7 @@ impl LiteralGuarantee { // Build guarantees for common columns let mut builder = builder; - for col in common_cols { + for (col, target) in common_cols { let literals: Vec<_> = termsets .iter() .filter_map(|terms| { @@ -230,6 +264,7 @@ impl LiteralGuarantee { builder = builder.aggregate_multi_conjunct( col, + target, Guarantee::In, literals, ); @@ -243,6 +278,39 @@ impl LiteralGuarantee { } } +/// Returns the target of an expression that can have a guarantee. +type Resolve<'a, T> = &'a dyn Fn(&Arc) -> Option; + +impl LiteralGuarantee { + /// Return a list of [`LiteralGuarantee`]s that must be satisfied for `expr` + /// to evaluate to `true`. + /// + /// This is [`ExprLiteralGuarantee::analyze`] for columns. + pub fn analyze(expr: &Arc) -> Vec { + ExprLiteralGuarantee::analyze(expr, |expr| { + expr.is::().then_some(()) + }) + .into_iter() + .filter_map(|guarantee| Self::try_from_expr_guarantee(&guarantee)) + .collect() + } + + /// Returns the column form of `guarantee`, or `None` if it is not about a + /// column. + pub fn try_from_expr_guarantee( + guarantee: &ExprLiteralGuarantee, + ) -> Option { + let column = guarantee + .expr + .downcast_ref::()?; + Some(Self { + column: Column::from_name(column.name()), + guarantee: guarantee.guarantee, + literals: guarantee.literals.clone(), + }) + } +} + impl Display for LiteralGuarantee { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let mut sorted_literals: Vec<_> = @@ -265,23 +333,26 @@ impl Display for LiteralGuarantee { } } -/// Combines conjuncts (aka terms `AND`ed together) into [`LiteralGuarantee`]s, +/// Combines conjuncts (aka terms `AND`ed together) into [`ExprLiteralGuarantee`]s, /// preserving insert order -#[derive(Debug, Default)] -struct GuaranteeBuilder<'a> { +#[derive(Debug)] +struct GuaranteeBuilder<'a, T> { /// List of guarantees that have been created so far /// if we have determined a subsequent conjunct invalidates a guarantee /// e.g. `a = foo AND a = bar` then the relevant guarantee will be None - guarantees: Vec>, + guarantees: Vec>>, - /// Key is the (column name, guarantee type) + /// Key is the (target expression, guarantee type) /// Value is the index into `guarantees` - map: HashMap<(&'a crate::expressions::Column, Guarantee), usize>, + map: HashMap<(&'a Arc, Guarantee), usize>, } -impl<'a> GuaranteeBuilder<'a> { +impl<'a, T: Clone> GuaranteeBuilder<'a, T> { fn new() -> Self { - Default::default() + Self { + guarantees: vec![], + map: HashMap::new(), + } } /// Aggregate a new single `AND col literal` term to this builder @@ -290,9 +361,10 @@ impl<'a> GuaranteeBuilder<'a> { /// # Examples /// * `AND (a = 1)`: `a` is guaranteed to be 1 /// * `AND (a != 1)`: a is guaranteed to not be 1 - fn aggregate_conjunct(self, col_op_lit: &ColOpLit<'a>) -> Self { + fn aggregate_conjunct(self, col_op_lit: &ColOpLit<'a, T>) -> Self { self.aggregate_multi_conjunct( col_op_lit.col, + col_op_lit.target.clone(), col_op_lit.guarantee, [col_op_lit.lit.value()], ) @@ -310,7 +382,8 @@ impl<'a> GuaranteeBuilder<'a> { #[allow(clippy::allow_attributes, clippy::mutable_key_type)] // ScalarValue has interior mutability but is intentionally used as hash key fn aggregate_multi_conjunct<'b>( mut self, - col: &'a crate::expressions::Column, + col: &'a Arc, + target: T, guarantee: Guarantee, new_values: impl IntoIterator, ) -> Self { @@ -359,7 +432,8 @@ impl<'a> GuaranteeBuilder<'a> { // This is a new guarantee let new_values: HashSet<_> = new_values.into_iter().collect(); - let guarantee = LiteralGuarantee::new(col.name(), guarantee, new_values); + let guarantee = + ExprLiteralGuarantee::new(Arc::clone(col), target, guarantee, new_values); // add it to the list of guarantees self.guarantees.push(Some(guarantee)); self.map.insert(key, self.guarantees.len() - 1); @@ -369,16 +443,20 @@ impl<'a> GuaranteeBuilder<'a> { } /// Return all guarantees that have been created so far - fn build(self) -> Vec { + fn build(self) -> Vec> { // filter out any guarantees that have been invalidated self.guarantees.into_iter().flatten().collect() } } +/// An expression, its target and the values that it must be one of. +type ProjectedInList<'a, T> = (&'a Arc, T, Vec); + /// Project necessary per-column guarantees; the original predicate retains tuple correlation. -fn project_struct_in_list( - inlist: &crate::expressions::InListExpr, -) -> Option)>> { +fn project_struct_in_list<'a, T>( + inlist: &'a crate::expressions::InListExpr, + resolve: Resolve, +) -> Option>> { if inlist.negated() || inlist.is_empty() { return None; } @@ -415,10 +493,8 @@ fn project_struct_in_list( let mut projected = Vec::new(); for (accessor_args, source_index) in mapping.fields { - let column = expr - .args() - .get(source_index)? - .downcast_ref::()?; + let column = expr.args().get(source_index)?; + let target = resolve(column)?; let mut args: Vec> = vec![Arc::new(crate::expressions::Column::new("tuple", 0))]; args.extend(accessor_args.into_iter().map(crate::expressions::lit)); @@ -448,27 +524,28 @@ fn project_struct_in_list( values.push(value); } if !values.is_empty() { - projected.push((column, values)); + projected.push((column, target, values)); } } Some(projected) } /// Represents a single `col [not]in literal` expression -struct ColOpLit<'a> { - col: &'a crate::expressions::Column, +struct ColOpLit<'a, T> { + col: &'a Arc, + target: T, guarantee: Guarantee, lit: &'a crate::expressions::Literal, } -impl<'a> ColOpLit<'a> { +impl<'a, T> ColOpLit<'a, T> { /// Returns Some(ColOpLit) if the expression is either: /// 1. `col literal` /// 2. `literal col` /// 3. operator is `=` or `!=` /// /// Returns None otherwise - fn try_new(expr: &'a Arc) -> Option { + fn try_new(expr: &'a Arc, resolve: Resolve) -> Option { let binary_expr = expr.downcast_ref::()?; let (left, op, right) = @@ -478,48 +555,41 @@ impl<'a> ColOpLit<'a> { Operator::NotEq => Guarantee::NotIn, _ => return None, }; - // col literal - if let (Some(col), Some(lit)) = ( - left.downcast_ref::(), - right.downcast_ref::(), - ) { - Some(Self { - col, - guarantee, - lit, - }) - } - // literal col - else if let (Some(lit), Some(col)) = ( - left.downcast_ref::(), - right.downcast_ref::(), - ) { - Some(Self { - col, - guarantee, - lit, - }) - } else { - None - } + let (col, lit) = match right.downcast_ref::() { + // col literal + Some(lit) => (left, lit), + // literal col + None => (right, left.downcast_ref::()?), + }; + Some(Self { + col, + target: resolve(col)?, + guarantee, + lit, + }) } } /// Represents a single `col [not]in literal` expression -struct ColInList<'a> { - col: &'a crate::expressions::Column, +struct ColInList<'a, T> { + col: &'a Arc, + target: T, guarantee: Guarantee, list: Vec<&'a crate::expressions::Literal>, } -impl<'a> ColInList<'a> { +impl<'a, T> ColInList<'a, T> { /// Returns Some(ColInList) if the expression is either: /// 1. `col (literal1, literal2, ...)` /// 3. operator is `in` or `not in` /// /// Returns None otherwise - fn try_new(inlist: &'a crate::expressions::InListExpr) -> Option { - let col = inlist.expr().downcast_ref::()?; + fn try_new( + inlist: &'a crate::expressions::InListExpr, + resolve: Resolve, + ) -> Option { + let col = inlist.expr(); + let target = resolve(col)?; let literals = inlist .list() @@ -535,6 +605,7 @@ impl<'a> ColInList<'a> { Some(Self { col, + target, guarantee, list: literals, }) @@ -542,16 +613,16 @@ impl<'a> ColInList<'a> { } /// Represents a single `col [not]in literal` expression or a single `col literal` expression -enum ColOpLitOrInList<'a> { - ColOpLit(ColOpLit<'a>), - ColInList(ColInList<'a>), +enum ColOpLitOrInList<'a, T> { + ColOpLit(ColOpLit<'a, T>), + ColInList(ColInList<'a, T>), } -impl<'a> ColOpLitOrInList<'a> { - fn try_new(expr: &'a Arc) -> Option { +impl<'a, T> ColOpLitOrInList<'a, T> { + fn try_new(expr: &'a Arc, resolve: Resolve) -> Option { match expr.downcast_ref::() { - Some(inlist) => Some(Self::ColInList(ColInList::try_new(inlist)?)), - None => ColOpLit::try_new(expr).map(Self::ColOpLit), + Some(inlist) => Some(Self::ColInList(ColInList::try_new(inlist, resolve)?)), + None => ColOpLit::try_new(expr, resolve).map(Self::ColOpLit), } } @@ -562,13 +633,20 @@ impl<'a> ColOpLitOrInList<'a> { } } - fn col(&self) -> &'a crate::expressions::Column { + fn col(&self) -> &'a Arc { match self { Self::ColOpLit(col_op_lit) => col_op_lit.col, Self::ColInList(col_in_list) => col_in_list.col, } } + fn target(&self) -> &T { + match self { + Self::ColOpLit(col_op_lit) => &col_op_lit.target, + Self::ColInList(col_in_list) => &col_in_list.target, + } + } + fn lits(&self) -> Vec<&'a crate::expressions::Literal> { match self { Self::ColOpLit(col_op_lit) => vec![col_op_lit.lit], @@ -577,10 +655,10 @@ impl<'a> ColOpLitOrInList<'a> { } } -/// Find columns that appear in all termsets -fn find_common_columns<'a>( - termsets: &[Vec>], -) -> Vec<&'a crate::expressions::Column> { +/// Find columns that appear in all termsets, and their targets +fn find_common_columns<'a, T: Clone>( + termsets: &[Vec>], +) -> Vec<(&'a Arc, T)> { if termsets.is_empty() { return Vec::new(); } @@ -596,7 +674,7 @@ fn find_common_columns<'a>( } // Intersect with columns from remaining termsets - let mut termset_cols: HashSet<&crate::expressions::Column> = HashSet::new(); + let mut termset_cols: HashSet<&Arc> = HashSet::new(); for termset in termsets.iter().skip(1) { termset_cols.clear(); termset_cols.extend(termset.iter().map(|term| term.col())); @@ -606,7 +684,11 @@ fn find_common_columns<'a>( common_cols.retain(|col| termset_cols.contains(col)); } - common_cols.into_iter().collect() + termsets[0] + .iter() + .filter(|term| common_cols.contains(term.col())) + .map(|term| (term.col(), term.target().clone())) + .collect() } #[cfg(test)] @@ -628,6 +710,38 @@ mod test { test_analyze(lit(true), vec![]) } + #[test] + fn test_expr_target() { + let schema = schema(); + // `-b` is the target, and `b` is not + let analyze = |expr: Expr| { + let expr = logical2physical(&expr, &schema); + ExprLiteralGuarantee::analyze(&expr, |expr| { + expr.is::().then_some(()) + }) + .into_iter() + .map(|g| { + let mut literals = + g.literals.iter().map(|l| l.to_string()).collect::>(); + literals.sort(); + format!("{} {:?} {}", g.expr, g.guarantee, literals.join(",")) + }) + .collect::>() + }; + let neg = || Expr::Negative(Box::new(col("b"))); + + assert_eq!(analyze(neg().eq(lit(1))), ["(- b@1) In 1"]); + assert_eq!( + analyze(lit(1).eq(neg()).or(neg().eq(lit(2)))), + ["(- b@1) In 1,2"] + ); + assert_eq!( + analyze(neg().in_list(vec![lit(1), lit(2)], true)), + ["(- b@1) NotIn 1,2"] + ); + assert!(analyze(col("b").eq(lit(1))).is_empty()); + } + #[test] fn test_single() { // a = "foo" @@ -1275,7 +1389,11 @@ mod test { S: Into + 'a, { let literals: Vec<_> = literals.into_iter().map(|s| s.into()).collect(); - LiteralGuarantee::new(column, Guarantee::In, literals.iter()) + LiteralGuarantee { + column: Column::from_name(column), + guarantee: Guarantee::In, + literals: literals.into_iter().collect(), + } } /// Guarantee that the expression is true if the column is NOT any of the specified values @@ -1285,7 +1403,11 @@ mod test { S: Into + 'a, { let literals: Vec<_> = literals.into_iter().map(|s| s.into()).collect(); - LiteralGuarantee::new(column, Guarantee::NotIn, literals.iter()) + LiteralGuarantee { + column: Column::from_name(column), + guarantee: Guarantee::NotIn, + literals: literals.into_iter().collect(), + } } // Schema for testing diff --git a/datafusion/physical-expr/src/utils/mod.rs b/datafusion/physical-expr/src/utils/mod.rs index d322fc98c9022..b4324f97d6dbf 100644 --- a/datafusion/physical-expr/src/utils/mod.rs +++ b/datafusion/physical-expr/src/utils/mod.rs @@ -3,7 +3,7 @@ // SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements mod guarantee; -pub use guarantee::{Guarantee, LiteralGuarantee}; +pub use guarantee::{ExprLiteralGuarantee, Guarantee, LiteralGuarantee}; use std::borrow::Borrow; use std::sync::Arc; From 895b5cc386c926ab5756f82758f53c0e69fe15af Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:51:09 -0800 Subject: [PATCH 4/6] feat: let PruningPredicate read statistics by typed target A PruningPredicate can read the statistics of columns only, and it names them by column name. A statistics source that has statistics for other expressions, such as the leaf column of a struct field, cannot say so. Add StatisticsResolver. Its resolve method returns a target for each expression that has statistics, or None. The predicate stores the target and passes it back to the statistics source when it prunes, so the check "can the predicate use this expression" and the answer "which statistics does it read" are one call. | Item | Change | |-------------------------|---------------------------------------------| | PruningPredicate | Gets a target type parameter, default Column | | RequiredColumns | Same | | PruningPredicateBuilder | Gets with_resolver, default ColumnResolver | | PruningStatisticsSource | New trait: PruningStatistics for a target | Every PruningStatistics implements PruningStatisticsSource, so existing code compiles without changes. The predicates that the default resolver builds do not change. Co-Authored-By: Claude Fable 5.2 --- .../datasource-parquet/src/page_filter.rs | 18 +- datafusion/pruning/src/lib.rs | 4 + datafusion/pruning/src/pruning_predicate.rs | 811 +++++++++++------- datafusion/pruning/src/statistics_source.rs | 500 +++++++++++ .../library-user-guide/upgrading/index.md | 33 + 5 files changed, 1062 insertions(+), 304 deletions(-) create mode 100644 datafusion/pruning/src/statistics_source.rs diff --git a/datafusion/datasource-parquet/src/page_filter.rs b/datafusion/datasource-parquet/src/page_filter.rs index ef998b0e0beed..c49a8b9c0f6e0 100644 --- a/datafusion/datasource-parquet/src/page_filter.rs +++ b/datafusion/datasource-parquet/src/page_filter.rs @@ -18,7 +18,6 @@ use arrow::{ }; use datafusion_common::ScalarValue; use datafusion_common::pruning::PruningStatistics; -use datafusion_physical_expr::expressions::Column; use datafusion_physical_expr::{PhysicalExpr, split_conjunction}; use datafusion_pruning::{MAX_IN_LIST_SIZE, PruningPredicate, PruningPredicateBuilder}; @@ -479,7 +478,7 @@ impl PagePruningAccessPlanFilter { self.predicates .iter() .filter_map(single_column) - .map(|c| c.name()) + .map(|c| c.name.as_str()) } } @@ -488,8 +487,8 @@ impl PagePruningAccessPlanFilter { /// /// The pages of each column have their own row boundaries. So page pruning can /// evaluate a predicate only on the pages of one column. -fn single_column(predicate: &PruningPredicate) -> Option<&Column> { - let mut columns = predicate.required_columns().columns(); +fn single_column(predicate: &PruningPredicate) -> Option<&datafusion_common::Column> { + let mut columns = predicate.required_columns().targets(); let first = columns.next()?; columns.all(|c| c == first).then_some(first) } @@ -619,12 +618,12 @@ fn prune_pages_for_predicate( let column = single_column(predicate)?; let converter = - match StatisticsConverter::try_new(column.name(), arrow_schema, parquet_schema) { + match StatisticsConverter::try_new(&column.name, arrow_schema, parquet_schema) { Ok(converter) => converter, Err(e) => { debug!( "Could not create statistics converter for column {}: {e}", - column.name() + column.name ); return None; } @@ -874,7 +873,7 @@ mod tests { use arrow::record_batch::RecordBatch; use bytes::Bytes; use datafusion_expr::Operator; - use datafusion_physical_expr::expressions::{BinaryExpr, lit}; + use datafusion_physical_expr::expressions::{BinaryExpr, Column, lit}; use datafusion_physical_plan::metrics::ExecutionPlanMetricsSet; use parquet::arrow::ArrowWriter; use parquet::arrow::arrow_reader::{ @@ -911,7 +910,10 @@ mod tests { .with_file_schema(Arc::clone(&schema)) .try_build(one) .unwrap(); - assert_eq!(single_column(&pp), Some(&Column::new("a", 0))); + assert_eq!( + single_column(&pp), + Some(&datafusion_common::Column::from_name("a")) + ); let two: Arc = Arc::new(BinaryExpr::new( cmp("a", 0, Operator::Gt), diff --git a/datafusion/pruning/src/lib.rs b/datafusion/pruning/src/lib.rs index 40be3376c86c8..1fbf047d6d413 100644 --- a/datafusion/pruning/src/lib.rs +++ b/datafusion/pruning/src/lib.rs @@ -9,6 +9,7 @@ mod in_list; mod key_range_bitmap_expr; mod primitive_in_list; mod pruning_predicate; +mod statistics_source; mod string_in_list; pub use file_pruner::FilePruner; @@ -16,3 +17,6 @@ pub use pruning_predicate::{ MAX_IN_LIST_SIZE, PredicateRewriter, PruningPredicate, PruningPredicateBuilder, PruningStatistics, RequiredColumns, UnhandledPredicateHook, build_pruning_predicate, }; +pub use statistics_source::{ + ColumnResolver, PruningStatisticsSource, StatisticsResolver, +}; diff --git a/datafusion/pruning/src/pruning_predicate.rs b/datafusion/pruning/src/pruning_predicate.rs index 4d1bcea1c396e..e2be9b6ec0f1d 100644 --- a/datafusion/pruning/src/pruning_predicate.rs +++ b/datafusion/pruning/src/pruning_predicate.rs @@ -7,7 +7,7 @@ //! //! [`Expr`]: https://docs.rs/datafusion/latest/datafusion/logical_expr/enum.Expr.html use std::collections::HashSet; -use std::sync::Arc; +use std::sync::{Arc, OnceLock}; use crate::in_list::{SetMembership, unwrap_scalar}; use crate::key_range_bitmap_expr::KeyRangeBitmapPruningExpr; @@ -26,16 +26,19 @@ use datafusion_physical_expr::simplifier::PhysicalExprSimplifier; use datafusion_physical_plan::metrics::Count; use log::{debug, trace}; +use crate::{ColumnResolver, PruningStatisticsSource, StatisticsResolver}; use datafusion_common::error::Result; use datafusion_common::tree_node::{TransformedResult, TreeNodeRecursion}; -use datafusion_common::{_internal_datafusion_err, Column, assert_eq_or_internal_err}; +use datafusion_common::{_internal_datafusion_err, assert_eq_or_internal_err}; use datafusion_common::{ - ScalarValue, internal_datafusion_err, plan_datafusion_err, plan_err, + Column, ScalarValue, internal_datafusion_err, plan_datafusion_err, plan_err, tree_node::{Transformed, TreeNode}, }; use datafusion_expr_common::casts::try_cast_literal_to_type; use datafusion_expr_common::operator::Operator; -use datafusion_physical_expr::utils::{Guarantee, LiteralGuarantee}; +use datafusion_physical_expr::utils::{ + ExprLiteralGuarantee, Guarantee, LiteralGuarantee, +}; use datafusion_physical_expr::{PhysicalExprRef, expressions as phys_expr}; use datafusion_physical_expr_common::physical_expr::snapshot_physical_expr_opt; use datafusion_physical_plan::joins::HashTableLookupExpr; @@ -352,15 +355,23 @@ use datafusion_physical_plan::{ColumnarValue, PhysicalExpr}; /// [small materialized aggregates]: https://www.vldb.org/conf/1998/p476.pdf /// [zone maps]: https://dl.acm.org/doi/10.1007/978-3-642-03730-6_10 /// [data skipping]: https://dl.acm.org/doi/10.1145/2588555.2610515 +/// +/// # Targets +/// +/// `T` names the statistics of one expression of the predicate. The default +/// is [`Column`]: the predicate reads the statistics of columns from a +/// [`PruningStatistics`]. To read the statistics of other expressions, give +/// the builder a [`StatisticsResolver`], see +/// [`PruningPredicateBuilder::with_resolver`]. #[derive(Debug, Clone)] -pub struct PruningPredicate { +pub struct PruningPredicate { /// The input schema against which the predicate will be evaluated schema: SchemaRef, /// A min/max pruning predicate (rewritten in terms of column min/max /// values, which are supplied by statistics) predicate_expr: Arc, /// Description of which statistics are required to evaluate `predicate_expr` - required_columns: RequiredColumns, + required_columns: RequiredColumns, /// Original physical predicate from which this predicate expr is derived /// (required for serialization) orig_expr: Arc, @@ -368,7 +379,11 @@ pub struct PruningPredicate { /// evaluate to `true`. /// /// See [`PruningPredicate::literal_guarantees`] for more details. - literal_guarantees: Vec, + target_literal_guarantees: Vec>, + /// The column form of `target_literal_guarantees`, for + /// [`PruningPredicate::literal_guarantees`]. Built on first use, so that a + /// predicate built for each file does not copy the literals. + literal_guarantees: OnceLock>, /// Maximum IN-list size used to build this predicate. max_in_list_size: usize, /// Whether its logical inverse can safely prove every row matches. @@ -411,20 +426,52 @@ pub fn build_pruning_predicate( /// - [`Self::try_build`]: returns a raw `Result` for /// callers that want to surface errors themselves. /// -#[derive(Default)] -pub struct PruningPredicateBuilder<'a> { +pub struct PruningPredicateBuilder<'a, R = ColumnResolver> { file_schema: Option, error_counter: Option<&'a Count>, max_in_list_size: usize, + resolver: R, +} + +impl Default for PruningPredicateBuilder<'_> { + fn default() -> Self { + Self::new() + } } -impl<'a> PruningPredicateBuilder<'a> { +impl PruningPredicateBuilder<'_> { /// Create a new builder with the default pruning predicate configuration. pub fn new() -> Self { Self { file_schema: None, error_counter: None, max_in_list_size: MAX_IN_LIST_SIZE, + resolver: ColumnResolver, + } + } +} + +impl<'a, R: StatisticsResolver> PruningPredicateBuilder<'a, R> { + /// Read the statistics of the expressions that `resolver` resolves, + /// instead of the statistics of columns. + /// + /// A statistics source can know the statistics of expressions other than + /// columns. For example, Parquet stores statistics for each field of a + /// struct column, so it knows the bounds of `get_field(s, 'a')`. + /// + /// The predicate stores the target that `resolver` returns for an + /// expression. [`PruningPredicate::prune`] then takes a + /// [`PruningStatisticsSource`] for that target type, and passes the target + /// to it. See [`StatisticsResolver`] for the rules. + pub fn with_resolver( + self, + resolver: R2, + ) -> PruningPredicateBuilder<'a, R2> { + PruningPredicateBuilder { + file_schema: self.file_schema, + error_counter: self.error_counter, + max_in_list_size: self.max_in_list_size, + resolver, } } @@ -481,7 +528,7 @@ impl<'a> PruningPredicateBuilder<'a> { pub fn build( self, predicate: Arc, - ) -> Option> { + ) -> Option>> { let error_counter = self.error_counter; match self.try_build(predicate) { Ok(pruning_predicate) => { @@ -505,7 +552,7 @@ impl<'a> PruningPredicateBuilder<'a> { pub fn try_build( self, mut predicate: Arc, - ) -> Result { + ) -> Result> { let file_schema = self.file_schema.ok_or_else(|| { _internal_datafusion_err!( "PruningPredicateBuilder requires a file schema (call `with_file_schema`)" @@ -537,6 +584,7 @@ impl<'a> PruningPredicateBuilder<'a> { schema: &file_schema, unhandled_hook: &unhandled_hook, max_in_list_size: self.max_in_list_size, + resolver: &self.resolver, }; let predicate_expr = build_predicate_expression( &predicate, @@ -548,14 +596,16 @@ impl<'a> PruningPredicateBuilder<'a> { // Simplify the newly created predicate to get rid of redundant casts, comparisons, etc. let predicate_expr = PhysicalExprSimplifier::new(&predicate_schema).simplify(predicate_expr)?; - let literal_guarantees = LiteralGuarantee::analyze(&predicate); + let target_literal_guarantees = + ExprLiteralGuarantee::analyze(&predicate, |expr| ctx.resolve(expr)); Ok(PruningPredicate { schema: file_schema, predicate_expr, required_columns, orig_expr: predicate, - literal_guarantees, + target_literal_guarantees, + literal_guarantees: OnceLock::new(), max_in_list_size: self.max_in_list_size, can_be_inverted_for_full_match: !properties.has_filter_semantics_only, }) @@ -563,7 +613,8 @@ impl<'a> PruningPredicateBuilder<'a> { /// Builds the predicate that proves that every row of a container passes /// `predicate`. If the result prunes a container, every row of the - /// container passes `predicate`. + /// container passes `predicate`. The result reads statistics through the + /// resolver of this builder. /// /// Returns `Ok(None)` if no inverse can prove a full match, see /// [`PruningPredicate::can_be_inverted_for_full_match`]. @@ -576,18 +627,19 @@ impl<'a> PruningPredicateBuilder<'a> { /// rewrite(NOT predicate) OR x_null_count > 0 OR y_null_count > 0 ... /// \___________________/ \________________________________/ /// a row can be FALSE a row can be NULL: one term for each - /// nullable column `x`, `y` that + /// nullable input `x`, `y` that /// `rewrite(NOT predicate)` reads /// ``` /// - /// A column that the rewrite does not read needs no term. The rewrite + /// An input is a column, or another expression that the resolver resolves. + /// An input that the rewrite does not read needs no term. The rewrite /// replaces a comparison that it cannot use with `true`. So it prunes a /// container only if the comparisons that it reads are FALSE on their own, /// and `FALSE AND x` is FALSE for every `x`, also for NULL. pub fn try_build_inverse( self, predicate: Arc, - ) -> Result> { + ) -> Result>> { let file_schema = self.file_schema.clone().ok_or_else(|| { _internal_datafusion_err!( "PruningPredicateBuilder requires a file schema (call `with_file_schema`)" @@ -672,7 +724,9 @@ impl PruningPredicate { .with_file_schema(schema) .try_build(expr) } +} +impl PruningPredicate { /// For each set of statistics, evaluates the pruning predicate /// and returns a `bool` with the following meaning for a /// all rows whose values match the statistics: @@ -687,21 +741,25 @@ impl PruningPredicate { /// simplified version `b`. See [`ExprSimplifier`] to simplify expressions. /// /// [`ExprSimplifier`]: https://docs.rs/datafusion/latest/datafusion/optimizer/simplify_expressions/struct.ExprSimplifier.html - pub fn prune( + pub fn prune + ?Sized>( &self, statistics: &S, - ) -> Result> { + ) -> Result> + where + T: std::fmt::Debug, + { let mut builder = BoolVecBuilder::new(statistics.num_containers()); // Try to prove the predicate can't be true for the containers based on // literal guarantees - for literal_guarantee in &self.literal_guarantees { - let LiteralGuarantee { - column, - guarantee, - literals, - } = literal_guarantee; - if let Some(results) = statistics.contained(column, literals) { + for ExprLiteralGuarantee { + target, + guarantee, + literals, + .. + } in &self.target_literal_guarantees + { + if let Some(results) = statistics.contained(target, literals) { match guarantee { // `In` means the values in the column must be one of the // values in the set for the predicate to evaluate to true. @@ -760,7 +818,21 @@ impl PruningPredicate { /// expression to possibly be `true`. If any is not satisfied, the /// expression is guaranteed to be `null` or `false`. pub fn literal_guarantees(&self) -> &[LiteralGuarantee] { - &self.literal_guarantees + self.literal_guarantees.get_or_init(|| { + self.target_literal_guarantees + .iter() + .filter_map(LiteralGuarantee::try_from_expr_guarantee) + .collect() + }) + } + + /// Returns the literal guarantees that [`Self::prune`] checks with + /// [`PruningStatisticsSource::contained`]. Each guarantee holds the + /// target that `prune` passes to `contained`. + /// + /// [`Self::literal_guarantees`] is the column form of these guarantees. + pub fn target_literal_guarantees(&self) -> &[ExprLiteralGuarantee] { + &self.target_literal_guarantees } /// Returns true if this pruning predicate can not prune anything. @@ -770,7 +842,7 @@ impl PruningPredicate { /// /// This can happen when a predicate is simplified to a constant `true` pub fn always_true(&self) -> bool { - is_always_true(&self.predicate_expr) && self.literal_guarantees.is_empty() + is_always_true(&self.predicate_expr) && self.target_literal_guarantees.is_empty() } /// Returns the configured maximum IN-list size used to build this predicate. @@ -785,24 +857,34 @@ impl PruningPredicate { } /// Changes this predicate to keep every container that can hold a NULL in - /// a column that the predicate reads. - fn keep_containers_with_nulls(&mut self) -> Result<()> { - let mut columns: Vec = vec![]; - for (column, _, _) in self.required_columns.iter() { - if !columns.contains(column) { - columns.push(column.clone()); + /// a column, or another expression, that the predicate reads. + fn keep_containers_with_nulls(&mut self) -> Result<()> + where + T: Clone, + { + let mut inputs: Vec<(Arc, T)> = vec![]; + for statistic in self.required_columns.iter() { + if !inputs.iter().any(|(expr, _)| expr == &statistic.expr) { + inputs.push((Arc::clone(&statistic.expr), statistic.target.clone())); } } - for column in columns { - let field = self.schema.field_with_name(column.name())?; - if !field.is_nullable() { + for (expr, target) in inputs { + let (name, nullable) = match expr.downcast_ref::() { + Some(column) => { + let field = self.schema.field_with_name(column.name())?; + (field.name().clone(), field.is_nullable()) + } + // For example, a struct field can be NULL when its struct + // column is not nullable. + None => (expr.to_string(), true), + }; + if !nullable { continue; } - let null_count_field = Field::new(field.name(), DataType::UInt64, true); - let column_expr = Arc::new(column.clone()) as _; + let null_count_field = Field::new(name, DataType::UInt64, true); let null_count = self.required_columns.null_count_column_expr( - &column, - &column_expr, + (&expr, &target), + &expr, &null_count_field, )?; // A missing null count makes this term NULL, which keeps the @@ -820,11 +902,12 @@ impl PruningPredicate { } // A literal guarantee prunes a container on its own, before the // null count terms can keep it. - self.literal_guarantees.clear(); + self.target_literal_guarantees.clear(); + self.literal_guarantees = OnceLock::new(); Ok(()) } - pub fn required_columns(&self) -> &RequiredColumns { + pub fn required_columns(&self) -> &RequiredColumns { &self.required_columns } @@ -836,10 +919,11 @@ impl PruningPredicate { /// used in the predicate. For example, it can be used to avoid reading /// unneeded bloom filters (a non trivial operation). pub fn literal_columns(&self) -> Vec { - let mut seen = HashSet::with_capacity(self.literal_guarantees.len()); - self.literal_guarantees + let mut seen = HashSet::with_capacity(self.target_literal_guarantees.len()); + self.target_literal_guarantees .iter() - .map(|e| &e.column.name) + .filter_map(|e| e.expr.downcast_ref::()) + .map(|column| column.name()) // avoid duplicates .filter(|name| seen.insert(*name)) .map(|s| s.to_string()) @@ -926,7 +1010,7 @@ fn is_always_false(expr: &Arc) -> bool { .is_some_and(|l| *l.value() == ScalarValue::Boolean(Some(false))) } -/// Describes which columns statistics are necessary to evaluate a +/// Describes which statistics are necessary to evaluate a /// [`PruningPredicate`]. /// /// This structure permits reading and creating the minimum number statistics, @@ -935,27 +1019,40 @@ fn is_always_false(expr: &Arc) -> bool { /// /// Handles creating references to the min/max statistics /// for columns as well as recording which statistics are needed -#[derive(Debug, Default, Clone)] -pub struct RequiredColumns { - /// The statistics required to evaluate this predicate: - /// * The unqualified column in the input schema - /// * Statistics type (e.g. Min or Max or Null_Count) - /// * The field the statistics value should be placed in for - /// pruning predicate evaluation (e.g. `min_value` or `max_value`) - columns: Vec<(phys_expr::Column, StatisticsType, Field)>, +/// +/// `T` is the target type of the [`PruningPredicate`]. +#[derive(Debug, Clone)] +pub struct RequiredColumns { + /// The statistics required to evaluate this predicate, in the order of the + /// columns of the statistics batch. + columns: Vec>, } -impl RequiredColumns { - fn new() -> Self { - Self::default() +impl Default for RequiredColumns { + fn default() -> Self { + Self::new() } +} - /// Returns the column of each statistic that the predicate requires, in order. - /// - /// A column appears once for each of its statistics. For example, if the - /// predicate requires the min and the max of `a`, `a` appears twice. - pub fn columns(&self) -> impl Iterator { - self.columns.iter().map(|(column, _, _)| column) +/// One statistic that a [`PruningPredicate`] reads from the statistics source. +#[derive(Debug, Clone)] +pub(crate) struct RequiredStatistic { + /// Names the statistic for the statistics source. + pub(crate) target: T, + /// The expression that the statistic describes: a column in the input + /// schema, or another expression that the source has statistics for. + /// The rewrite finds the statistic of an expression with it. + pub(crate) expr: Arc, + /// Statistics type (e.g. Min or Max or Null_Count) + pub(crate) statistics_type: StatisticsType, + /// The field the statistics value should be placed in for + /// pruning predicate evaluation (e.g. `min_value` or `max_value`) + pub(crate) field: Field, +} + +impl RequiredColumns { + fn new() -> Self { + Self { columns: vec![] } } /// Returns Some(column) if this is a single column predicate. @@ -968,19 +1065,29 @@ impl RequiredColumns { /// * `true` returns None #[deprecated( since = "57.0.0", - note = "use `RequiredColumns::columns` and compare the columns instead" + note = "use `RequiredColumns::targets` and compare the targets instead" )] pub fn single_column(&self) -> Option<&phys_expr::Column> { - if self.columns.windows(2).all(|w| { - // check if all columns are the same (ignoring statistics and field) - let c1 = &w[0].0; - let c2 = &w[1].0; - c1 == c2 - }) { - self.columns.first().map(|r| &r.0) - } else { - None - } + let (first, rest) = self.columns.split_first()?; + rest.iter() + .all(|statistic| statistic.expr.eq(&first.expr)) + .then(|| first.expr.downcast_ref::()) + .flatten() + } + + /// Returns the expression that each required statistic describes: a + /// column, or another expression that the source has statistics for. + /// + /// An expression appears once for each of its statistics. + pub fn exprs(&self) -> impl Iterator> { + self.columns.iter().map(|statistic| &statistic.expr) + } + + /// Returns the target of each required statistic. + /// + /// A target appears once for each of its statistics. + pub fn targets(&self) -> impl Iterator { + self.columns.iter().map(|statistic| &statistic.target) } /// Returns a schema that describes the columns required to evaluate this @@ -993,43 +1100,31 @@ impl RequiredColumns { let fields = self .columns .iter() - .map(|(_c, _t, f)| f.clone()) + .map(|statistic| statistic.field.clone()) .collect::>(); Schema::new(fields) } /// Returns an iterator over items in columns (see doc on /// `self.columns` for details) - pub(crate) fn iter( - &self, - ) -> impl Iterator { + pub(crate) fn iter(&self) -> impl Iterator> { self.columns.iter() } fn find_stat_column( &self, - column: &phys_expr::Column, + stats_expr: &Arc, statistics_type: StatisticsType, ) -> Option { - match statistics_type { - StatisticsType::RowCount => { + self.columns.iter().position(|statistic| { + statistic.statistics_type == statistics_type // Use the first row count we find, if any - self.columns - .iter() - .enumerate() - .find(|(_i, (_c, t, _f))| t == &statistics_type) - .map(|(i, (_c, _t, _f))| i) - } - _ => self - .columns - .iter() - .enumerate() - .find(|(_i, (c, t, _f))| c == column && t == &statistics_type) - .map(|(i, (_c, _t, _f))| i), - } + && (statistics_type == StatisticsType::RowCount + || &statistic.expr == stats_expr) + }) } - /// Rewrites column_expr so that all appearances of column + /// Rewrites column_expr so that all appearances of `stats_expr` /// are replaced with a reference to either the min or max /// statistics column, while keeping track that a reference to the statistics /// column is required @@ -1039,17 +1134,23 @@ impl RequiredColumns { /// 5` with the appropriate entry noted in self.columns fn stat_column_expr( &mut self, - column: &phys_expr::Column, + (stats_expr, target): StatisticsExpr<'_, T>, column_expr: &Arc, field: &Field, stat_type: StatisticsType, - ) -> Result> { - let (idx, need_to_insert) = match self.find_stat_column(column, stat_type) { + ) -> Result> + where + T: Clone, + { + let (idx, need_to_insert) = match self.find_stat_column(stats_expr, stat_type) { Some(idx) => (idx, false), None => (self.columns.len(), true), }; - let column_name = column.name(); + let column_name = match stats_expr.downcast_ref::() { + Some(column) => column.name().to_string(), + None => stats_expr.to_string(), + }; let stat_column_name = match stat_type { StatisticsType::Min => format!("{column_name}_min"), StatisticsType::Max => format!("{column_name}_max"), @@ -1065,54 +1166,83 @@ impl RequiredColumns { let nullable = true; let stat_field = Field::new(stat_column.name(), field.data_type().clone(), nullable); - self.columns.push((column.clone(), stat_type, stat_field)); + self.columns.push(RequiredStatistic { + target: target.clone(), + expr: Arc::clone(stats_expr), + statistics_type: stat_type, + field: stat_field, + }); } - rewrite_column_expr(Arc::clone(column_expr), column, &stat_column) + rewrite_column_expr(Arc::clone(column_expr), stats_expr, &stat_column) } /// rewrite col --> col_min fn min_column_expr( &mut self, - column: &phys_expr::Column, + stats_expr: StatisticsExpr<'_, T>, column_expr: &Arc, field: &Field, - ) -> Result> { - self.stat_column_expr(column, column_expr, field, StatisticsType::Min) + ) -> Result> + where + T: Clone, + { + self.stat_column_expr(stats_expr, column_expr, field, StatisticsType::Min) } /// rewrite col --> col_max fn max_column_expr( &mut self, - column: &phys_expr::Column, + stats_expr: StatisticsExpr<'_, T>, column_expr: &Arc, field: &Field, - ) -> Result> { - self.stat_column_expr(column, column_expr, field, StatisticsType::Max) + ) -> Result> + where + T: Clone, + { + self.stat_column_expr(stats_expr, column_expr, field, StatisticsType::Max) } /// rewrite col --> col_null_count fn null_count_column_expr( &mut self, - column: &phys_expr::Column, + stats_expr: StatisticsExpr<'_, T>, column_expr: &Arc, field: &Field, - ) -> Result> { - self.stat_column_expr(column, column_expr, field, StatisticsType::NullCount) + ) -> Result> + where + T: Clone, + { + self.stat_column_expr(stats_expr, column_expr, field, StatisticsType::NullCount) } /// rewrite col --> col_row_count fn row_count_column_expr( &mut self, - column: &phys_expr::Column, + stats_expr: StatisticsExpr<'_, T>, column_expr: &Arc, field: &Field, - ) -> Result> { - self.stat_column_expr(column, column_expr, field, StatisticsType::RowCount) + ) -> Result> + where + T: Clone, + { + self.stat_column_expr(stats_expr, column_expr, field, StatisticsType::RowCount) } } +/// An expression with statistics, and the target of those statistics. +type StatisticsExpr<'a, T> = (&'a Arc, &'a T); + impl From> for RequiredColumns { fn from(columns: Vec<(phys_expr::Column, StatisticsType, Field)>) -> Self { + let columns = columns + .into_iter() + .map(|(column, statistics_type, field)| RequiredStatistic { + target: Column::from_name(column.name()), + expr: Arc::new(column), + statistics_type, + field, + }) + .collect(); Self { columns } } } @@ -1142,22 +1272,30 @@ impl From> for RequiredColumns { /// -------+-------- /// 5 | 1000 /// ``` -fn build_statistics_record_batch( +fn build_statistics_record_batch + ?Sized>( statistics: &S, - required_columns: &RequiredColumns, -) -> Result { + required_columns: &RequiredColumns, +) -> Result +where + T: std::fmt::Debug, +{ let mut arrays = Vec::::with_capacity(required_columns.columns.len()); // For each needed statistics column: - for (column, statistics_type, stat_field) in required_columns.iter() { - let column = Column::from_name(column.name()); + for RequiredStatistic { + target, + statistics_type, + field: stat_field, + .. + } in required_columns.iter() + { let data_type = stat_field.data_type(); let num_containers = statistics.num_containers(); let array = match statistics_type { - StatisticsType::Min => statistics.min_values(&column), - StatisticsType::Max => statistics.max_values(&column), - StatisticsType::NullCount => statistics.null_counts(&column), + StatisticsType::Min => statistics.min_values(target), + StatisticsType::Max => statistics.max_values(target), + StatisticsType::NullCount => statistics.null_counts(target), StatisticsType::RowCount => statistics.row_counts(), }; let array = array.unwrap_or_else(|| new_null_array(data_type, num_containers)); @@ -1189,63 +1327,70 @@ fn build_statistics_record_batch( }) } -struct PruningExpressionBuilder<'a> { - column: phys_expr::Column, +struct PruningExpressionBuilder<'a, T> { + /// The column, or other expression, whose statistics the predicate reads + stats_expr: Arc, + /// The target of `stats_expr` + target: T, column_expr: Arc, op: Operator, scalar_expr: Arc, - field: &'a Field, - required_columns: &'a mut RequiredColumns, + field: Field, + required_columns: &'a mut RequiredColumns, } -impl<'a> PruningExpressionBuilder<'a> { - fn try_new( +impl<'a, T: Clone> PruningExpressionBuilder<'a, T> { + fn try_new>( left: &'a Arc, right: &'a Arc, - left_columns: ColumnReferenceCount, - right_columns: ColumnReferenceCount, + left_columns: StatisticsExprCount, + right_columns: StatisticsExprCount, op: Operator, - schema: &'a SchemaRef, - required_columns: &'a mut RequiredColumns, + ctx: &PredicateBuildContext<'_, R>, + required_columns: &'a mut RequiredColumns, ) -> Result { // find column name; input could be a more complicated expression - let (column_expr, scalar_expr, column, correct_operator) = match ( + let (column_expr, scalar_expr, (stats_expr, target), correct_operator) = match ( left_columns, right_columns, ) { - (ColumnReferenceCount::One(column), ColumnReferenceCount::Zero) => { - (left, right, column, op) + (StatisticsExprCount::One(column, target), StatisticsExprCount::Zero) => { + (left, right, (column, target), op) } - (ColumnReferenceCount::Zero, ColumnReferenceCount::One(column)) => { - (right, left, column, reverse_operator(op)?) + (StatisticsExprCount::Zero, StatisticsExprCount::One(column, target)) => { + (right, left, (column, target), reverse_operator(op)?) } - (ColumnReferenceCount::One(_), ColumnReferenceCount::One(_)) => { + (StatisticsExprCount::One(..), StatisticsExprCount::One(..)) => { // both sides have one column - not supported return plan_err!( "Expression not supported for pruning: left has 1 column, right has 1 column" ); } - (ColumnReferenceCount::Zero, ColumnReferenceCount::Zero) => { + (StatisticsExprCount::Zero, StatisticsExprCount::Zero) => { // both sides are literals - should be handled before calling try_new return plan_err!( "Pruning literal expressions is not supported, please call PhysicalExprSimplifier first" ); } - (ColumnReferenceCount::Many, _) | (_, ColumnReferenceCount::Many) => { + (StatisticsExprCount::Many, _) | (_, StatisticsExprCount::Many) => { return plan_err!( "Expression not supported for pruning: left or right has multiple columns" ); } }; - let (column_expr, correct_operator, scalar_expr) = - rewrite_expr_to_prunable(column_expr, correct_operator, scalar_expr, schema)?; - let Some((_, field)) = schema.column_with_name(column.name()) else { - return plan_err!("Field not found in schema"); - }; + let (column_expr, correct_operator, scalar_expr) = rewrite_expr_to_prunable( + column_expr, + correct_operator, + scalar_expr, + &stats_expr, + ctx.schema, + )?; + let field = ctx.statistics_field(&stats_expr)?; Ok(Self { - column, + stats_expr, + target, column_expr, op: correct_operator, scalar_expr, @@ -1263,13 +1408,19 @@ impl<'a> PruningExpressionBuilder<'a> { } fn min_column_expr(&mut self) -> Result> { - self.required_columns - .min_column_expr(&self.column, &self.column_expr, self.field) + self.required_columns.min_column_expr( + (&self.stats_expr, &self.target), + &self.column_expr, + &self.field, + ) } fn max_column_expr(&mut self) -> Result> { - self.required_columns - .max_column_expr(&self.column, &self.column_expr, self.field) + self.required_columns.max_column_expr( + (&self.stats_expr, &self.target), + &self.column_expr, + &self.field, + ) } /// This function is to simply retune the `null_count` physical expression no matter what the @@ -1279,14 +1430,13 @@ impl<'a> PruningExpressionBuilder<'a> { /// cast(x as int) < 10 => x_null_count, /// try_cast(x as float) < 10.0 => x_null_count fn null_count_column_expr(&mut self) -> Result> { - // Retune to [`phys_expr::Column`] - let column_expr = Arc::new(self.column.clone()) as _; + let column_expr = Arc::clone(&self.stats_expr); // null_count is DataType::UInt64, which is different from the column's data type (i.e. self.field) let null_count_field = &Field::new(self.field.name(), DataType::UInt64, true); self.required_columns.null_count_column_expr( - &self.column, + (&self.stats_expr, &self.target), &column_expr, null_count_field, ) @@ -1299,14 +1449,13 @@ impl<'a> PruningExpressionBuilder<'a> { /// cast(x as int) < 10 => x_row_count, /// try_cast(x as float) < 10.0 => x_row_count fn row_count_column_expr(&mut self) -> Result> { - // Retune to [`phys_expr::Column`] - let column_expr = Arc::new(self.column.clone()) as _; + let column_expr = Arc::clone(&self.stats_expr); // row_count is DataType::UInt64, which is different from the column's data type (i.e. self.field) let row_count_field = &Field::new(self.field.name(), DataType::UInt64, true); self.required_columns.row_count_column_expr( - &self.column, + (&self.stats_expr, &self.target), &column_expr, row_count_field, ) @@ -1325,17 +1474,20 @@ impl<'a> PruningExpressionBuilder<'a> { /// 6. `try_cast(can_prunable_expr) > 10` /// /// More rewrite rules are still in progress. +/// +/// `stats_expr` is the one expression in `column_expr` that has statistics. fn rewrite_expr_to_prunable( column_expr: &PhysicalExprRef, op: Operator, scalar_expr: &PhysicalExprRef, + stats_expr: &PhysicalExprRef, schema: &Schema, ) -> Result<(PhysicalExprRef, Operator, PhysicalExprRef)> { if !is_compare_op(op) { return plan_err!("rewrite_expr_to_prunable only support compare expression"); } - if column_expr.downcast_ref::().is_some() { + if column_expr == stats_expr { // `col op lit()` Ok((Arc::clone(column_expr), op, Arc::clone(scalar_expr))) } else if let Some(cast) = column_expr.downcast_ref::() { @@ -1345,6 +1497,7 @@ fn rewrite_expr_to_prunable( cast.cast_type(), op, scalar_expr, + stats_expr, schema, )?; let left = Arc::new(phys_expr::CastExpr::new_with_target_field( @@ -1364,6 +1517,7 @@ fn rewrite_expr_to_prunable( try_cast.cast_type(), op, scalar_expr, + stats_expr, schema, )?; let left = Arc::new(phys_expr::TryCastExpr::new( @@ -1374,7 +1528,7 @@ fn rewrite_expr_to_prunable( } else if let Some(neg) = column_expr.downcast_ref::() { // `-col > lit()` --> `col < -lit()` let (left, op, right) = - rewrite_expr_to_prunable(neg.arg(), op, scalar_expr, schema)?; + rewrite_expr_to_prunable(neg.arg(), op, scalar_expr, stats_expr, schema)?; let right = Arc::new(phys_expr::NegativeExpr::new(right)); Ok((left, reverse_operator(op)?, right)) } else if let Some(not) = column_expr.downcast_ref::() { @@ -1390,7 +1544,7 @@ fn rewrite_expr_to_prunable( "Not with operator other than Eq / NotEq / IsDistinctFrom / IsNotDistinctFrom is not supported" ); } - if not.arg().downcast_ref::().is_some() { + if not.arg() == stats_expr { let left = Arc::clone(not.arg()); let right = Arc::new(phys_expr::NotExpr::new(Arc::clone(scalar_expr))); Ok((left, reverse_operator(op)?, right)) @@ -1407,10 +1561,11 @@ fn rewrite_cast_child_to_prunable( cast_type: &DataType, op: Operator, scalar_expr: &PhysicalExprRef, + stats_expr: &PhysicalExprRef, schema: &Schema, ) -> Result<(PhysicalExprRef, Operator, PhysicalExprRef)> { verify_support_type_for_prune(&cast_child_expr.data_type(schema)?, cast_type)?; - rewrite_expr_to_prunable(cast_child_expr, op, scalar_expr, schema) + rewrite_expr_to_prunable(cast_child_expr, op, scalar_expr, stats_expr, schema) } fn is_compare_op(op: Operator) -> bool { @@ -1456,16 +1611,14 @@ fn verify_support_type_for_prune(from_type: &DataType, to_type: &DataType) -> Re } } -/// replaces a column with an old name with a new name in an expression +/// Replaces every appearance of `old` in `e` with the column `column_new` fn rewrite_column_expr( e: Arc, - column_old: &phys_expr::Column, + old: &Arc, column_new: &phys_expr::Column, ) -> Result> { e.transform(|expr| { - if let Some(column) = expr.downcast_ref::() - && column == column_old - { + if &expr == old { return Ok(Transformed::yes(Arc::new(column_new.clone()))); } @@ -1486,16 +1639,16 @@ fn reverse_operator(op: Operator) -> Result { /// expression in terms of the min and max that will evaluate to true /// if the column may contain values, and false if definitely does not /// contain values -fn build_single_column_expr( - column: &phys_expr::Column, - schema: &Schema, - required_columns: &mut RequiredColumns, +fn build_single_column_expr( + column: StatisticsExpr<'_, R::Target>, + ctx: &PredicateBuildContext<'_, R>, + required_columns: &mut RequiredColumns, is_not: bool, // if true, treat as !col ) -> Option> { - let field = schema.field_with_name(column.name()).ok()?; + let field = &ctx.statistics_field(column.0).ok()?; if *field.data_type() == DataType::Boolean { - let col_ref = Arc::new(column.clone()) as _; + let col_ref = Arc::clone(column.0); let min = required_columns .min_column_expr(column, &col_ref, field) @@ -1531,22 +1684,23 @@ fn build_single_column_expr( /// The pruning expression evaluates to true ONLY if the column definitely CONTAINS /// at least one NULL value. In this case we can know that `IS NOT NULL` can not be true and /// thus can prune the row group / value -fn build_is_null_column_expr( +fn build_is_null_column_expr( expr: &Arc, - schema: &Schema, - required_columns: &mut RequiredColumns, + ctx: &PredicateBuildContext<'_, R>, + required_columns: &mut RequiredColumns, with_not: bool, ) -> Option> { - if let Some(col) = expr.downcast_ref::() { - let field = schema.field_with_name(col.name()).ok()?; + if let Some(target) = ctx.resolve(expr) { + let field = ctx.statistics_field(expr).ok()?; + let stats_expr = (expr, &target); let null_count_field = &Field::new(field.name(), DataType::UInt64, true); if with_not { if let Ok(row_count_expr) = - required_columns.row_count_column_expr(col, expr, null_count_field) + required_columns.row_count_column_expr(stats_expr, expr, null_count_field) { required_columns - .null_count_column_expr(col, expr, null_count_field) + .null_count_column_expr(stats_expr, expr, null_count_field) .map(|null_count_column_expr| { // IsNotNull(column) => null_count != row_count Arc::new(phys_expr::BinaryExpr::new( @@ -1561,7 +1715,7 @@ fn build_is_null_column_expr( } } else { required_columns - .null_count_column_expr(col, expr, null_count_field) + .null_count_column_expr(stats_expr, expr, null_count_field) .map(|null_count_column_expr| { // IsNull(column) => null_count > 0 Arc::new(phys_expr::BinaryExpr::new( @@ -1597,12 +1751,12 @@ impl CompactInListDomain { /// Statistics expressions for `column`: its min, its max, and "not every row is /// NULL". Appends to `required_columns`, rolling the appends back if any part /// cannot be built, since [`RequiredColumns::stat_column_expr`] only appends. -fn min_max_non_null_exprs( - column: &phys_expr::Column, +fn min_max_non_null_exprs( + column: StatisticsExpr<'_, R::Target>, column_expr: &Arc, field: &Field, - schema: &Schema, - required_columns: &mut RequiredColumns, + ctx: &PredicateBuildContext<'_, R>, + required_columns: &mut RequiredColumns, ) -> Option<(PhysicalExprRef, PhysicalExprRef, PhysicalExprRef)> { let appended = required_columns.columns.len(); let statistics = (|| { @@ -1612,14 +1766,9 @@ fn min_max_non_null_exprs( let max = required_columns .max_column_expr(column, column_expr, field) .ok()?; - // A cast on `column_expr` (widening it towards min/max's target type) - // does not affect nullability, so check it on the bare column beneath. - let bare_expr = match column_expr.downcast_ref::() { - Some(cast) => cast.expr(), - None => column_expr, - }; - let non_null = - build_is_null_column_expr(bare_expr, schema, required_columns, true)?; + // A cast around `column` in `column_expr` does not change which rows + // are NULL, so check the nullability of `column` itself. + let non_null = build_is_null_column_expr(column.0, ctx, required_columns, true)?; Some((min, max, non_null)) })(); if statistics.is_none() { @@ -1632,10 +1781,10 @@ fn min_max_non_null_exprs( /// build side pushed down as an opaque hash-table lookup): tests container /// min/max stats against the build side's key-range bitmap, which is fixed size /// and built once with the join's hash table. -fn build_hash_lookup_pruning_expr( +fn build_hash_lookup_pruning_expr( lookup: &HashTableLookupExpr, - schema: &Schema, - required_columns: &mut RequiredColumns, + ctx: &PredicateBuildContext<'_, R>, + required_columns: &mut RequiredColumns, ) -> Option> { let bitmap = Arc::clone(lookup.pruning_bitmap()?); let on_columns = lookup.children(); @@ -1645,20 +1794,24 @@ fn build_hash_lookup_pruning_expr( // The schema adapter often wraps the column in a same-type or widening cast // (a nullable table column over a REQUIRED file column, or a narrower file // type). `stat_column_expr` rewrites only the inner `Column`, keeping it. - let column = match column_expr.downcast_ref::() { - Some(cast) => { - let column = cast.expr().downcast_ref::()?; - let from = schema.fields().get(column.index())?.data_type(); - cast.is_bigger_cast(from).then_some(column)? + let (column, cast, target) = match ctx.resolve(column_expr) { + Some(target) => (column_expr, None, target), + None => { + let cast = column_expr.downcast_ref::()?; + (cast.expr(), Some(cast), ctx.resolve(cast.expr())?) } - None => column_expr.downcast_ref::()?, }; - let field = schema.fields().get(column.index())?; - if field.name() != column.name() { + let field = ctx.statistics_field(column).ok()?; + if cast.is_some_and(|cast| !cast.is_bigger_cast(field.data_type())) { return None; } - let (min, max, non_null) = - min_max_non_null_exprs(column, column_expr, field, schema, required_columns)?; + let (min, max, non_null) = min_max_non_null_exprs( + (column, &target), + column_expr, + &field, + ctx, + required_columns, + )?; Some(Arc::new(phys_expr::BinaryExpr::new( non_null, Operator::And, @@ -1681,10 +1834,10 @@ fn build_hash_lookup_pruning_expr( /// A NULL list member makes `NOT IN` and an all-NULL `IN` list never TRUE. For /// other `IN` lists, NULL does not change which rows can make the predicate TRUE, /// but prevents inversion from proving that a container is fully matched. -fn build_compact_in_list_expr( +fn build_compact_in_list_expr( in_list: &phys_expr::InListExpr, - schema: &Schema, - required_columns: &mut RequiredColumns, + ctx: &PredicateBuildContext<'_, R>, + required_columns: &mut RequiredColumns, properties: &mut PruningExpressionProperties, ) -> Option> { let membership = if in_list.negated() { @@ -1692,15 +1845,13 @@ fn build_compact_in_list_expr( } else { SetMembership::In }; - let column = in_list.expr().downcast_ref::()?; - let field = schema.fields().get(column.index())?; + let column = in_list.expr(); + let target = ctx.resolve(column)?; + let field = &ctx.statistics_field(column).ok()?; let data_type = match field.data_type() { DataType::Dictionary(_, value) => value.as_ref(), data_type => data_type, }; - if field.name() != column.name() { - return None; - } let mut domain = if data_type.is_string() { CompactInListDomain::String(Vec::with_capacity(in_list.list().len())) } else if matches!( @@ -1742,8 +1893,13 @@ fn build_compact_in_list_expr( Some(false), )))); } - let (min, max, non_null) = - min_max_non_null_exprs(column, in_list.expr(), field, schema, required_columns)?; + let (min, max, non_null) = min_max_non_null_exprs( + (column, &target), + in_list.expr(), + field, + ctx, + required_columns, + )?; let may_match = match domain { CompactInListDomain::String(values) => { Arc::new(StringInListPruningExpr::new(membership, min, max, values)) @@ -1841,6 +1997,7 @@ impl PredicateRewriter { schema: &schema, unhandled_hook: &self.unhandled_hook, max_in_list_size: self.max_in_list_size, + resolver: &ColumnResolver, }; build_predicate_expression(expr, &ctx, &mut required_columns, &mut properties) } @@ -1848,14 +2005,40 @@ impl PredicateRewriter { /// The settings that do not change while [`build_predicate_expression`] /// rewrites one predicate. -#[derive(Clone, Copy)] -struct PredicateBuildContext<'a> { +struct PredicateBuildContext<'a, R> { /// The schema of the predicate schema: &'a SchemaRef, /// Rewrites the predicates that pruning cannot use unhandled_hook: &'a Arc, /// The largest `IN (...)` list that pruning uses max_in_list_size: usize, + /// See [`PruningPredicateBuilder::with_resolver`] + resolver: &'a R, +} + +impl PredicateBuildContext<'_, R> { + /// Returns the target of `expr` if the predicate reads the statistics of + /// `expr` as a whole. + fn resolve(&self, expr: &Arc) -> Option { + self.resolver.resolve(expr) + } + + /// Returns a field with the type of the values of the statistics + /// expression `expr`. + fn statistics_field(&self, expr: &Arc) -> Result { + match expr.downcast_ref::() { + // A statistics source identifies a column by its name. + Some(column) => match self.schema.column_with_name(column.name()) { + Some((_, field)) => Ok(field.clone()), + None => plan_err!("Field not found in schema"), + }, + None => Ok(Field::new( + expr.to_string(), + expr.data_type(self.schema)?, + true, + )), + } + } } /// Translate logical filter expression into pruning predicate @@ -1870,17 +2053,19 @@ struct PredicateBuildContext<'a> { /// pruning. Large literal lists of supported ordered types use a compact /// representation for both `IN` and `NOT IN`; unsupported lists use per-value /// checks. Longer lists fall back to `unhandled_hook`. -fn build_predicate_expression( +fn build_predicate_expression( expr: &Arc, - ctx: &PredicateBuildContext, - required_columns: &mut RequiredColumns, + ctx: &PredicateBuildContext<'_, R>, + required_columns: &mut RequiredColumns, properties: &mut PruningExpressionProperties, ) -> Arc { let PredicateBuildContext { schema, unhandled_hook, max_in_list_size, - } = *ctx; + .. + } = ctx; + let max_in_list_size = *max_in_list_size; if is_always_false(expr) { // Shouldn't return `unhandled_hook.handle(expr)` // Because it will transfer false to true. @@ -1888,27 +2073,27 @@ fn build_predicate_expression( } // predicate expression can only be a binary expression if let Some(is_null) = expr.downcast_ref::() { - return build_is_null_column_expr(is_null.arg(), schema, required_columns, false) + return build_is_null_column_expr(is_null.arg(), ctx, required_columns, false) .unwrap_or_else(|| unhandled_hook.handle(expr)); } if let Some(is_not_null) = expr.downcast_ref::() { - return build_is_null_column_expr( - is_not_null.arg(), - schema, - required_columns, - true, - ) - .unwrap_or_else(|| unhandled_hook.handle(expr)); + return build_is_null_column_expr(is_not_null.arg(), ctx, required_columns, true) + .unwrap_or_else(|| unhandled_hook.handle(expr)); } - if let Some(col) = expr.downcast_ref::() { - return build_single_column_expr(col, schema, required_columns, false) + if let Some(target) = ctx.resolve(expr) { + return build_single_column_expr((expr, &target), ctx, required_columns, false) .unwrap_or_else(|| unhandled_hook.handle(expr)); } if let Some(not) = expr.downcast_ref::() { // match !col (don't do so recursively) - if let Some(col) = not.arg().downcast_ref::() { - return build_single_column_expr(col, schema, required_columns, true) - .unwrap_or_else(|| unhandled_hook.handle(expr)); + if let Some(target) = ctx.resolve(not.arg()) { + return build_single_column_expr( + (not.arg(), &target), + ctx, + required_columns, + true, + ) + .unwrap_or_else(|| unhandled_hook.handle(expr)); } else { return unhandled_hook.handle(expr); } @@ -1921,7 +2106,7 @@ fn build_predicate_expression( if in_list.list().len() > MAX_IN_LIST_SIZE && in_list.list().len() <= max_in_list_size && let Some(pruning_expr) = - build_compact_in_list_expr(in_list, schema, required_columns, properties) + build_compact_in_list_expr(in_list, ctx, required_columns, properties) { return pruning_expr; } @@ -1959,7 +2144,7 @@ fn build_predicate_expression( } } if let Some(lookup) = expr.downcast_ref::() { - return build_hash_lookup_pruning_expr(lookup, schema, required_columns) + return build_hash_lookup_pruning_expr(lookup, ctx, required_columns) .unwrap_or_else(|| unhandled_hook.handle(expr)); } // A partitioned hash join hides its per-partition filters under a `CASE` on the @@ -2045,15 +2230,15 @@ fn build_predicate_expression( return expr; } - let left_columns = ColumnReferenceCount::from_expression(&left); - let right_columns = ColumnReferenceCount::from_expression(&right); + let left_columns = StatisticsExprCount::from_expression(&left, ctx); + let right_columns = StatisticsExprCount::from_expression(&right, ctx); let expr_builder = PruningExpressionBuilder::try_new( &left, &right, left_columns, right_columns, op, - schema, + ctx, required_columns, ); let mut expr_builder = match expr_builder { @@ -2070,52 +2255,60 @@ fn build_predicate_expression( .unwrap_or_else(|_| unhandled_hook.handle(expr)) } -/// Count of distinct column references in an expression. -/// This is the same as [`collect_columns`] but optimized to stop counting -/// once more than one distinct column is found. +/// Count of the distinct statistics expressions in an expression: the +/// columns, and the other expressions that the predicate reads statistics for. +/// The children of a statistics expression do not count. /// /// For example, in expression `col1 + col2`, the count is `Many`. /// In expression `col1 + 5`, the count is `One`. /// In expression `5 + 10`, the count is `Zero`. -/// -/// [`collect_columns`]: datafusion_physical_expr::utils::collect_columns -#[derive(Debug, PartialEq, Eq)] -enum ColumnReferenceCount { - /// no column references +#[derive(Debug)] +enum StatisticsExprCount { + /// no statistics expressions Zero, - /// Only one column reference - One(phys_expr::Column), - /// More than one column reference + /// Only one statistics expression, and its target + One(Arc, T), + /// More than one statistics expression, or a column without a target Many, } -impl ColumnReferenceCount { - /// Count the number of distinct column references in an expression - fn from_expression(expr: &Arc) -> Self { - let mut seen = HashSet::::new(); +impl StatisticsExprCount { + /// Count the number of distinct statistics expressions in an expression + fn from_expression>( + expr: &Arc, + ctx: &PredicateBuildContext<'_, R>, + ) -> Self { + let mut count = StatisticsExprCount::Zero; expr.apply(|expr| { - if let Some(column) = expr.downcast_ref::() { - seen.insert(column.clone()); - if seen.len() > 1 { + let Some(target) = ctx.resolve(expr) else { + // A column without a target has no statistics, and it is not + // a constant. So the predicate cannot use the comparison. + if expr.is::() { + count = StatisticsExprCount::Many; + return Ok(TreeNodeRecursion::Stop); + } + return Ok(TreeNodeRecursion::Continue); + }; + match &count { + StatisticsExprCount::Zero => { + count = StatisticsExprCount::One(Arc::clone(expr), target); + } + StatisticsExprCount::One(seen, _) if seen == expr => {} + _ => { + count = StatisticsExprCount::Many; return Ok(TreeNodeRecursion::Stop); } } - Ok(TreeNodeRecursion::Continue) + Ok(TreeNodeRecursion::Jump) }) // pre_visit always returns OK, so this will always too .expect("no way to return error during recursion"); - match seen.len() { - 0 => ColumnReferenceCount::Zero, - 1 => ColumnReferenceCount::One( - seen.into_iter().next().expect("just checked len==1"), - ), - _ => ColumnReferenceCount::Many, - } + count } } -fn build_statistics_expr( - expr_builder: &mut PruningExpressionBuilder, +fn build_statistics_expr( + expr_builder: &mut PruningExpressionBuilder<'_, T>, ) -> Result> { let statistics_expr: Arc = match expr_builder.op() { Operator::NotEq => build_ne_statistics_expr(expr_builder)?, @@ -2197,8 +2390,8 @@ fn or_expr( binary_expr(left, Operator::Or, right) } -fn build_eq_statistics_expr( - expr_builder: &mut PruningExpressionBuilder, +fn build_eq_statistics_expr( + expr_builder: &mut PruningExpressionBuilder<'_, T>, ) -> Result> { let min_column_expr = expr_builder.min_column_expr()?; let max_column_expr = expr_builder.max_column_expr()?; @@ -2216,8 +2409,8 @@ fn build_eq_statistics_expr( )) } -fn build_ne_statistics_expr( - expr_builder: &mut PruningExpressionBuilder, +fn build_ne_statistics_expr( + expr_builder: &mut PruningExpressionBuilder<'_, T>, ) -> Result> { let min_column_expr = expr_builder.min_column_expr()?; let max_column_expr = expr_builder.max_column_expr()?; @@ -2235,8 +2428,8 @@ fn build_ne_statistics_expr( )) } -fn column_has_nulls_expr( - expr_builder: &mut PruningExpressionBuilder, +fn column_has_nulls_expr( + expr_builder: &mut PruningExpressionBuilder<'_, T>, ) -> Result> { Ok(binary_expr( expr_builder.null_count_column_expr()?, @@ -2245,8 +2438,8 @@ fn column_has_nulls_expr( )) } -fn column_has_non_nulls_expr( - expr_builder: &mut PruningExpressionBuilder, +fn column_has_non_nulls_expr( + expr_builder: &mut PruningExpressionBuilder<'_, T>, ) -> Result> { Ok(binary_expr( expr_builder.null_count_column_expr()?, @@ -2255,8 +2448,8 @@ fn column_has_non_nulls_expr( )) } -fn build_is_distinct_from( - expr_builder: &mut PruningExpressionBuilder, +fn build_is_distinct_from( + expr_builder: &mut PruningExpressionBuilder<'_, T>, ) -> Result> { let scalar_expr = Arc::clone(expr_builder.scalar_expr()); @@ -2275,8 +2468,8 @@ fn build_is_distinct_from( )) } -fn build_is_not_distinct_from( - expr_builder: &mut PruningExpressionBuilder, +fn build_is_not_distinct_from( + expr_builder: &mut PruningExpressionBuilder<'_, T>, ) -> Result> { let scalar_expr = Arc::clone(expr_builder.scalar_expr()); @@ -2327,8 +2520,8 @@ fn string_literal_as(value: String, target_type: &DataType) -> Arc( + expr_builder: &mut PruningExpressionBuilder<'_, T>, ) -> Option> { // column LIKE literal => (min, max) LIKE literal split at unescaped % => min <= split literal && split literal <= max // column LIKE 'foo%' => min <= 'foo' && 'foo' <= max @@ -2387,8 +2580,8 @@ fn build_like_match( // The intuition is that if both `col_min` and `col_max` begin with `const_prefix` that means // **all** data in this row group begins with `const_prefix` as well (and therefore the predicate // looking for rows that don't begin with `const_prefix` can never be true) -fn build_not_like_match( - expr_builder: &mut PruningExpressionBuilder<'_>, +fn build_not_like_match( + expr_builder: &mut PruningExpressionBuilder<'_, T>, ) -> Result> { // col NOT LIKE 'const_prefix%' -> !(col_min LIKE 'const_prefix%' && col_max LIKE 'const_prefix%') -> (col_min NOT LIKE 'const_prefix%' || col_max NOT LIKE 'const_prefix%') @@ -2523,9 +2716,9 @@ fn increment_utf8(data: &str) -> Option { /// If the column is known to be all nulls, then the expression /// `x_null_count = x_row_count` will be true, which will cause the /// boolean expression to return false. Therefore, prune out the container. -fn wrap_null_count_check_expr( +fn wrap_null_count_check_expr( statistics_expr: Arc, - expr_builder: &mut PruningExpressionBuilder, + expr_builder: &mut PruningExpressionBuilder<'_, T>, ) -> Result> { // (x_null_count != x_row_count) AND () Ok(and_expr( @@ -2548,6 +2741,7 @@ mod tests { use std::ops::{Not, Rem}; use super::*; + use datafusion_common::Column; use datafusion_common::test_util::batches_to_string; use datafusion_expr::{and, col, lit, or}; use datafusion_physical_expr::utils::collect_columns; @@ -2977,7 +3171,7 @@ mod tests { // Fields in required schema should be unique, otherwise when creating batches // it will fail because of duplicate field names let mut fields = HashSet::new(); - for (_col, _ty, field) in p.required_columns().iter() { + for RequiredStatistic { field, .. } in p.required_columns().iter() { let was_new = fields.insert(field); assert!( was_new, @@ -4426,7 +4620,7 @@ mod tests { } #[test] - fn required_columns_lists_each_statistic_column() { + fn required_columns_lists_each_statistic_target() { let schema = Arc::new(Schema::new(vec![ Field::new("a", DataType::Int32, true), Field::new("b", DataType::Int32, true), @@ -4439,8 +4633,8 @@ mod tests { .unwrap(); let names: Vec<_> = predicate .required_columns() - .columns() - .map(|c| c.name()) + .targets() + .map(|c| c.name.as_str()) .collect(); assert_eq!(names, ["a", "a", "a", "b", "b"]); } @@ -4526,8 +4720,8 @@ mod tests { assert_eq!(predicate.literal_guarantees()[0].literals.len(), count); let names: HashSet<_> = predicate .required_columns() - .columns() - .map(|c| c.name()) + .targets() + .map(|c| c.name.as_str()) .collect(); assert_eq!(names, HashSet::from(["c1"])); if count > MAX_IN_LIST_SIZE { @@ -7125,7 +7319,7 @@ mod tests { let right_input = lit(ScalarValue::Int32(Some(12))); let right_input = logical2physical(&right_input, &schema); let (result_left, _, result_right) = - rewrite_expr_to_prunable(&left_input, Operator::Eq, &right_input, &schema) + rewrite_to_prunable(&left_input, Operator::Eq, &right_input, &schema) .unwrap(); assert_eq!(result_left.to_string(), left_input.to_string()); assert_eq!(result_right.to_string(), right_input.to_string()); @@ -7136,7 +7330,7 @@ mod tests { let right_input = lit(ScalarValue::Decimal128(Some(12), 20, 3)); let right_input = logical2physical(&right_input, &schema); let (result_left, _, result_right) = - rewrite_expr_to_prunable(&left_input, Operator::Gt, &right_input, &schema) + rewrite_to_prunable(&left_input, Operator::Gt, &right_input, &schema) .unwrap(); // The rewrite rebuilds the cast with its nullable target field assert_eq!(result_left.to_string(), "CAST(a@0 AS Decimal128(20, 3);N)"); @@ -7148,7 +7342,7 @@ mod tests { let right_input = lit(ScalarValue::Int64(Some(12))); let right_input = logical2physical(&right_input, &schema); let (result_left, _, result_right) = - rewrite_expr_to_prunable(&left_input, Operator::Gt, &right_input, &schema) + rewrite_to_prunable(&left_input, Operator::Gt, &right_input, &schema) .unwrap(); assert_eq!(result_left.to_string(), left_input.to_string()); assert_eq!(result_right.to_string(), right_input.to_string()); @@ -7234,7 +7428,7 @@ mod tests { let right_input = lit(ScalarValue::Int64(Some(12))); let right_input = logical2physical(&right_input, &schema); let result = - rewrite_expr_to_prunable(&left_input, Operator::Gt, &right_input, &schema); + rewrite_to_prunable(&left_input, Operator::Gt, &right_input, &schema); assert!(result.is_err()); // other expr @@ -7243,7 +7437,7 @@ mod tests { let right_input = lit(ScalarValue::Int64(Some(12))); let right_input = logical2physical(&right_input, &schema); let result = - rewrite_expr_to_prunable(&left_input, Operator::Gt, &right_input, &schema); + rewrite_to_prunable(&left_input, Operator::Gt, &right_input, &schema); assert!(result.is_err()); // TODO: add other negative test for other case and op } @@ -7738,6 +7932,30 @@ mod tests { )) } + impl PartialEq<(phys_expr::Column, StatisticsType, Field)> for RequiredStatistic { + fn eq( + &self, + (column, statistics_type, field): &(phys_expr::Column, StatisticsType, Field), + ) -> bool { + self.expr.downcast_ref::() == Some(column) + && &self.statistics_type == statistics_type + && &self.field == field + } + } + + /// Calls [`rewrite_expr_to_prunable`] for the one column of `column_expr`. + fn rewrite_to_prunable( + column_expr: &PhysicalExprRef, + op: Operator, + scalar_expr: &PhysicalExprRef, + schema: &Schema, + ) -> Result<(PhysicalExprRef, Operator, PhysicalExprRef)> { + let mut columns = collect_columns(column_expr).into_iter(); + let stats_expr = Arc::new(columns.next().expect("a column")) as PhysicalExprRef; + assert!(columns.next().is_none()); + rewrite_expr_to_prunable(column_expr, op, scalar_expr, &stats_expr, schema) + } + fn test_build_predicate_expression( expr: &Expr, schema: &Schema, @@ -7751,6 +7969,7 @@ mod tests { schema: &schema, unhandled_hook: &unhandled_hook, max_in_list_size: MAX_IN_LIST_SIZE, + resolver: &ColumnResolver, }; build_predicate_expression(&expr, &ctx, required_columns, &mut properties) } diff --git a/datafusion/pruning/src/statistics_source.rs b/datafusion/pruning/src/statistics_source.rs new file mode 100644 index 0000000000000..9922030475ea1 --- /dev/null +++ b/datafusion/pruning/src/statistics_source.rs @@ -0,0 +1,500 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +use std::collections::HashSet; +use std::fmt::Debug; +use std::sync::Arc; + +use arrow::array::{ArrayRef, BooleanArray}; +use datafusion_common::pruning::PruningStatistics; +use datafusion_common::{Column, ScalarValue}; +use datafusion_physical_expr::expressions as phys_expr; +use datafusion_physical_plan::PhysicalExpr; + +/// Decides which expressions of a predicate have statistics, and names the +/// statistics of each one with a target. +/// +/// [`PruningPredicateBuilder`](crate::PruningPredicateBuilder) calls +/// [`Self::resolve`] while it builds a +/// [`PruningPredicate`](crate::PruningPredicate). The predicate stores each +/// target, and passes it back to the [`PruningStatisticsSource`] when it +/// prunes. So the source does not inspect expressions. +/// +/// | Resolver | Target | Expressions with statistics | +/// |--------------------|------------|-----------------------------| +/// | [`ColumnResolver`] | [`Column`] | Columns | +/// | Your own | Your own | What `resolve` accepts | +/// +/// The builder asks about an expression before it asks about the children of +/// that expression. So the outermost resolved expression wins, and the +/// predicate does not look inside it. +/// +/// A resolver decides for columns too. The predicate cannot use a comparison +/// that reads a column without a target. +pub trait StatisticsResolver { + /// Names the statistics of one expression. + type Target: Clone + Debug; + + /// Returns the target of `expr` if the statistics source has statistics + /// for the values of `expr`. + /// + /// The statistics must describe exactly the values of `expr`. The + /// predicate treats `expr` like a column. + /// + /// The builder calls this for many nodes of the predicate, so it must be + /// cheap to reject an expression. The source may still return `None` for + /// a target, and then nothing is pruned for it. + fn resolve(&self, expr: &Arc) -> Option; +} + +impl StatisticsResolver for &R { + type Target = R::Target; + + fn resolve(&self, expr: &Arc) -> Option { + (**self).resolve(expr) + } +} + +/// The default [`StatisticsResolver`]: every column has statistics, and no +/// other expression has. +/// +/// The target is the [`Column`] that [`PruningStatistics`] takes. It holds +/// the name of the column, and no relation. +#[derive(Debug, Clone, Copy, Default)] +pub struct ColumnResolver; + +impl StatisticsResolver for ColumnResolver { + type Target = Column; + + fn resolve(&self, expr: &Arc) -> Option { + expr.downcast_ref::() + .map(|column| Column::from_name(column.name())) + } +} + +/// Statistics for a set of containers (such as files, row groups or pages), +/// read by target. +/// +/// A target names the statistics of one expression of a predicate. A +/// [`StatisticsResolver`] creates the targets. +/// +/// This is the target based form of [`PruningStatistics`]. Every type that +/// implements [`PruningStatistics`] also implements this trait for the +/// [`Column`] target, which is the default. Implement this trait for another +/// target to provide statistics for expressions other than columns. One type +/// can implement both. +pub trait PruningStatisticsSource { + /// Returns the minimum values of `target`, if known. + /// + /// The requirements on the values are those of + /// [`PruningStatistics::min_values`]. + fn min_values(&self, target: &T) -> Option; + + /// Returns the maximum values of `target`, if known. + /// + /// The requirements on the values are those of + /// [`PruningStatistics::max_values`]. + fn max_values(&self, target: &T) -> Option; + + /// Returns the number of containers that these statistics describe. + /// + /// Every returned array must have this length. + fn num_containers(&self) -> usize; + + /// Returns the number of rows for which `target` is null, as a + /// [`UInt64Array`](arrow::array::UInt64Array), if known. + fn null_counts(&self, target: &T) -> Option; + + /// Returns the number of rows in each container, as a + /// [`UInt64Array`](arrow::array::UInt64Array), if known. + fn row_counts(&self) -> Option; + + /// Returns what is known about whether the values of `target` are in + /// `values`. + /// + /// The meaning of the result is that of [`PruningStatistics::contained`]. + #[allow(clippy::allow_attributes, clippy::mutable_key_type)] // ScalarValue has interior mutability but is intentionally used as hash key + fn contained( + &self, + target: &T, + values: &HashSet, + ) -> Option; +} + +impl PruningStatisticsSource for S { + fn min_values(&self, column: &Column) -> Option { + PruningStatistics::min_values(self, column) + } + + fn max_values(&self, column: &Column) -> Option { + PruningStatistics::max_values(self, column) + } + + fn num_containers(&self) -> usize { + PruningStatistics::num_containers(self) + } + + fn null_counts(&self, column: &Column) -> Option { + PruningStatistics::null_counts(self, column) + } + + fn row_counts(&self) -> Option { + PruningStatistics::row_counts(self) + } + + fn contained( + &self, + column: &Column, + values: &HashSet, + ) -> Option { + PruningStatistics::contained(self, column, values) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{PruningPredicate, PruningPredicateBuilder}; + use arrow::array::{Int32Array, UInt64Array}; + use arrow::datatypes::{DataType, Field, Schema}; + use datafusion_expr_common::operator::Operator; + + /// Column `a` has the bounds `[1, 5]` and `[10, 20]`, and `contained` + /// rules out the second container for every column. + struct ColumnStats; + + impl PruningStatistics for ColumnStats { + fn min_values(&self, column: &Column) -> Option { + (column.name == "a").then(|| Arc::new(Int32Array::from(vec![1, 10])) as _) + } + fn max_values(&self, column: &Column) -> Option { + (column.name == "a").then(|| Arc::new(Int32Array::from(vec![5, 20])) as _) + } + fn num_containers(&self) -> usize { + 2 + } + fn null_counts(&self, column: &Column) -> Option { + (column.name == "a").then(|| Arc::new(UInt64Array::from(vec![3, 4])) as _) + } + fn row_counts(&self) -> Option { + Some(Arc::new(UInt64Array::from(vec![100, 200]))) + } + fn contained( + &self, + column: &Column, + _values: &HashSet, + ) -> Option { + (column.name == "a").then(|| BooleanArray::from(vec![None, Some(false)])) + } + } + + fn col(name: &str, index: usize) -> Arc { + Arc::new(phys_expr::Column::new(name, index)) + } + + fn lit(value: i32) -> Arc { + phys_expr::lit(value) + } + + fn binary( + left: Arc, + op: Operator, + right: Arc, + ) -> Arc { + Arc::new(phys_expr::BinaryExpr::new(left, op, right)) + } + + /// The target of a sum, such as `a + b`. + #[derive(Debug, Clone, PartialEq)] + struct Sum; + + /// Sums have statistics. Columns have none. + struct SumResolver; + + impl StatisticsResolver for SumResolver { + type Target = Sum; + + fn resolve(&self, expr: &Arc) -> Option { + expr.downcast_ref::() + .is_some_and(|binary| *binary.op() == Operator::Plus) + .then_some(Sum) + } + } + + /// Two containers with these statistics for a sum, and with the + /// statistics of [`ColumnStats`] for a column: + /// + /// | Container | min | max | Nulls | Rows | Bloom filter | + /// |-----------|-----|-----|-------|------|--------------| + /// | 0 | 1 | 3 | 0 | 5 | no value | + /// | 1 | 10 | 20 | 5 | 5 | unknown | + struct SumStats; + + impl PruningStatisticsSource for SumStats { + fn min_values(&self, _sum: &Sum) -> Option { + Some(Arc::new(Int32Array::from(vec![1, 10]))) + } + fn max_values(&self, _sum: &Sum) -> Option { + Some(Arc::new(Int32Array::from(vec![3, 20]))) + } + fn num_containers(&self) -> usize { + 2 + } + fn null_counts(&self, _sum: &Sum) -> Option { + Some(Arc::new(UInt64Array::from(vec![0, 5]))) + } + fn row_counts(&self) -> Option { + Some(Arc::new(UInt64Array::from(vec![5, 5]))) + } + fn contained( + &self, + _sum: &Sum, + _values: &HashSet, + ) -> Option { + Some(BooleanArray::from(vec![Some(false), None])) + } + } + + /// The same type is also a source for the column target. + impl PruningStatistics for SumStats { + fn min_values(&self, column: &Column) -> Option { + PruningStatistics::min_values(&ColumnStats, column) + } + fn max_values(&self, column: &Column) -> Option { + PruningStatistics::max_values(&ColumnStats, column) + } + fn num_containers(&self) -> usize { + 2 + } + fn null_counts(&self, column: &Column) -> Option { + PruningStatistics::null_counts(&ColumnStats, column) + } + fn row_counts(&self) -> Option { + PruningStatistics::row_counts(&ColumnStats) + } + fn contained( + &self, + column: &Column, + values: &HashSet, + ) -> Option { + PruningStatistics::contained(&ColumnStats, column, values) + } + } + + fn sum_schema() -> Arc { + Arc::new(Schema::new(vec![ + Field::new("a", DataType::Int32, true), + Field::new("b", DataType::Int32, true), + Field::new("c", DataType::Int32, true), + ])) + } + + /// `a + b` + fn sum() -> Arc { + binary(col("a", 0), Operator::Plus, col("b", 1)) + } + + /// A predicate that reads the statistics of columns. + fn column_predicate(expr: Arc) -> PruningPredicate { + PruningPredicateBuilder::new() + .with_file_schema(sum_schema()) + .try_build(expr) + .unwrap() + } + + /// A predicate that reads the statistics of sums. + fn sum_predicate(expr: Arc) -> PruningPredicate { + PruningPredicateBuilder::new() + .with_file_schema(sum_schema()) + .with_resolver(SumResolver) + .try_build(expr) + .unwrap() + } + + #[test] + #[expect(deprecated)] + fn resolved_expression_reads_its_own_statistics() { + let expr = binary(sum(), Operator::Gt, lit(5)); + let predicate = sum_predicate(Arc::clone(&expr)); + assert_eq!( + predicate.predicate_expr().to_string(), + "a@0 + b@1_null_count@1 != row_count@2 AND a@0 + b@1_max@0 > 5" + ); + // Container 0 has max 3. Container 1 holds only nulls. + assert_eq!(predicate.prune(&SumStats).unwrap(), [false, false]); + let required = predicate.required_columns(); + assert!(required.exprs().all(|expr| expr == &sum())); + assert_eq!(required.targets().collect::>(), [∑ 3]); + assert!(required.single_column().is_none()); + + // By default only columns have statistics, and `a + b` is not one. + let predicate = column_predicate(expr); + assert!(predicate.always_true()); + } + + #[test] + fn full_match_inverse_checks_resolved_expression_for_nulls() { + let inverse = PruningPredicateBuilder::new() + .with_file_schema(sum_schema()) + .with_resolver(SumResolver) + .try_build_inverse(binary(sum(), Operator::Gt, lit(5))) + .unwrap() + .unwrap(); + // The null check reads the null count of `a + b`, not of a column. + assert_eq!( + inverse.predicate_expr().to_string(), + "a@0 + b@1_null_count@1 != row_count@2 AND a@0 + b@1_min@0 <= 5 OR a@0 + b@1_null_count@1 > 0" + ); + assert_eq!( + inverse.required_columns().targets().collect::>(), + [∑ 3] + ); + } + + #[test] + fn resolved_expression_null_checks() { + let is_null: Arc = Arc::new(phys_expr::IsNullExpr::new(sum())); + let predicate = sum_predicate(is_null); + assert_eq!( + predicate.predicate_expr().to_string(), + "a@0 + b@1_null_count@0 > 0" + ); + assert_eq!(predicate.prune(&SumStats).unwrap(), [false, true]); + + let is_not_null: Arc = + Arc::new(phys_expr::IsNotNullExpr::new(sum())); + let predicate = sum_predicate(is_not_null); + assert_eq!( + predicate.predicate_expr().to_string(), + "a@0 + b@1_null_count@1 != row_count@0" + ); + assert_eq!(predicate.prune(&SumStats).unwrap(), [true, false]); + } + + #[test] + fn outermost_resolved_expression_wins() { + // `(a + b) + c` and `a + b` are both sums. + let outer = binary(sum(), Operator::Plus, col("c", 2)); + let predicate = sum_predicate(binary(Arc::clone(&outer), Operator::Gt, lit(5))); + assert!( + predicate + .required_columns() + .exprs() + .all(|expr| expr == &outer) + ); + } + + #[test] + fn rewrite_looks_inside_an_expression_that_is_not_resolved() { + // `-(a + b) > -2` is `a + b < 2` + let negative: Arc = + Arc::new(phys_expr::NegativeExpr::new(sum())); + let predicate = sum_predicate(binary(negative, Operator::Gt, lit(-2))); + assert_eq!( + predicate.predicate_expr().to_string(), + "a@0 + b@1_null_count@1 != row_count@2 AND a@0 + b@1_min@0 < 2" + ); + assert_eq!(predicate.prune(&SumStats).unwrap(), [true, false]); + } + + #[test] + fn resolved_expression_literal_guarantee() { + let expr = binary( + binary(sum(), Operator::Eq, lit(2)), + Operator::Or, + binary(sum(), Operator::Eq, lit(15)), + ); + let predicate = sum_predicate(expr); + let [guarantee] = predicate.target_literal_guarantees() else { + panic!("expected one guarantee"); + }; + assert_eq!(guarantee.target, Sum); + assert_eq!(guarantee.expr.to_string(), "a@0 + b@1"); + assert_eq!(guarantee.literals.len(), 2); + // The column forms have no place for an expression. + assert!(predicate.literal_guarantees().is_empty()); + assert!(predicate.literal_columns().is_empty()); + // The bounds keep container 0 for the value 2. `contained` rules it + // out. Container 1 holds only nulls. + assert_eq!(predicate.prune(&SumStats).unwrap(), [false, false]); + } + + #[test] + fn two_statistics_expressions_in_one_comparison_are_not_prunable() { + let other_sum = binary(col("b", 1), Operator::Plus, col("c", 2)); + assert!(sum_predicate(binary(sum(), Operator::Gt, other_sum)).always_true()); + } + + #[test] + fn column_without_a_target_is_not_prunable() { + // `SumResolver` gives no target to `c`. So `c` has no statistics, and + // it is not a constant either. + for expr in [ + binary(col("c", 2), Operator::Gt, lit(5)), + binary(sum(), Operator::Gt, col("c", 2)), + binary(col("c", 2), Operator::Eq, lit(5)), + Arc::new(phys_expr::IsNullExpr::new(col("c", 2))), + ] { + assert!(sum_predicate(expr).always_true()); + } + } + + #[test] + #[allow(clippy::allow_attributes, clippy::mutable_key_type)] // ScalarValue as a set key, as in the trait + fn blanket_impl_forwards_columns() { + let stats: &dyn PruningStatistics = &ColumnStats; + // The target holds the name of the column only + let a = ColumnResolver.resolve(&col("a", 7)).unwrap(); + assert_eq!(a, Column::from_name("a")); + let values = HashSet::from([ScalarValue::from(1)]); + + let min = PruningStatisticsSource::min_values(stats, &a).unwrap(); + assert_eq!(min.as_ref(), &Int32Array::from(vec![1, 10])); + let max = PruningStatisticsSource::max_values(stats, &a).unwrap(); + assert_eq!(max.as_ref(), &Int32Array::from(vec![5, 20])); + let nulls = PruningStatisticsSource::null_counts(stats, &a).unwrap(); + assert_eq!(nulls.as_ref(), &UInt64Array::from(vec![3, 4])); + let rows = PruningStatisticsSource::row_counts(stats).unwrap(); + assert_eq!(rows.as_ref(), &UInt64Array::from(vec![100, 200])); + assert_eq!( + PruningStatisticsSource::contained(stats, &a, &values), + Some(BooleanArray::from(vec![None, Some(false)])) + ); + assert_eq!(PruningStatisticsSource::num_containers(stats), 2); + } + + #[test] + fn column_resolver_resolves_only_columns() { + assert!(ColumnResolver.resolve(&sum()).is_none()); + assert!(ColumnResolver.resolve(&lit(1)).is_none()); + } + + #[test] + fn one_source_serves_two_targets() { + // `a > 7` reads the column statistics of `SumStats`. + let columns = column_predicate(binary(col("a", 0), Operator::Gt, lit(7))); + assert_eq!(columns.prune(&SumStats).unwrap(), [false, true]); + assert_eq!( + columns + .prune(&ColumnStats as &dyn PruningStatistics) + .unwrap(), + [false, true] + ); + // `a + b > 7` reads the sum statistics of `SumStats`. + let sums = sum_predicate(binary(sum(), Operator::Gt, lit(7))); + assert_eq!(sums.prune(&SumStats).unwrap(), [false, false]); + } + + #[test] + fn literal_guarantee_passes_the_column_target() { + // The bounds keep the first container for `a = 3`. `contained` rules + // out the second container. + let predicate = column_predicate(binary(col("a", 1), Operator::Eq, lit(3))); + let [guarantee] = predicate.target_literal_guarantees() else { + panic!("expected one guarantee"); + }; + assert_eq!(guarantee.target, Column::from_name("a")); + assert_eq!(predicate.prune(&ColumnStats).unwrap(), [true, false]); + } +} diff --git a/docs/source/library-user-guide/upgrading/index.md b/docs/source/library-user-guide/upgrading/index.md index 686d68bb58c2c..70ad7a83de9f7 100644 --- a/docs/source/library-user-guide/upgrading/index.md +++ b/docs/source/library-user-guide/upgrading/index.md @@ -394,6 +394,39 @@ Row values are unchanged, but schema inspection can differ: code that compares the resulting schema against a hand-written one with `nullable: true` for every field needs to be updated. +### `PruningPredicate` has a statistics target type + +`PruningPredicate`, `PruningPredicateBuilder` and `RequiredColumns` have a new +type parameter with a default. `PruningPredicate` reads statistics by +target: a value of type `T` that names the statistics of one expression. The +default target is `Column`, so code that names `PruningPredicate` and +implements `PruningStatistics` works without changes. + +| Item | Before | Now | +| ---------------------------------- | ---------------------- | ------------------------------------------------- | +| `PruningPredicate` | Not generic | `PruningPredicate` | +| `RequiredColumns` | Not generic | `RequiredColumns` | +| `PruningPredicateBuilder<'a>` | Not generic | `PruningPredicateBuilder<'a, R = ColumnResolver>` | +| `PruningPredicate::prune` argument | `S: PruningStatistics` | `S: PruningStatisticsSource` | + +Every `PruningStatistics` implements `PruningStatisticsSource`. + +Two things can need an update: + +- The two traits have methods of the same name. Code that imports both traits + and calls such a method on a `PruningStatistics` must name the trait, for + example `PruningStatistics::min_values(&statistics, &column)`. +- Code that lets the compiler infer the type of a `RequiredColumns` or a + `PruningPredicate` from nothing else must name the type. + +To prune with the statistics of expressions other than columns: + +1. Implement `StatisticsResolver`. Its `resolve` method returns a target for + each expression that has statistics. +2. Pass the resolver to `PruningPredicateBuilder::with_resolver`. +3. Implement `PruningStatisticsSource` for the statistics source. One + type can implement it for several targets, and `PruningStatistics` too. + ## Past Upgrade Guides The upgrade guides for released versions can be found here: From bd653f150ef1e162889dce29a949a2ccb897e61b Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:53:26 -0800 Subject: [PATCH 5/6] refactor: read Parquet pruning statistics by leaf column The Parquet statistics sources find the leaf column of a predicate column by name, each time the predicate reads a statistic. Row group statistics, bloom filters and the page index each do this in their own way. A name can only identify a top-level column. Resolve each expression of a pruning predicate to a ParquetStatisticsTarget (leaf index and Arrow field) when the predicate is built for a file. The three statistics sources read by target. | Build site | Resolver | |-----------------------------------------|---------------------------------| | Opener, push decoder, inverted predicate | ParquetStatisticsResolver | | Plan display, which has no file | ArrowStatisticsResolver | | Public methods that take a PruningPredicate | Build it again for the file | PagePruningAccessPlanFilter::new has no Parquet schema, so it must build its predicates again for each file. Deprecate it in favor of new_with_parquet_schema. The resolvers accept columns only, so pruning results do not change. Co-Authored-By: Claude Fable 5.2 --- .../datasource-parquet/src/bloom_filter.rs | 120 ++- datafusion/datasource-parquet/src/mod.rs | 2 + .../datasource-parquet/src/opener/mod.rs | 95 +- .../datasource-parquet/src/page_filter.rs | 878 ++++++++++-------- datafusion/datasource-parquet/src/pruning.rs | 52 ++ .../datasource-parquet/src/push_decoder.rs | 21 +- .../src/row_group_filter.rs | 111 ++- datafusion/datasource-parquet/src/source.rs | 2 + .../datasource-parquet/src/statistics_expr.rs | 250 +++++ .../src/statistics_order_tests.rs | 79 +- .../library-user-guide/upgrading/index.md | 20 + 11 files changed, 1119 insertions(+), 511 deletions(-) create mode 100644 datafusion/datasource-parquet/src/pruning.rs create mode 100644 datafusion/datasource-parquet/src/statistics_expr.rs diff --git a/datafusion/datasource-parquet/src/bloom_filter.rs b/datafusion/datasource-parquet/src/bloom_filter.rs index d00d513bb1fed..2cea5d421273e 100644 --- a/datafusion/datasource-parquet/src/bloom_filter.rs +++ b/datafusion/datasource-parquet/src/bloom_filter.rs @@ -8,9 +8,11 @@ use std::collections::{HashMap, HashSet}; +use crate::statistics_expr::ParquetStatisticsTarget; use arrow::array::{ArrayRef, BooleanArray}; use datafusion_common::pruning::PruningStatistics; use datafusion_common::{Column, ScalarValue}; +use datafusion_pruning::PruningStatisticsSource; use parquet::basic::Type; use parquet::bloom_filter::Sbbf; use parquet::data_type::Decimal; @@ -23,6 +25,9 @@ use parquet::data_type::Decimal; pub struct BloomFilterStatistics { /// Per-column Bloom filters keyed by predicate column name. column_sbbf: HashMap, + /// Bloom filters keyed by the index of their Parquet leaf column. A + /// predicate that reads leaf columns finds its filters here. + leaf_sbbf: HashMap, } #[derive(Debug, Clone)] @@ -45,12 +50,13 @@ impl BloomFilterStatistics { pub fn with_capacity(capacity: usize) -> Self { Self { column_sbbf: HashMap::with_capacity(capacity), + leaf_sbbf: HashMap::new(), } } /// Returns true if no per-column Bloom filters have been loaded. pub fn is_empty(&self) -> bool { - self.column_sbbf.is_empty() + self.column_sbbf.is_empty() && self.leaf_sbbf.is_empty() } /// Add a Bloom filter for the specified column, along with the column's @@ -72,6 +78,33 @@ impl BloomFilterStatistics { ); } + /// Returns an empty set with room for the Bloom filters of `capacity` + /// Parquet leaf columns. + pub(crate) fn with_leaf_capacity(capacity: usize) -> Self { + Self { + column_sbbf: HashMap::new(), + leaf_sbbf: HashMap::with_capacity(capacity), + } + } + + /// Add the Bloom filter of the Parquet leaf column with index `leaf`. + pub(crate) fn insert_leaf( + &mut self, + leaf: usize, + sbbf: Sbbf, + ty: Type, + type_length: i32, + ) { + self.leaf_sbbf.insert( + leaf, + ColumnBloomFilter { + sbbf, + physical_type: ty, + type_length, + }, + ); + } + /// Returns `true` if the Bloom filter definitely does not contain any of the given values. /// /// If all values are confirmed absent by the Bloom filter, returns `true`. @@ -178,6 +211,38 @@ impl BloomFilterStatistics { } } +impl ColumnBloomFilter { + /// Use the bloom filter to determine if we are sure this column can not + /// possibly contain `values` + /// + /// The `contained` API returns false if the bloom filters knows that *ALL* + /// of the values in a column are not present. + #[allow(clippy::allow_attributes, clippy::mutable_key_type)] // ScalarValue has interior mutability but is intentionally used as hash key + fn contained(&self, values: &HashSet) -> BooleanArray { + // Bloom filters are probabilistic data structures that can return false + // positives (i.e. it might return true even if the value is not + // present) however, the bloom filter will return `false` if the value is + // definitely not present. + let known_not_present = BloomFilterStatistics::is_known_not_present( + &self.sbbf, + values, + &self.physical_type, + self.type_length, + ); + + let contains = if known_not_present { + Some(false) + } else { + // Given the bloom filter is probabilistic, we can't be sure that + // the row group actually contains the values. Return `None` to + // indicate this uncertainty + None + }; + + BooleanArray::from(vec![contains]) + } +} + impl PruningStatistics for BloomFilterStatistics { fn min_values(&self, _column: &Column) -> Option { None @@ -199,39 +264,44 @@ impl PruningStatistics for BloomFilterStatistics { None } - /// Use bloom filters to determine if we are sure this column can not - /// possibly contain `values` - /// - /// The `contained` API returns false if the bloom filters knows that *ALL* - /// of the values in a column are not present. fn contained( &self, column: &Column, values: &HashSet, ) -> Option { let column_bloom_filter = self.column_sbbf.get(column.name.as_str())?; + Some(column_bloom_filter.contained(values)) + } +} - // Bloom filters are probabilistic data structures that can return false - // positives (i.e. it might return true even if the value is not - // present) however, the bloom filter will return `false` if the value is - // definitely not present. - let known_not_present = Self::is_known_not_present( - &column_bloom_filter.sbbf, - values, - &column_bloom_filter.physical_type, - column_bloom_filter.type_length, - ); +impl PruningStatisticsSource for BloomFilterStatistics { + fn min_values(&self, _target: &ParquetStatisticsTarget) -> Option { + None + } - let contains = if known_not_present { - Some(false) - } else { - // Given the bloom filter is probabilistic, we can't be sure that - // the row group actually contains the values. Return `None` to - // indicate this uncertainty - None - }; + fn max_values(&self, _target: &ParquetStatisticsTarget) -> Option { + None + } + + fn num_containers(&self) -> usize { + 1 + } + + fn null_counts(&self, _target: &ParquetStatisticsTarget) -> Option { + None + } + + fn row_counts(&self) -> Option { + None + } - Some(BooleanArray::from(vec![contains])) + fn contained( + &self, + target: &ParquetStatisticsTarget, + values: &HashSet, + ) -> Option { + let leaf_bloom_filter = self.leaf_sbbf.get(&target.leaf())?; + Some(leaf_bloom_filter.contained(values)) } } diff --git a/datafusion/datasource-parquet/src/mod.rs b/datafusion/datasource-parquet/src/mod.rs index 03eb960b6ab78..341821e9172af 100644 --- a/datafusion/datasource-parquet/src/mod.rs +++ b/datafusion/datasource-parquet/src/mod.rs @@ -22,6 +22,7 @@ mod nested_schema_pruning; mod opener; mod page_filter; mod projection_read_plan; +mod pruning; mod push_decoder; mod reader; mod row_filter; @@ -30,6 +31,7 @@ mod schema_coercion; mod sink; mod sort; pub mod source; +mod statistics_expr; #[cfg(test)] mod statistics_order_tests; mod supported_predicates; diff --git a/datafusion/datasource-parquet/src/opener/mod.rs b/datafusion/datasource-parquet/src/opener/mod.rs index 1866b6ba81992..98abd439b20ba 100644 --- a/datafusion/datasource-parquet/src/opener/mod.rs +++ b/datafusion/datasource-parquet/src/opener/mod.rs @@ -16,11 +16,13 @@ use crate::bloom_filter::BloomFilterStatistics; use crate::decoder_projection::DecoderProjection; use crate::metrics::{ByteProgress, RowFilterSkippedFullyMatchedMetric}; use crate::page_filter::PagePruningAccessPlanFilter; +use crate::pruning::ParquetPruningPredicate; use crate::push_decoder::{ DecoderBuilderConfig, InitialDecoderState, PushDecoderStreamState, RgPlanEntry, RowFilterContext, RowGroupPruner, RowGroupReverser, }; use crate::row_group_filter::{RowGroupAccessPlanFilter, row_group_in_range}; +use crate::statistics_expr::ParquetStatisticsResolver; use crate::{ Int96Coercer, ParquetAccessPlan, ParquetFileMetrics, ParquetFileReaderFactory, ParquetRowSelection, ParquetVirtualColumn, RowGroupAccess, @@ -59,7 +61,9 @@ use datafusion_physical_expr_common::sort_expr::LexOrdering; use datafusion_physical_plan::metrics::{ BaselineMetrics, Count, ExecutionPlanMetricsSet, MetricBuilder, MetricCategory, }; -use datafusion_pruning::{FilePruner, PruningPredicate, PruningPredicateBuilder}; +use datafusion_pruning::{ + FilePruner, PruningPredicate, PruningPredicateBuilder, StatisticsResolver, +}; #[cfg(feature = "parquet_encryption")] use datafusion_common::config::EncryptionFactoryOptions; @@ -74,9 +78,9 @@ use parquet::arrow::arrow_reader::{ ArrowReaderMetadata, ArrowReaderOptions, MaskRunIter, }; use parquet::arrow::async_reader::AsyncFileReader; -use parquet::arrow::parquet_column; use parquet::bloom_filter::Sbbf; use parquet::file::metadata::{PageIndexPolicy, ParquetMetaDataReader, RowGroupMetaData}; +use parquet::schema::types::SchemaDescriptor; /// Morselizer-level state for virtual columns, precomputed once per scan /// partition so each file skips the validator walks, `null_replacements` @@ -515,7 +519,7 @@ struct MetadataLoadedParquetOpen { /// specialized for the files specific schema. struct FiltersPreparedParquetOpen { loaded: MetadataLoadedParquetOpen, - pruning_predicate: Option>, + pruning_predicate: Option>, page_pruning_predicate: Option>, } @@ -1226,9 +1230,11 @@ impl MetadataLoadedParquetOpen { } // Build predicates for this specific file + let parquet_schema = reader_metadata.metadata().file_metadata().schema_descr(); let pruning_predicate = build_pruning_predicates( prepared.predicate.as_ref(), &physical_file_schema, + ParquetStatisticsResolver::new(&physical_file_schema, parquet_schema), &prepared.predicate_creation_errors, prepared.max_in_list_size, ); @@ -1239,6 +1245,7 @@ impl MetadataLoadedParquetOpen { let p = build_page_pruning_predicate( predicate, &physical_file_schema, + parquet_schema, prepared.max_in_list_size, ); (p.filter_number() > 0).then_some(p) @@ -1319,7 +1326,7 @@ impl FiltersPreparedParquetOpen { // If there is a predicate that can be evaluated against the metadata if let Some(predicate) = self.pruning_predicate.as_ref().map(|p| p.as_ref()) { if prepared.enable_row_group_stats_pruning { - row_groups.prune_by_statistics_with_metadata( + row_groups.prune_by_leaf_statistics( &prepared.physical_file_schema, &file_metadata, predicate, @@ -1458,17 +1465,16 @@ 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 + .leaf_indexes(arrow_schema, parquet_schema) + .into_iter() + .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. @@ -1524,21 +1530,21 @@ impl RowGroupsPrunedParquetOpen { reader_metadata, ); - let parquet_columns = predicate - .literal_columns() + // The leaf column of each target with a literal guarantee. + // Targets that read the same leaf share its Bloom filter. + let parquet_schema = builder.parquet_schema(); + let mut bloom_filter_leaves = vec![]; + for guarantee in predicate.target_literal_guarantees() { + let leaf = guarantee.target.leaf(); + if !bloom_filter_leaves.contains(&leaf) { + bloom_filter_leaves.push(leaf); + } + } + let parquet_columns = bloom_filter_leaves .into_iter() - .filter_map(|column_name| { - let (column_idx, _) = parquet_column( - builder.parquet_schema(), - &prepared.physical_file_schema, - &column_name, - )?; - Some(( - column_name, - column_idx, - builder.parquet_schema().column(column_idx).physical_type(), - builder.parquet_schema().column(column_idx).type_length(), - )) + .map(|leaf| { + let descr = parquet_schema.column(leaf); + (leaf, descr.physical_type(), descr.type_length()) }) .collect::>(); @@ -1551,12 +1557,10 @@ impl RowGroupsPrunedParquetOpen { continue; } let mut bloom_filter_stats = - BloomFilterStatistics::with_capacity(parquet_columns.len()); + BloomFilterStatistics::with_leaf_capacity(parquet_columns.len()); let mut pruned = false; - for (column_name, column_idx, physical_type, type_length) in - &parquet_columns - { + for (column_idx, physical_type, type_length) in &parquet_columns { let bf: Sbbf = match builder .get_row_group_column_bloom_filter(idx, *column_idx) .await @@ -1570,8 +1574,8 @@ impl RowGroupsPrunedParquetOpen { } }; - bloom_filter_stats.insert( - column_name.clone(), + bloom_filter_stats.insert_leaf( + *column_idx, bf, *physical_type, *type_length, @@ -2098,24 +2102,34 @@ fn create_initial_plan( pub(crate) fn build_page_pruning_predicate( predicate: &Arc, file_schema: &SchemaRef, + parquet_schema: &SchemaDescriptor, max_in_list_size: usize, ) -> Arc { Arc::new(PagePruningAccessPlanFilter::new_with_max_in_list_size( predicate, file_schema, + parquet_schema, max_in_list_size, )) } -pub(crate) fn build_pruning_predicates( +/// Builds the pruning predicate of the files with `file_schema`. +/// +/// | `resolver` | The predicate | +/// |-------------------------------|-------------------------------------------------------| +/// | [`ParquetStatisticsResolver`] | Prunes the file that the resolver was created for | +/// | `ArrowStatisticsResolver` | Shows which statistics a scan reads. It prunes nothing | +pub(crate) fn build_pruning_predicates( predicate: Option<&Arc>, file_schema: &SchemaRef, + resolver: R, predicate_creation_errors: &Count, max_in_list_size: usize, -) -> Option> { +) -> Option>> { let predicate = predicate.as_ref()?; PruningPredicateBuilder::new() .with_file_schema(Arc::clone(file_schema)) + .with_resolver(resolver) .with_error_counter(predicate_creation_errors) .with_max_in_list_size(max_in_list_size) .build(Arc::clone(predicate)) @@ -2427,7 +2441,12 @@ mod test { ); let page_pruning_predicate = predicate.map(|expr| { let predicate = logical2physical(&expr, &arrow_schema); - build_page_pruning_predicate(&predicate, &arrow_schema, MAX_IN_LIST_SIZE) + build_page_pruning_predicate( + &predicate, + &arrow_schema, + metadata.file_metadata().schema_descr(), + MAX_IN_LIST_SIZE, + ) }); let store: Arc = Arc::new(InMemory::new()); diff --git a/datafusion/datasource-parquet/src/page_filter.rs b/datafusion/datasource-parquet/src/page_filter.rs index c49a8b9c0f6e0..b48bd2b40b345 100644 --- a/datafusion/datasource-parquet/src/page_filter.rs +++ b/datafusion/datasource-parquet/src/page_filter.rs @@ -4,11 +4,14 @@ //! Contains code to filter entire pages +use std::borrow::Cow; use std::collections::HashSet; use std::sync::Arc; use super::metrics::ParquetFileMetrics; use crate::metadata::has_untrusted_min_max_order; +use crate::pruning::{ParquetPruningPredicate, bind_to_file, build_inverted_predicate}; +use crate::statistics_expr::{ParquetStatisticsResolver, ParquetStatisticsTarget}; use crate::{ParquetAccessPlan, RowGroupAccess}; use arrow::array::BooleanArray; @@ -17,9 +20,11 @@ use arrow::{ datatypes::{Schema, SchemaRef}, }; use datafusion_common::ScalarValue; -use datafusion_common::pruning::PruningStatistics; use datafusion_physical_expr::{PhysicalExpr, split_conjunction}; -use datafusion_pruning::{MAX_IN_LIST_SIZE, PruningPredicate, PruningPredicateBuilder}; +use datafusion_pruning::{ + ColumnResolver, MAX_IN_LIST_SIZE, PruningPredicate, PruningPredicateBuilder, + PruningStatisticsSource, StatisticsResolver, +}; use log::{debug, trace}; use parquet::arrow::arrow_reader::statistics::StatisticsConverter; @@ -100,12 +105,51 @@ use parquet::{ pub struct PagePruningAccessPlanFilter { /// single column predicates (e.g. (`col = 5`) extracted from the overall /// predicate. Must all be true for a row to be included in the result. - predicates: Vec, + predicates: PagePredicates, /// Whether every original conjunct can be evaluated from one column's page /// statistics. Otherwise no range can be classified as fully matched. all_predicates_supported: bool, } +/// The predicates of a [`PagePruningAccessPlanFilter`]. +/// +/// | Variant | Built by | Bound to a file | +/// |-----------|---------------------------|-----------------------------------------| +/// | `Unbound` | `new` (deprecated) | Each time the filter prunes a file | +/// | `Bound` | `new_with_parquet_schema` | When the filter is built | +/// +/// Only `Bound` predicates prune. See [`PagePredicates::bound`]. +#[derive(Debug)] +enum PagePredicates { + Unbound(Vec), + Bound(Vec), +} + +impl PagePredicates { + /// Returns the predicates for the file with these schemas, and whether + /// page pruning can use every one of them. + fn bound( + &self, + arrow_schema: &Schema, + parquet_schema: &SchemaDescriptor, + ) -> (Cow<'_, [ParquetPruningPredicate]>, bool) { + match self { + Self::Bound(predicates) => (Cow::Borrowed(predicates), true), + Self::Unbound(predicates) => { + let bound: Vec<_> = predicates + .iter() + .filter_map(|predicate| { + bind_to_file(predicate, arrow_schema, parquet_schema) + }) + .filter(|predicate| single_target(predicate).is_some()) + .collect(); + let all_bound = bound.len() == predicates.len(); + (Cow::Owned(bound), all_bound) + } + } + } +} + /// Result of applying page-index pruning to a [`ParquetAccessPlan`]. pub(crate) struct PagePruningResult { pub(crate) access_plan: ParquetAccessPlan, @@ -133,53 +177,49 @@ impl PagePruningResult { impl PagePruningAccessPlanFilter { /// Create a new [`PagePruningAccessPlanFilter`] from a physical /// expression, using the default `IN (...)` pruning limit. + /// + /// The filter builds its predicates again for each file that it prunes, + /// because it does not know the Parquet schema of the file here. + #[deprecated( + since = "57.0.0", + note = "Use `PagePruningAccessPlanFilter::new_with_parquet_schema`, which builds the predicates one time" + )] #[expect(clippy::needless_pass_by_value)] pub fn new(expr: &Arc, schema: SchemaRef) -> Self { - Self::new_with_max_in_list_size(expr, &schema, MAX_IN_LIST_SIZE) + let (predicates, all_predicates_supported) = + build_page_predicates(expr, &schema, &ColumnResolver, MAX_IN_LIST_SIZE); + Self { + predicates: PagePredicates::Unbound(predicates), + all_predicates_supported, + } + } + + /// Create a new [`PagePruningAccessPlanFilter`] from a physical + /// expression, for the Parquet file with these schemas. It uses the + /// default `IN (...)` pruning limit. + /// + /// The filter prunes with the statistics of columns and of struct fields. + /// Use it only with the page index of a file that has `parquet_schema`. + pub fn new_with_parquet_schema( + expr: &Arc, + schema: &SchemaRef, + parquet_schema: &SchemaDescriptor, + ) -> Self { + Self::new_with_max_in_list_size(expr, schema, parquet_schema, MAX_IN_LIST_SIZE) } /// Create a page filter using the same `IN (...)` limit as row-group pruning. pub(crate) fn new_with_max_in_list_size( expr: &Arc, schema: &SchemaRef, + parquet_schema: &SchemaDescriptor, max_in_list_size: usize, ) -> Self { - let mut predicates = vec![]; - let mut all_predicates_supported = true; - - // Ordinary pruning can use any supported conjunct. Fully matched - // ranges require every original conjunct to be supported. - for predicate in split_conjunction(expr) { - let pp = match PruningPredicateBuilder::new() - .with_file_schema(Arc::clone(schema)) - .with_max_in_list_size(max_in_list_size) - .try_build(Arc::clone(predicate)) - { - Ok(pp) => pp, - Err(e) => { - debug!("Ignoring error creating page pruning predicate: {e}"); - all_predicates_supported = false; - continue; - } - }; - - if pp.always_true() { - debug!("Ignoring always true page pruning predicate: {predicate}"); - all_predicates_supported = false; - continue; - } - - if single_column(&pp).is_none() { - debug!("Ignoring multi-column page pruning predicate: {predicate}"); - all_predicates_supported = false; - continue; - } - - predicates.push(pp); - } - + let resolver = ParquetStatisticsResolver::new(schema, parquet_schema); + let (predicates, all_predicates_supported) = + build_page_predicates(expr, schema, &resolver, max_in_list_size); Self { - predicates, + predicates: PagePredicates::Bound(predicates), all_predicates_supported, } } @@ -209,288 +249,368 @@ impl PagePruningAccessPlanFilter { /// to the parquet page index, if any. pub(crate) fn prune_plan_with_page_index_and_metrics( &self, - mut access_plan: ParquetAccessPlan, + access_plan: ParquetAccessPlan, arrow_schema: &Schema, parquet_schema: &SchemaDescriptor, parquet_metadata: &ParquetMetaData, file_metrics: &ParquetFileMetrics, limit: Option, ) -> PagePruningResult { - // scoped timer updates on drop - let _timer_guard = file_metrics.page_index_eval_time.timer(); - if self.predicates.is_empty() { - return PagePruningResult::new(access_plan, 0, 0); + let (predicates, all_bound) = self.predicates.bound(arrow_schema, parquet_schema); + prune_plan_with_page_index( + &predicates, + self.all_predicates_supported && all_bound, + access_plan, + arrow_schema, + parquet_schema, + parquet_metadata, + file_metrics, + limit, + ) + } + + /// Returns the number of filters in the [`PagePruningAccessPlanFilter`] + pub fn filter_number(&self) -> usize { + match &self.predicates { + PagePredicates::Unbound(predicates) => predicates.len(), + PagePredicates::Bound(predicates) => predicates.len(), } + } - let page_index_predicates = &self.predicates; - let groups = parquet_metadata.row_groups(); + /// Returns the index of the leaf column that each page pruning predicate + /// reads in the file with these schemas. A predicate without a leaf + /// column in the file has no entry. + pub(crate) fn leaf_indexes( + &self, + arrow_schema: &Schema, + parquet_schema: &SchemaDescriptor, + ) -> Vec { + let (predicates, _) = self.predicates.bound(arrow_schema, parquet_schema); + predicates + .iter() + .filter_map(|predicate| Some(single_target(predicate)?.leaf())) + .collect() + } +} - if groups.is_empty() { - return PagePruningResult::new(access_plan, 0, 0); +/// Splits `expr` into the conjuncts that page pruning can use, and builds a +/// predicate for each one. +/// +/// Also returns whether page pruning can use every conjunct. Ordinary pruning +/// can use any supported conjunct. Fully matched ranges require every +/// original conjunct to be supported. +fn build_page_predicates( + expr: &Arc, + schema: &SchemaRef, + resolver: &R, + max_in_list_size: usize, +) -> (Vec>, bool) +where + R: StatisticsResolver, + R::Target: PartialEq, +{ + let mut predicates = vec![]; + let mut all_predicates_supported = true; + + for predicate in split_conjunction(expr) { + let pp = match PruningPredicateBuilder::new() + .with_file_schema(Arc::clone(schema)) + .with_resolver(resolver) + .with_max_in_list_size(max_in_list_size) + .try_build(Arc::clone(predicate)) + { + Ok(pp) => pp, + Err(e) => { + debug!("Ignoring error creating page pruning predicate: {e}"); + all_predicates_supported = false; + continue; + } + }; + + if pp.always_true() { + debug!("Ignoring always true page pruning predicate: {predicate}"); + all_predicates_supported = false; + continue; } - if !parquet_metadata + if single_target(&pp).is_none() { + debug!("Ignoring multi-column page pruning predicate: {predicate}"); + all_predicates_supported = false; + continue; + } + + predicates.push(pp); + } + + (predicates, all_predicates_supported) +} + +/// Applies `predicates` to the page index, see +/// [`PagePruningAccessPlanFilter::prune_plan_with_page_index_and_metrics`]. +/// +/// `parquet_schema` is the schema of the file that the predicates were built +/// for. +#[expect(clippy::too_many_arguments)] +fn prune_plan_with_page_index( + predicates: &[ParquetPruningPredicate], + all_predicates_supported: bool, + mut access_plan: ParquetAccessPlan, + arrow_schema: &Schema, + parquet_schema: &SchemaDescriptor, + parquet_metadata: &ParquetMetaData, + file_metrics: &ParquetFileMetrics, + limit: Option, +) -> PagePruningResult { + // scoped timer updates on drop + let _timer_guard = file_metrics.page_index_eval_time.timer(); + if predicates.is_empty() { + return PagePruningResult::new(access_plan, 0, 0); + } + + let page_index_predicates = predicates; + let groups = parquet_metadata.row_groups(); + + if groups.is_empty() { + return PagePruningResult::new(access_plan, 0, 0); + } + + if !parquet_metadata + .page_index() + .is_some_and(|page_index| page_index.is_complete()) + { + debug!( + "Can not prune pages due to lack of indexes. Have offset: {}, column index: {}", + parquet_metadata + .page_index() + .is_some_and(|page_index| page_index.has_offset_indexes()), + parquet_metadata + .page_index() + .is_some_and(|page_index| page_index.has_column_indexes()) + ); + return PagePruningResult::new(access_plan, 0, 0); + } + + // Build inverse predicates only for unordered LIMIT queries. Ordinary + // page pruning does not need them. + let inverted_predicates: Option> = if limit.is_some() + && all_predicates_supported + { + predicates + .iter() + .map(|predicate| { + let inverted = + build_inverted_predicate(predicate, arrow_schema, parquet_schema)?; + single_target(&inverted).is_some().then_some(inverted) + }) + .collect() + } else { + None + }; + + // track the total number of rows that should be skipped + let mut total_skip = 0; + // track the total number of rows that should not be skipped + let mut total_select = 0; + // track the total number of pages that should be skipped + let mut total_pages_skip = 0; + // track the total number of pages that should not be skipped + let mut total_pages_select = 0; + // track pages for which page-index pruning was skipped because the + // containing row group was already proven fully matched by statistics + let mut total_pages_skipped_by_fully_matched = 0; + let mut fully_matched_page_selections = inverted_predicates + .as_ref() + .map(|_| vec![None; groups.len()]); + let mut guaranteed_rows = 0; + + // for each row group specified in the access plan + let row_group_indexes = access_plan.row_group_indexes(); + // Page index sets, reused across row groups + let mut matched_pages_in_group: HashSet = HashSet::new(); + let mut matched_pages_indexes: HashSet = HashSet::new(); + for row_group_index in row_group_indexes { + // Skip page pruning for fully matched row groups: all rows are + // known to satisfy the predicate, so page-level pruning is wasted work. + if access_plan.is_fully_matched(row_group_index) { + let page_count = fully_matched_page_count(row_group_index, parquet_metadata); + total_pages_skipped_by_fully_matched += page_count; + guaranteed_rows += selected_rows_in_access( + &access_plan.inner()[row_group_index], + &groups[row_group_index], + ); + + continue; + } + // The selection for this particular row group + let mut overall_selection = None; + + let total_pages_in_group = parquet_metadata .page_index() - .is_some_and(|page_index| page_index.is_complete()) - { + .and_then(|page_index| page_index.offset_index(row_group_index, 0)) + .map_or(0, |offset_index| offset_index.page_locations().len()); + // stores the indexes of the matched pages + matched_pages_in_group.clear(); + matched_pages_in_group.extend(0..total_pages_in_group); + + for predicate in page_index_predicates { + let selection = prune_pages_for_predicate( + row_group_index, + predicate, + parquet_schema, + parquet_metadata, + file_metrics, + ); + + let Some((selection, pages)) = selection else { + trace!("No pages pruned in prune_pages_in_one_row_group"); + continue; + }; + debug!( - "Can not prune pages due to lack of indexes. Have offset: {}, column index: {}", - parquet_metadata - .page_index() - .is_some_and(|page_index| page_index.has_offset_indexes()), - parquet_metadata - .page_index() - .is_some_and(|page_index| page_index.has_column_indexes()) + "Use filter and page index to create RowSelection {:?} from predicate: {:?}", + selection, + predicate.predicate_expr(), ); - return PagePruningResult::new(access_plan, 0, 0); + + matched_pages_indexes.clear(); + matched_pages_indexes + .extend(pages.into_iter().enumerate().filter(|x| x.1).map(|x| x.0)); + matched_pages_in_group.retain(|x| matched_pages_indexes.contains(x)); + + overall_selection = update_selection(overall_selection, selection); + + // if the overall selection has ruled out all rows, no need to + // continue with the other predicates + let selects_any = overall_selection + .as_ref() + .map(|selection| selection.selects_any()) + .unwrap_or(true); + + if !selects_any { + break; + } } - // Build inverse predicates only for unordered LIMIT queries. Ordinary - // page pruning does not need them. - let inverted_predicates: Option> = - if limit.is_some() && self.all_predicates_supported { - self.predicates - .iter() - .map(|predicate| { - let inverted = PruningPredicateBuilder::new() - .with_file_schema(Arc::clone(predicate.schema())) - .with_max_in_list_size(predicate.max_in_list_size()) - .try_build_inverse(Arc::clone(predicate.orig_expr())) - .ok() - .flatten()?; - single_column(&inverted).is_some().then_some(inverted) - }) - .collect() + if let Some(overall_selection) = overall_selection { + let rows_selected = overall_selection.row_count(); + if rows_selected > 0 { + let rows_skipped = overall_selection.skipped_row_count(); + trace!( + "Overall selection from predicate skipped {rows_skipped}, selected {rows_selected}: {overall_selection:?}" + ); + total_skip += rows_skipped; + total_select += rows_selected; + access_plan.scan_selection(row_group_index, overall_selection) } else { - None - }; - - // track the total number of rows that should be skipped - let mut total_skip = 0; - // track the total number of rows that should not be skipped - let mut total_select = 0; - // track the total number of pages that should be skipped - let mut total_pages_skip = 0; - // track the total number of pages that should not be skipped - let mut total_pages_select = 0; - // track pages for which page-index pruning was skipped because the - // containing row group was already proven fully matched by statistics - let mut total_pages_skipped_by_fully_matched = 0; - let mut fully_matched_page_selections = inverted_predicates - .as_ref() - .map(|_| vec![None; groups.len()]); - let mut guaranteed_rows = 0; - - // for each row group specified in the access plan - let row_group_indexes = access_plan.row_group_indexes(); - // Page index sets, reused across row groups - let mut matched_pages_in_group: HashSet = HashSet::new(); - let mut matched_pages_indexes: HashSet = HashSet::new(); - for row_group_index in row_group_indexes { - // Skip page pruning for fully matched row groups: all rows are - // known to satisfy the predicate, so page-level pruning is wasted work. - if access_plan.is_fully_matched(row_group_index) { - let page_count = - fully_matched_page_count(row_group_index, parquet_metadata); - total_pages_skipped_by_fully_matched += page_count; - guaranteed_rows += selected_rows_in_access( - &access_plan.inner()[row_group_index], - &groups[row_group_index], + // Selection skips all rows, so skip the entire row group + let rows_skipped = groups[row_group_index].num_rows() as usize; + access_plan.skip(row_group_index); + total_skip += rows_skipped; + trace!( + "Overall selection from predicate is empty, \ + skipping all {rows_skipped} rows in row group {row_group_index}" ); - - continue; } - // The selection for this particular row group - let mut overall_selection = None; + } else { + total_select += + parquet_metadata.row_group(row_group_index).num_rows() as usize; + } - let total_pages_in_group = parquet_metadata - .page_index() - .and_then(|page_index| page_index.offset_index(row_group_index, 0)) - .map_or(0, |offset_index| offset_index.page_locations().len()); - // stores the indexes of the matched pages - matched_pages_in_group.clear(); - matched_pages_in_group.extend(0..total_pages_in_group); - - for predicate in page_index_predicates { - let selection = prune_pages_for_predicate( + if guaranteed_rows < limit.unwrap_or(0) + && access_plan.should_scan(row_group_index) + && let Some(inverted_predicates) = &inverted_predicates + { + let mut fully_matched_selection = None; + let mut complete = true; + + for predicate in inverted_predicates { + let Some((selection, _)) = prune_pages_for_predicate( row_group_index, predicate, - arrow_schema, parquet_schema, parquet_metadata, file_metrics, - ); - - let Some((selection, pages)) = selection else { - trace!("No pages pruned in prune_pages_in_one_row_group"); - continue; + ) else { + complete = false; + break; }; - debug!( - "Use filter and page index to create RowSelection {:?} from predicate: {:?}", - selection, - predicate.predicate_expr(), + fully_matched_selection = update_selection( + fully_matched_selection, + complement_selection(selection), ); - matched_pages_indexes.clear(); - matched_pages_indexes - .extend(pages.into_iter().enumerate().filter(|x| x.1).map(|x| x.0)); - matched_pages_in_group.retain(|x| matched_pages_indexes.contains(x)); - - overall_selection = update_selection(overall_selection, selection); - - // if the overall selection has ruled out all rows, no need to - // continue with the other predicates - let selects_any = overall_selection + // An empty intersection cannot gain rows from later conjuncts. + if !fully_matched_selection .as_ref() - .map(|selection| selection.selects_any()) - .unwrap_or(true); - - if !selects_any { + .is_some_and(|selection| selection.selects_any()) + { break; } } - if let Some(overall_selection) = overall_selection { - let rows_selected = overall_selection.row_count(); - if rows_selected > 0 { - let rows_skipped = overall_selection.skipped_row_count(); - trace!( - "Overall selection from predicate skipped {rows_skipped}, selected {rows_selected}: {overall_selection:?}" - ); - total_skip += rows_skipped; - total_select += rows_selected; - access_plan.scan_selection(row_group_index, overall_selection) - } else { - // Selection skips all rows, so skip the entire row group - let rows_skipped = groups[row_group_index].num_rows() as usize; - access_plan.skip(row_group_index); - total_skip += rows_skipped; - trace!( - "Overall selection from predicate is empty, \ - skipping all {rows_skipped} rows in row group {row_group_index}" - ); - } - } else { - total_select += - parquet_metadata.row_group(row_group_index).num_rows() as usize; - } - - if guaranteed_rows < limit.unwrap_or(0) - && access_plan.should_scan(row_group_index) - && let Some(inverted_predicates) = &inverted_predicates + if complete + && let Some(selections) = fully_matched_page_selections.as_mut() + && let Some(selection) = fully_matched_selection { - let mut fully_matched_selection = None; - let mut complete = true; - - for predicate in inverted_predicates { - let Some((selection, _)) = prune_pages_for_predicate( - row_group_index, - predicate, - arrow_schema, - parquet_schema, - parquet_metadata, - file_metrics, - ) else { - complete = false; - break; - }; - - fully_matched_selection = update_selection( - fully_matched_selection, - complement_selection(selection), - ); - - // An empty intersection cannot gain rows from later conjuncts. - if !fully_matched_selection - .as_ref() - .is_some_and(|selection| selection.selects_any()) - { - break; + guaranteed_rows += match &access_plan.inner()[row_group_index] { + RowGroupAccess::Skip => 0, + RowGroupAccess::Scan => selection.row_count(), + RowGroupAccess::Selection(existing) => { + existing.intersection(&selection).row_count() } - } - - if complete - && let Some(selections) = fully_matched_page_selections.as_mut() - && let Some(selection) = fully_matched_selection - { - guaranteed_rows += match &access_plan.inner()[row_group_index] { - RowGroupAccess::Skip => 0, - RowGroupAccess::Scan => selection.row_count(), - RowGroupAccess::Selection(existing) => { - existing.intersection(&selection).row_count() - } - }; - selections[row_group_index] = Some(selection); - } + }; + selections[row_group_index] = Some(selection); } - - let pages_matched = matched_pages_in_group.len(); - total_pages_select += pages_matched; - total_pages_skip += total_pages_in_group - pages_matched; - } - - file_metrics.page_index_rows_pruned.add_pruned(total_skip); - file_metrics - .page_index_rows_pruned - .add_matched(total_select); - file_metrics - .page_index_pages_pruned - .add_pruned(total_pages_skip); - file_metrics - .page_index_pages_pruned - .add_matched(total_pages_select); - - let mut limit_pruned_rows = 0; - if let Some(limit) = limit - && let Some(fully_matched_page_selections) = - fully_matched_page_selections.as_deref() - && let Some((limit_plan, pruned_rows, pruned_row_groups)) = limit_pruned_plan( - &access_plan, - fully_matched_page_selections, - limit, - groups, - ) - { - access_plan = limit_plan; - limit_pruned_rows = pruned_rows; - file_metrics - .limit_pruned_row_groups - .add_pruned(pruned_row_groups); } - PagePruningResult::new( - access_plan, - total_pages_skipped_by_fully_matched, - limit_pruned_rows, - ) + let pages_matched = matched_pages_in_group.len(); + total_pages_select += pages_matched; + total_pages_skip += total_pages_in_group - pages_matched; } - /// Returns the number of filters in the [`PagePruningAccessPlanFilter`] - pub fn filter_number(&self) -> usize { - self.predicates.len() + file_metrics.page_index_rows_pruned.add_pruned(total_skip); + file_metrics + .page_index_rows_pruned + .add_matched(total_select); + file_metrics + .page_index_pages_pruned + .add_pruned(total_pages_skip); + file_metrics + .page_index_pages_pruned + .add_matched(total_pages_select); + + let mut limit_pruned_rows = 0; + if let Some(limit) = limit + && let Some(fully_matched_page_selections) = + fully_matched_page_selections.as_deref() + && let Some((limit_plan, pruned_rows, pruned_row_groups)) = + limit_pruned_plan(&access_plan, fully_matched_page_selections, limit, groups) + { + access_plan = limit_plan; + limit_pruned_rows = pruned_rows; + file_metrics + .limit_pruned_row_groups + .add_pruned(pruned_row_groups); } - /// 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 { - self.predicates - .iter() - .filter_map(single_column) - .map(|c| c.name.as_str()) - } + PagePruningResult::new( + access_plan, + total_pages_skipped_by_fully_matched, + limit_pruned_rows, + ) } -/// Returns the column if every statistic that `predicate` requires is of that -/// column. Returns `None` if the predicate reads several columns or none. +/// Returns the target of every statistic that `predicate` reads. Returns +/// `None` if the predicate reads the statistics of several targets, or of +/// none. /// -/// The pages of each column have their own row boundaries. So page pruning can -/// evaluate a predicate only on the pages of one column. -fn single_column(predicate: &PruningPredicate) -> Option<&datafusion_common::Column> { - let mut columns = predicate.required_columns().targets(); - let first = columns.next()?; - columns.all(|c| c == first).then_some(first) +/// The pages of each leaf column have their own row boundaries. So page +/// pruning can evaluate a predicate only on the pages of one leaf column. +fn single_target(predicate: &PruningPredicate) -> Option<&T> { + let mut targets = predicate.required_columns().targets(); + let first = targets.next()?; + targets.all(|target| target == first).then_some(first) } fn update_selection( @@ -607,8 +727,7 @@ fn fully_matched_page_count( fn prune_pages_for_predicate( row_group_index: usize, - predicate: &PruningPredicate, - arrow_schema: &Schema, + predicate: &ParquetPruningPredicate, parquet_schema: &SchemaDescriptor, parquet_metadata: &ParquetMetaData, metrics: &ParquetFileMetrics, @@ -616,22 +735,16 @@ fn prune_pages_for_predicate( #[cfg(test)] tests::PAGE_PREDICATE_CALLS.set(tests::PAGE_PREDICATE_CALLS.get() + 1); - let column = single_column(predicate)?; - let converter = - match StatisticsConverter::try_new(&column.name, arrow_schema, parquet_schema) { - Ok(converter) => converter, - Err(e) => { - debug!( - "Could not create statistics converter for column {}: {e}", - column.name - ); - return None; - } - }; + let target = single_target(predicate)?; + let Some(converter) = target.statistics_converter(parquet_schema) else { + debug!("Could not create statistics converter for {target:?}"); + return None; + }; prune_pages_in_one_row_group( row_group_index, predicate, + target, converter, parquet_metadata, metrics, @@ -648,13 +761,18 @@ fn prune_pages_for_predicate( /// page information is not present. fn prune_pages_in_one_row_group( row_group_index: usize, - pruning_predicate: &PruningPredicate, + pruning_predicate: &ParquetPruningPredicate, + target: &ParquetStatisticsTarget, converter: StatisticsConverter<'_>, parquet_metadata: &ParquetMetaData, metrics: &ParquetFileMetrics, ) -> Option<(RowSelection, Vec)> { - let pruning_stats = - PagesPruningStatistics::try_new(row_group_index, converter, parquet_metadata)?; + let pruning_stats = PagesPruningStatistics::try_new( + row_group_index, + converter, + target, + parquet_metadata, + )?; // Each element in values is a boolean indicating whether the page may have // values that match the predicate (true) or could not possibly have values @@ -708,7 +826,7 @@ fn prune_pages_in_one_row_group( Some((RowSelection::from(vec), values)) } -/// Implement [`PruningStatistics`] for one column's [`PageIndexProvider`] +/// Implement [`PruningStatisticsSource`] for one leaf column's [`PageIndexProvider`] #[derive(Debug)] struct PagesPruningStatistics<'a> { row_group_index: usize, @@ -717,6 +835,10 @@ struct PagesPruningStatistics<'a> { page_index: &'a dyn PageIndexProvider, page_offsets: &'a Vec, trusted_min_max: bool, + /// The target of the leaf column whose pages these statistics describe. + /// The pages of another leaf column have other row boundaries, so these + /// statistics answer for this target only. + target: &'a ParquetStatisticsTarget, } impl<'a> PagesPruningStatistics<'a> { @@ -728,6 +850,7 @@ impl<'a> PagesPruningStatistics<'a> { fn try_new( row_group_index: usize, converter: StatisticsConverter<'a>, + target: &'a ParquetStatisticsTarget, parquet_metadata: &'a ParquetMetaData, ) -> Option { let Some(parquet_column_index) = converter.parquet_column_index() else { @@ -768,6 +891,7 @@ impl<'a> PagesPruningStatistics<'a> { page_index, page_offsets, trusted_min_max, + target, }) } @@ -792,9 +916,9 @@ impl<'a> PagesPruningStatistics<'a> { Some(vec) } } -impl PruningStatistics for PagesPruningStatistics<'_> { - fn min_values(&self, _column: &datafusion_common::Column) -> Option { - if !self.trusted_min_max { +impl PruningStatisticsSource for PagesPruningStatistics<'_> { + fn min_values(&self, target: &ParquetStatisticsTarget) -> Option { + if !self.trusted_min_max || target != self.target { return None; } match self @@ -809,8 +933,8 @@ impl PruningStatistics for PagesPruningStatistics<'_> { } } - fn max_values(&self, _column: &datafusion_common::Column) -> Option { - if !self.trusted_min_max { + fn max_values(&self, target: &ParquetStatisticsTarget) -> Option { + if !self.trusted_min_max || target != self.target { return None; } match self @@ -829,7 +953,10 @@ impl PruningStatistics for PagesPruningStatistics<'_> { self.page_offsets.len() } - fn null_counts(&self, _column: &datafusion_common::Column) -> Option { + fn null_counts(&self, target: &ParquetStatisticsTarget) -> Option { + if target != self.target { + return None; + } match self .converter .data_page_null_counts(self.page_index, [&self.row_group_index]) @@ -858,7 +985,7 @@ impl PruningStatistics for PagesPruningStatistics<'_> { fn contained( &self, - _column: &datafusion_common::Column, + _target: &ParquetStatisticsTarget, _values: &HashSet, ) -> Option { None @@ -888,45 +1015,6 @@ mod tests { pub(super) static PAGE_PREDICATE_CALLS: std::cell::Cell = const { std::cell::Cell::new(0) }; } - #[test] - fn single_column_requires_one_column() { - let schema = Arc::new(Schema::new(vec![ - Field::new("a", DataType::Int32, true), - Field::new("b", DataType::Int32, true), - ])); - let cmp = |name: &str, idx, op| -> Arc { - Arc::new(BinaryExpr::new( - Arc::new(Column::new(name, idx)), - op, - lit(1), - )) - }; - let one: Arc = Arc::new(BinaryExpr::new( - cmp("a", 0, Operator::Gt), - Operator::And, - cmp("a", 0, Operator::Lt), - )); - let pp = PruningPredicateBuilder::new() - .with_file_schema(Arc::clone(&schema)) - .try_build(one) - .unwrap(); - assert_eq!( - single_column(&pp), - Some(&datafusion_common::Column::from_name("a")) - ); - - let two: Arc = Arc::new(BinaryExpr::new( - cmp("a", 0, Operator::Gt), - Operator::And, - cmp("b", 1, Operator::Lt), - )); - let pp = PruningPredicateBuilder::new() - .with_file_schema(schema) - .try_build(two) - .unwrap(); - assert_eq!(single_column(&pp), None); - } - #[test] fn inverse_pruning_short_circuits() { // Each row group has three two-row pages. Only the middle page can @@ -981,39 +1069,52 @@ mod tests { Operator::And, Arc::new(BinaryExpr::new(column, Operator::Lt, lit(20i32))), )); - let filter = PagePruningAccessPlanFilter::new(&expr, Arc::clone(&schema)); - let mut plan = ParquetAccessPlan::new_all(3); - plan.scan_selection( - 0, - vec![ - RowSelector::select(selected), - RowSelector::skip(6 - selected), - ] - .into(), - ); - if fully_matched { - plan.mark_fully_matched(0); - } - let metrics = - ParquetFileMetrics::new(0, "test", &ExecutionPlanMetricsSet::new()); - PAGE_PREDICATE_CALLS.set(0); - let result = filter.prune_plan_with_page_index_and_metrics( - plan, + // A filter bound to the file when it is built, and a filter bound + // each time it prunes. They prune the same pages. + let leaves = PagePruningAccessPlanFilter::new_with_parquet_schema( + &expr, &schema, reader.parquet_schema(), - reader.metadata(), - &metrics, - limit, - ); - assert_eq!( - PAGE_PREDICATE_CALLS.get(), - expected_calls, - "middle={middle:?}, limit={limit:?}, selected={selected}, fully_matched={fully_matched}" - ); - assert_eq!( - selected_row_count(&result.access_plan, reader.metadata().row_groups()), - expected_rows ); + #[expect(deprecated)] + let columns = PagePruningAccessPlanFilter::new(&expr, Arc::clone(&schema)); + for filter in [leaves, columns] { + let mut plan = ParquetAccessPlan::new_all(3); + plan.scan_selection( + 0, + vec![ + RowSelector::select(selected), + RowSelector::skip(6 - selected), + ] + .into(), + ); + if fully_matched { + plan.mark_fully_matched(0); + } + let metrics = + ParquetFileMetrics::new(0, "test", &ExecutionPlanMetricsSet::new()); + PAGE_PREDICATE_CALLS.set(0); + let result = filter.prune_plan_with_page_index_and_metrics( + plan, + &schema, + reader.parquet_schema(), + reader.metadata(), + &metrics, + limit, + ); + assert_eq!( + PAGE_PREDICATE_CALLS.get(), + expected_calls, + "middle={middle:?}, limit={limit:?}, selected={selected}, fully_matched={fully_matched}" + ); + assert_eq!( + selected_row_count( + &result.access_plan, + reader.metadata().row_groups() + ), + expected_rows + ); + } } } @@ -1101,4 +1202,43 @@ mod tests { .build() .unwrap() } + + #[test] + fn single_target_requires_one_target() { + let schema = Arc::new(Schema::new(vec![ + Field::new("a", DataType::Int32, true), + Field::new("b", DataType::Int32, true), + ])); + let cmp = |name: &str, idx, op| -> Arc { + Arc::new(BinaryExpr::new( + Arc::new(Column::new(name, idx)), + op, + lit(1), + )) + }; + let one: Arc = Arc::new(BinaryExpr::new( + cmp("a", 0, Operator::Gt), + Operator::And, + cmp("a", 0, Operator::Lt), + )); + let pp = PruningPredicateBuilder::new() + .with_file_schema(Arc::clone(&schema)) + .try_build(one) + .unwrap(); + assert_eq!( + single_target(&pp), + Some(&datafusion_common::Column::from_name("a")) + ); + + let two: Arc = Arc::new(BinaryExpr::new( + cmp("a", 0, Operator::Gt), + Operator::And, + cmp("b", 1, Operator::Lt), + )); + let pp = PruningPredicateBuilder::new() + .with_file_schema(schema) + .try_build(two) + .unwrap(); + assert_eq!(single_target(&pp), None); + } } diff --git a/datafusion/datasource-parquet/src/pruning.rs b/datafusion/datasource-parquet/src/pruning.rs new file mode 100644 index 0000000000000..ecab228f6d5dd --- /dev/null +++ b/datafusion/datasource-parquet/src/pruning.rs @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +//! Shared predicate construction for row-group and page-index pruning. + +use std::sync::Arc; + +use crate::statistics_expr::{ParquetStatisticsResolver, ParquetStatisticsTarget}; +use arrow::datatypes::Schema; +use datafusion_pruning::{PruningPredicate, PruningPredicateBuilder}; +use parquet::schema::types::SchemaDescriptor; + +/// A pruning predicate that reads the statistics of the leaf columns of one +/// Parquet file (see [`crate::statistics_expr`]). +pub(crate) type ParquetPruningPredicate = PruningPredicate; + +/// Builds the predicate of `predicate` again, for the file with these schemas. +/// +/// A predicate with column targets is not bound to a file. The public entry +/// points of this crate take such a predicate, and call this function one +/// time for each file. The result also reads the statistics of struct fields. +pub(crate) fn bind_to_file( + predicate: &PruningPredicate, + arrow_schema: &Schema, + parquet_schema: &SchemaDescriptor, +) -> Option { + PruningPredicateBuilder::new() + .with_file_schema(Arc::clone(predicate.schema())) + .with_resolver(ParquetStatisticsResolver::new(arrow_schema, parquet_schema)) + .with_max_in_list_size(predicate.max_in_list_size()) + .try_build(Arc::clone(predicate.orig_expr())) + .ok() +} + +/// Returns the predicate that proves that every row of a container passes +/// `predicate`, see [`PruningPredicateBuilder::try_build_inverse`]. +/// +/// `parquet_schema` is the schema of the file that `predicate` was built for. +pub(crate) fn build_inverted_predicate( + predicate: &ParquetPruningPredicate, + arrow_schema: &Schema, + parquet_schema: &SchemaDescriptor, +) -> Option { + PruningPredicateBuilder::new() + .with_file_schema(Arc::clone(predicate.schema())) + .with_resolver(ParquetStatisticsResolver::new(arrow_schema, parquet_schema)) + .with_max_in_list_size(predicate.max_in_list_size()) + .try_build_inverse(Arc::clone(predicate.orig_expr())) + .ok() + .flatten() +} diff --git a/datafusion/datasource-parquet/src/push_decoder.rs b/datafusion/datasource-parquet/src/push_decoder.rs index aa0d299d22560..10a462a7f28bf 100644 --- a/datafusion/datasource-parquet/src/push_decoder.rs +++ b/datafusion/datasource-parquet/src/push_decoder.rs @@ -44,12 +44,14 @@ use parquet::arrow::push_decoder::{ }; use parquet::file::metadata::ParquetMetaData; +use crate::pruning::ParquetPruningPredicate; +use crate::statistics_expr::ParquetStatisticsResolver; use datafusion_common::{DataFusionError, Result, internal_err}; use datafusion_execution::memory_pool::MemoryReservation; use datafusion_physical_expr::expressions::DynamicFilterTracking; use datafusion_physical_expr_common::physical_expr::PhysicalExpr; use datafusion_physical_plan::metrics::{BaselineMetrics, Count, Gauge}; -use datafusion_pruning::{PruningPredicate, PruningPredicateBuilder}; +use datafusion_pruning::PruningPredicateBuilder; use crate::ParquetFileMetrics; use crate::decoder_projection::DecoderProjection; @@ -146,7 +148,7 @@ pub(crate) struct InitialDecoderState { /// the row-group level: subscribes once to every still-incomplete dynamic /// filter inside the predicate via /// [`DynamicFilterTracker`](datafusion_physical_expr::expressions::DynamicFilterTracker) -/// and only rebuilds the [`PruningPredicate`] when one of those +/// and only rebuilds the [`ParquetPruningPredicate`] when one of those /// subscriptions reports an update, then evaluates the cached predicate /// against the statistics of the requested row groups. pub(crate) struct RowGroupPruner { @@ -164,7 +166,7 @@ pub(crate) struct RowGroupPruner { /// Cached pruning predicate. `None` means we couldn't build one for the /// current generation (e.g. the predicate has no analyzable bounds); /// in that case we conservatively don't prune. - pruning_predicate: Option>, + pruning_predicate: Option>, /// Metric for `build_pruning_predicate` failures (predicate creation). predicate_creation_errors: Count, /// Metric for `PruningPredicate::prune` failures (evaluating an @@ -220,9 +222,14 @@ impl RowGroupPruner { .tracking .watcher() .is_some_and(|tracker| tracker.changed()); + let file_metadata = self.parquet_metadata.file_metadata(); if self.needs_initial_build || dynamic_changed { self.pruning_predicate = PruningPredicateBuilder::new() .with_file_schema(Arc::clone(&self.arrow_schema)) + .with_resolver(ParquetStatisticsResolver::new( + &self.arrow_schema, + file_metadata.schema_descr(), + )) .with_error_counter(&self.predicate_creation_errors) .with_max_in_list_size(self.max_in_list_size) .build(Arc::clone(&self.predicate)); @@ -238,12 +245,8 @@ impl RowGroupPruner { .map(|&i| self.parquet_metadata.row_group(i)) .collect::>(); let stats = RowGroupPruningStatistics { - parquet_schema: self.parquet_metadata.file_metadata().schema_descr(), - column_orders: self - .parquet_metadata - .file_metadata() - .column_orders() - .map(Vec::as_slice), + parquet_schema: file_metadata.schema_descr(), + column_orders: file_metadata.column_orders().map(Vec::as_slice), row_group_metadatas, arrow_schema: self.arrow_schema.as_ref(), }; diff --git a/datafusion/datasource-parquet/src/row_group_filter.rs b/datafusion/datasource-parquet/src/row_group_filter.rs index 1bd83cba3e71f..5f711157f7743 100644 --- a/datafusion/datasource-parquet/src/row_group_filter.rs +++ b/datafusion/datasource-parquet/src/row_group_filter.rs @@ -8,14 +8,15 @@ use std::sync::Arc; use super::{ParquetAccessPlan, ParquetFileMetrics, RowGroupAccess}; use crate::bloom_filter::BloomFilterStatistics; use crate::metadata::{has_untrusted_byte_array_stats, has_untrusted_min_max_order}; +use crate::pruning::{ParquetPruningPredicate, bind_to_file, build_inverted_predicate}; +use crate::statistics_expr::ParquetStatisticsTarget; use arrow::array::{ArrayRef, BooleanArray, UInt64Array}; use arrow::compute::nullif; use arrow::datatypes::Schema; +use datafusion_common::ScalarValue; use datafusion_common::parquet_config::RowGroupRangeAssignment; -use datafusion_common::pruning::PruningStatistics; -use datafusion_common::{Column, Result, ScalarValue}; use datafusion_datasource::FileRange; -use datafusion_pruning::{PruningPredicate, PruningPredicateBuilder}; +use datafusion_pruning::{PruningPredicate, PruningStatisticsSource}; use parquet::arrow::arrow_reader::statistics::StatisticsConverter; use parquet::basic::ColumnOrder; use parquet::file::metadata::{ParquetMetaData, RowGroupMetaData}; @@ -293,12 +294,17 @@ impl RowGroupAccessPlanFilter { predicate: &PruningPredicate, metrics: &ParquetFileMetrics, ) { + let Some(predicate) = bind_to_file(predicate, arrow_schema, parquet_schema) + else { + metrics.predicate_evaluation_errors.add(1); + return; + }; self.prune_by_statistics_inner( arrow_schema, parquet_schema, groups, None, - predicate, + &predicate, metrics, ); } @@ -317,11 +323,31 @@ impl RowGroupAccessPlanFilter { metadata: &ParquetMetaData, predicate: &PruningPredicate, metrics: &ParquetFileMetrics, + ) { + let parquet_schema = metadata.file_metadata().schema_descr(); + let Some(predicate) = bind_to_file(predicate, arrow_schema, parquet_schema) + else { + metrics.predicate_evaluation_errors.add(1); + return; + }; + self.prune_by_leaf_statistics(arrow_schema, metadata, &predicate, metrics); + } + + /// [`Self::prune_by_statistics_with_metadata`] for a predicate that reads + /// the statistics of leaf columns. `metadata` is the metadata of the file + /// that the predicate was built for. + pub(crate) fn prune_by_leaf_statistics( + &mut self, + arrow_schema: &Schema, + metadata: &ParquetMetaData, + predicate: &ParquetPruningPredicate, + metrics: &ParquetFileMetrics, ) { let file_metadata = metadata.file_metadata(); + let parquet_schema = file_metadata.schema_descr(); self.prune_by_statistics_inner( arrow_schema, - file_metadata.schema_descr(), + parquet_schema, metadata.row_groups(), file_metadata.column_orders().map(Vec::as_slice), predicate, @@ -329,13 +355,15 @@ impl RowGroupAccessPlanFilter { ); } + /// `parquet_schema` is the schema of the file that `predicate` was built + /// for. fn prune_by_statistics_inner( &mut self, arrow_schema: &Schema, parquet_schema: &SchemaDescriptor, groups: &[RowGroupMetaData], column_orders: Option<&[ColumnOrder]>, - predicate: &PruningPredicate, + predicate: &ParquetPruningPredicate, metrics: &ParquetFileMetrics, ) { // scoped timer updates on drop @@ -401,7 +429,7 @@ impl RowGroupAccessPlanFilter { candidate_row_group_indices: &[usize], pruning_stats: &RowGroupPruningStatistics<'_>, groups: &[RowGroupMetaData], - predicate: &PruningPredicate, + predicate: &ParquetPruningPredicate, metrics: &ParquetFileMetrics, ) { if candidate_row_group_indices.is_empty() { @@ -409,13 +437,11 @@ impl RowGroupAccessPlanFilter { } let arrow_schema = pruning_stats.arrow_schema; - let Some(inverted_predicate) = PruningPredicateBuilder::new() - .with_file_schema(Arc::clone(predicate.schema())) - .with_max_in_list_size(predicate.max_in_list_size()) - .try_build_inverse(Arc::clone(predicate.orig_expr())) - .ok() - .flatten() - else { + let Some(inverted_predicate) = build_inverted_predicate( + predicate, + arrow_schema, + pruning_stats.parquet_schema, + ) else { return; }; @@ -517,7 +543,7 @@ impl RowGroupAccessPlanFilter { pub(crate) fn prune_row_group_with_bloom_filters( &mut self, idx: usize, - predicate: &PruningPredicate, + predicate: &ParquetPruningPredicate, bloom_filters: &BloomFilterStatistics, metrics: &ParquetFileMetrics, ) -> bool { @@ -538,11 +564,12 @@ impl RowGroupAccessPlanFilter { } } -/// Wraps a slice of [`RowGroupMetaData`] in a way that implements [`PruningStatistics`]. +/// Wraps a slice of [`RowGroupMetaData`] in a way that implements +/// [`PruningStatisticsSource`] for [`ParquetStatisticsTarget`]. /// /// Visible to sibling modules so runtime row-group pruners (e.g. the dynamic /// TopK pruner in `push_decoder.rs`) can reuse this adapter without -/// duplicating the statistics-to-`PruningStatistics` plumbing. +/// duplicating the statistics plumbing. pub(crate) struct RowGroupPruningStatistics<'a> { pub(crate) parquet_schema: &'a SchemaDescriptor, pub(crate) column_orders: Option<&'a [ColumnOrder]>, @@ -550,28 +577,29 @@ pub(crate) struct RowGroupPruningStatistics<'a> { pub(crate) arrow_schema: &'a Schema, } -impl<'a> RowGroupPruningStatistics<'a> { +impl RowGroupPruningStatistics<'_> { /// Return an iterator over the row group metadata - fn metadata_iter(&self) -> impl Iterator + '_ { - self.row_group_metadatas.iter().copied() + fn metadata_iter<'t>(&'t self) -> impl Iterator { + self.row_group_metadatas + .iter() + .map(|group| -> &'t RowGroupMetaData { group }) } - fn statistics_converter(&self, column: &Column) -> Result> { - Ok(StatisticsConverter::try_new( - &column.name, - self.arrow_schema, - self.parquet_schema, - )? + fn statistics_converter<'t>( + &'t self, + target: &'t ParquetStatisticsTarget, + ) -> Option> { + let converter = target.statistics_converter(self.parquet_schema)?; // Missing counts cannot rule out nulls, either when pruning groups or // when proving that every row matches the predicate. - .with_missing_null_counts_as_zero(false)) + Some(converter.with_missing_null_counts_as_zero(false)) } - fn min_max_statistics_converter( - &self, - column: &Column, - ) -> Option> { - let converter = self.statistics_converter(column).ok()?; + fn min_max_statistics_converter<'t>( + &'t self, + target: &'t ParquetStatisticsTarget, + ) -> Option> { + let converter = self.statistics_converter(target)?; let parquet_index = converter.parquet_column_index(); if parquet_index.is_some_and(|index| { has_untrusted_min_max_order(self.parquet_schema, self.column_orders, index) @@ -602,15 +630,15 @@ impl<'a> RowGroupPruningStatistics<'a> { } } -impl PruningStatistics for RowGroupPruningStatistics<'_> { - fn min_values(&self, column: &Column) -> Option { - let converter = self.min_max_statistics_converter(column)?; +impl PruningStatisticsSource for RowGroupPruningStatistics<'_> { + fn min_values(&self, target: &ParquetStatisticsTarget) -> Option { + let converter = self.min_max_statistics_converter(target)?; let values = converter.row_group_mins(self.metadata_iter()).ok()?; self.mask_untrusted_byte_array_stats(converter.parquet_column_index(), values) } - fn max_values(&self, column: &Column) -> Option { - let converter = self.min_max_statistics_converter(column)?; + fn max_values(&self, target: &ParquetStatisticsTarget) -> Option { + let converter = self.min_max_statistics_converter(target)?; let values = converter.row_group_maxes(self.metadata_iter()).ok()?; self.mask_untrusted_byte_array_stats(converter.parquet_column_index(), values) } @@ -619,9 +647,9 @@ impl PruningStatistics for RowGroupPruningStatistics<'_> { self.row_group_metadatas.len() } - fn null_counts(&self, column: &Column) -> Option { - self.statistics_converter(column) - .and_then(|c| Ok(c.row_group_null_counts(self.metadata_iter())?)) + fn null_counts(&self, target: &ParquetStatisticsTarget) -> Option { + self.statistics_converter(target)? + .row_group_null_counts(self.metadata_iter()) .ok() .map(|counts| Arc::new(counts) as ArrayRef) } @@ -637,7 +665,7 @@ impl PruningStatistics for RowGroupPruningStatistics<'_> { fn contained( &self, - _column: &Column, + _target: &ParquetStatisticsTarget, _values: &HashSet, ) -> Option { None @@ -660,6 +688,7 @@ mod tests { expressions::{BinaryExpr, CastExpr, Column as PhysicalColumn, Literal}, }; use datafusion_physical_plan::metrics::ExecutionPlanMetricsSet; + use datafusion_pruning::PruningPredicateBuilder; use parquet::arrow::ArrowSchemaConverter; use parquet::arrow::arrow_reader::{RowSelection, RowSelector}; use parquet::basic::LogicalType; diff --git a/datafusion/datasource-parquet/src/source.rs b/datafusion/datasource-parquet/src/source.rs index 62a003d24fa5c..ee661c5ff97ad 100644 --- a/datafusion/datasource-parquet/src/source.rs +++ b/datafusion/datasource-parquet/src/source.rs @@ -15,6 +15,7 @@ use crate::opener::build_pruning_predicates; use crate::opener::build_virtual_columns_state; use crate::row_filter::can_expr_be_pushed_down_with_schemas; use crate::schema_coercion::dictionary_reads_enabled; +use crate::statistics_expr::ArrowStatisticsResolver; use arrow_schema::Fields; use arrow_schema::extension::ExtensionType; use arrow_schema::{DataType, Field}; @@ -827,6 +828,7 @@ impl FileSource for ParquetSource { if let Some(pruning_predicate) = build_pruning_predicates( Some(predicate), self.table_schema.table_schema(), + ArrowStatisticsResolver::new(self.table_schema.table_schema()), &predicate_creation_errors, self.max_in_list_size(), ) { diff --git a/datafusion/datasource-parquet/src/statistics_expr.rs b/datafusion/datasource-parquet/src/statistics_expr.rs new file mode 100644 index 0000000000000..fe7d8ae6b0ccc --- /dev/null +++ b/datafusion/datasource-parquet/src/statistics_expr.rs @@ -0,0 +1,250 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +//! Finds the Parquet leaf column that holds the statistics of an expression. +//! +//! Parquet keeps min/max values, null counts, a page index and a bloom filter +//! for each leaf column. An expression has these statistics when its values +//! are the values of one leaf column: +//! +//! | Expression | Leaf column | +//! |-------------------------------|-------------| +//! | A column of a non-nested type | The column | +//! +//! Two resolvers inspect an expression. No other code does. +//! +//! | Resolver | Used when | Target | +//! |-------------------------------|------------------------------|-------------------------------| +//! | [`ParquetStatisticsResolver`] | A file is open | [`ParquetStatisticsTarget`] | +//! | [`ArrowStatisticsResolver`] | The plan is shown, no file | The Arrow field of the values | +//! +//! The predicate keeps the target of each expression, and the statistics +//! sources read by target: +//! +//! ```text +//! expression ---resolve---> ParquetStatisticsTarget --+--> row group statistics +//! (build the predicate) (leaf index, field) +--> bloom filter +//! +--> page index +//! ``` + +use std::sync::Arc; + +use arrow::datatypes::{FieldRef, Schema}; +use datafusion_physical_expr::PhysicalExpr; +use datafusion_physical_expr::expressions::Column; +use datafusion_pruning::StatisticsResolver; +use parquet::arrow::arrow_reader::statistics::StatisticsConverter; +use parquet::arrow::parquet_column; +use parquet::schema::types::SchemaDescriptor; + +/// Names the Parquet statistics of one expression of a pruning predicate: +/// the statistics of one leaf column of one file. +/// +/// The target owns its data, so a predicate does not borrow the schemas of +/// the file. +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct ParquetStatisticsTarget { + /// The Arrow field of the values. For a column, this is the field of the + /// file schema. + field: FieldRef, + /// The index of the leaf column that holds the values. + leaf: usize, +} + +impl ParquetStatisticsTarget { + /// Returns the index of the leaf column that holds the values. + pub(crate) fn leaf(&self) -> usize { + self.leaf + } + + /// Returns a converter for the statistics of this target. `parquet_schema` + /// is the schema of the file that the target was resolved for. + pub(crate) fn statistics_converter<'a>( + &'a self, + parquet_schema: &'a SchemaDescriptor, + ) -> Option> { + StatisticsConverter::from_column_index(self.leaf, &self.field, parquet_schema) + .ok() + } +} + +/// Resolves the expressions of a predicate to the leaf columns of one Parquet +/// file. +pub(crate) struct ParquetStatisticsResolver<'a> { + arrow_schema: &'a Schema, + parquet_schema: &'a SchemaDescriptor, +} + +impl<'a> ParquetStatisticsResolver<'a> { + /// Returns a resolver for the file with these schemas. + pub(crate) fn new( + arrow_schema: &'a Schema, + parquet_schema: &'a SchemaDescriptor, + ) -> Self { + Self { + arrow_schema, + parquet_schema, + } + } +} + +impl StatisticsResolver for ParquetStatisticsResolver<'_> { + type Target = ParquetStatisticsTarget; + + fn resolve(&self, expr: &Arc) -> Option { + let (column, field) = statistics_field(self.arrow_schema, expr)?; + // `None` for a column of a nested type: it has no single leaf. + let (leaf, _) = + parquet_column(self.parquet_schema, self.arrow_schema, column.name())?; + Some(ParquetStatisticsTarget { + field: Arc::clone(field), + leaf, + }) + } +} + +/// Resolves the expressions that can have statistics in a file with an Arrow +/// schema. The target is the Arrow field of the values. +/// +/// A predicate built with it shows which statistics a scan can read. No +/// statistics source prunes with it, because no file is open. +pub(crate) struct ArrowStatisticsResolver<'a> { + arrow_schema: &'a Schema, +} + +impl<'a> ArrowStatisticsResolver<'a> { + /// Returns a resolver for the files with this schema. + pub(crate) fn new(arrow_schema: &'a Schema) -> Self { + Self { arrow_schema } + } +} + +impl StatisticsResolver for ArrowStatisticsResolver<'_> { + type Target = FieldRef; + + fn resolve(&self, expr: &Arc) -> Option { + let (_, field) = statistics_field(self.arrow_schema, expr)?; + Some(Arc::clone(field)) + } +} + +/// Returns the column that `expr` reads, and the Arrow field of its values. +/// +/// Returns `None` if a file with `arrow_schema` cannot have statistics for +/// `expr`. +fn statistics_field<'e, 's>( + arrow_schema: &'s Schema, + expr: &'e Arc, +) -> Option<(&'e Column, &'s FieldRef)> { + let column = expr.downcast_ref::()?; + let (_, field) = arrow_schema.fields().find(column.name())?; + Some((column, field)) +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow::datatypes::{DataType, Field, Fields}; + use datafusion_expr::{Expr, col}; + use datafusion_functions::core::expr_fn::get_field; + use datafusion_physical_expr::planner::logical2physical; + use parquet::arrow::ArrowSchemaConverter; + + /// The leaf columns, in order: `s.a`, `s.inner.b`, `s.l.list.element`, + /// `m.key_value.key`, `m.key_value.value`, `c`. + fn schema() -> Schema { + let int = |name: &str| Field::new(name, DataType::Int32, true); + let inner = DataType::Struct(Fields::from(vec![int("b")])); + let list = DataType::List(Arc::new(int("element"))); + let s = DataType::Struct(Fields::from(vec![ + int("a"), + Field::new("inner", inner, true), + Field::new("l", list, true), + ])); + let entries = DataType::Struct(Fields::from(vec![ + Field::new("key", DataType::Utf8, false), + int("value"), + ])); + let map = DataType::Map(Arc::new(Field::new("key_value", entries, false)), false); + Schema::new(vec![ + Field::new("s", s, true), + Field::new("m", map, true), + int("c"), + ]) + } + + /// The result of resolving one expression. + #[derive(Debug, PartialEq)] + struct Resolved { + /// The target of [`ParquetStatisticsResolver`]: the name of its + /// field, its leaf, and the leaf of its converter. + parquet: Option<(String, usize, Option)>, + /// The name of the target of [`ArrowStatisticsResolver`] + arrow: Option, + } + + fn resolve(expr: &Expr) -> Resolved { + let arrow_schema = schema(); + let parquet_schema = ArrowSchemaConverter::new().convert(&arrow_schema).unwrap(); + let expr = logical2physical(expr, &arrow_schema); + let parquet = + ParquetStatisticsResolver::new(&arrow_schema, &parquet_schema).resolve(&expr); + let arrow = ArrowStatisticsResolver::new(&arrow_schema).resolve(&expr); + Resolved { + parquet: parquet.map(|target| { + let converter = target.statistics_converter(&parquet_schema); + ( + target.field.name().clone(), + target.leaf(), + converter.and_then(|converter| converter.parquet_column_index()), + ) + }), + arrow: arrow.map(|field| field.name().clone()), + } + } + + fn leaf(field: &str, leaf: usize) -> Resolved { + Resolved { + parquet: Some((field.to_string(), leaf, Some(leaf))), + arrow: Some(field.to_string()), + } + } + + #[test] + fn column_resolves_to_its_leaf() { + assert_eq!(resolve(&col("c")), leaf("c", 5)); + } + + #[test] + fn nested_column_has_no_leaf() { + // A file can hold `s`, but no single leaf column describes it. + let nested = Resolved { + parquet: None, + arrow: Some("s".to_string()), + }; + assert_eq!(resolve(&col("s")), nested); + } + + #[test] + fn expressions_without_statistics_have_no_target() { + for expr in [ + // A struct field + get_field(col("s"), "a"), + // A struct + get_field(col("s"), "inner"), + // A list + get_field(col("s"), "l"), + // A key lookup in a map + get_field(col("m"), "k"), + // Not a field access + col("c") + col("c"), + ] { + let none = Resolved { + parquet: None, + arrow: None, + }; + assert_eq!(resolve(&expr), none, "{expr}"); + } + } +} diff --git a/datafusion/datasource-parquet/src/statistics_order_tests.rs b/datafusion/datasource-parquet/src/statistics_order_tests.rs index c3ae36f5d9302..a84f7b1187cfb 100644 --- a/datafusion/datasource-parquet/src/statistics_order_tests.rs +++ b/datafusion/datasource-parquet/src/statistics_order_tests.rs @@ -10,14 +10,17 @@ use std::sync::Arc; use arrow::array::{BooleanArray, record_batch}; use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; use bytes::Bytes; -use datafusion_common::pruning::{PrunableStatistics, PruningStatistics}; +use datafusion_common::pruning::PrunableStatistics; use datafusion_common::stats::Precision; -use datafusion_common::{Column, ScalarValue, Statistics}; +use datafusion_common::{ScalarValue, Statistics}; use datafusion_expr::{Expr, col, lit}; use datafusion_physical_expr::PhysicalExpr; use datafusion_physical_expr::planner::logical2physical; use datafusion_physical_plan::metrics::{Count, ExecutionPlanMetricsSet}; -use datafusion_pruning::{MAX_IN_LIST_SIZE, PruningPredicate, PruningPredicateBuilder}; +use datafusion_pruning::{ + MAX_IN_LIST_SIZE, PruningPredicate, PruningPredicateBuilder, PruningStatisticsSource, + StatisticsResolver, +}; use parquet::arrow::ArrowWriter; use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder; use parquet::basic::{ColumnOrder, LogicalType, SortOrder, Type as PhysicalType}; @@ -37,6 +40,7 @@ use crate::RowGroupAccessPlanFilter; use crate::metadata::{DFParquetMetadata, has_untrusted_min_max_order}; use crate::push_decoder::RowGroupPruner; use crate::row_group_filter::RowGroupPruningStatistics; +use crate::statistics_expr::ParquetStatisticsResolver; use crate::{PagePruningAccessPlanFilter, ParquetAccessPlan, ParquetFileMetrics}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -247,14 +251,18 @@ impl TestFile { physical: &Arc, plan: ParquetAccessPlan, ) -> ParquetAccessPlan { - PagePruningAccessPlanFilter::new(physical, Arc::clone(&self.schema)) - .prune_plan_with_page_index( - plan, - &self.schema, - self.metadata.file_metadata().schema_descr(), - &self.metadata, - &metrics(), - ) + PagePruningAccessPlanFilter::new_with_parquet_schema( + physical, + &self.schema, + self.metadata.file_metadata().schema_descr(), + ) + .prune_plan_with_page_index( + plan, + &self.schema, + self.metadata.file_metadata().schema_descr(), + &self.metadata, + &metrics(), + ) } fn matching_rows( @@ -395,6 +403,7 @@ fn large_string_in_list_preserves_rows_with_untrusted_page_order() { let page_filter = crate::opener::build_page_pruning_predicate( &physical, &file.schema, + file.metadata.file_metadata().schema_descr(), max_in_list_size, ); assert_eq!(page_filter.filter_number(), 1); @@ -507,7 +516,6 @@ fn byte_array_order_modern_bounds_and_null_only_groups_remain_usable() { fn byte_array_order_guard_follows_parquet_type_not_arrow_representation() { let file = TestFile::new(StatisticsOrder::Deprecated); let metadata = file.metadata.file_metadata(); - let column = Column::from_name("s"); for data_type in [ DataType::Utf8, DataType::LargeUtf8, @@ -524,6 +532,12 @@ fn byte_array_order_guard_follows_parquet_type_not_arrow_representation() { row_group_metadatas: file.metadata.row_groups().iter().collect(), arrow_schema: &schema, }; + let column = ParquetStatisticsResolver::new(&schema, metadata.schema_descr()) + .resolve( + &(Arc::new(datafusion_physical_expr::expressions::Column::new("s", 0)) + as _), + ) + .unwrap(); for values in [stats.min_values(&column), stats.max_values(&column)] { let values = values.unwrap(); assert!(values.is_null(0)); @@ -660,15 +674,18 @@ fn fixed_byte_array_and_uuid_orders_guard_bounds_but_not_null_counts() { &metrics(), ); assert_eq!(row_groups.build().should_scan(0), !trusted || deprecated); - let pages = - PagePruningAccessPlanFilter::new(&physical, Arc::clone(&schema)) - .prune_plan_with_page_index( - ParquetAccessPlan::new_all(1), - &schema, - metadata.file_metadata().schema_descr(), - &metadata, - &metrics(), - ); + let pages = PagePruningAccessPlanFilter::new_with_parquet_schema( + &physical, + &schema, + metadata.file_metadata().schema_descr(), + ) + .prune_plan_with_page_index( + ParquetAccessPlan::new_all(1), + &schema, + metadata.file_metadata().schema_descr(), + &metadata, + &metrics(), + ); // Modern page indexes are independent of legacy row-group // bounds, but still need a recognized footer order. assert_eq!(pages.should_scan(0), !trusted); @@ -816,13 +833,17 @@ fn undefined_logical_byte_array_order_is_not_a_bound() { &metrics(), ); assert!(row_groups.build().should_scan(0)); - let pages = PagePruningAccessPlanFilter::new(&physical, Arc::clone(&schema)) - .prune_plan_with_page_index( - ParquetAccessPlan::new_all(1), - &schema, - metadata.file_metadata().schema_descr(), - &metadata, - &metrics(), - ); + let pages = PagePruningAccessPlanFilter::new_with_parquet_schema( + &physical, + &schema, + metadata.file_metadata().schema_descr(), + ) + .prune_plan_with_page_index( + ParquetAccessPlan::new_all(1), + &schema, + metadata.file_metadata().schema_descr(), + &metadata, + &metrics(), + ); assert!(pages.should_scan(0)); } diff --git a/docs/source/library-user-guide/upgrading/index.md b/docs/source/library-user-guide/upgrading/index.md index 70ad7a83de9f7..d29e2c8985fb0 100644 --- a/docs/source/library-user-guide/upgrading/index.md +++ b/docs/source/library-user-guide/upgrading/index.md @@ -427,6 +427,26 @@ To prune with the statistics of expressions other than columns: 3. Implement `PruningStatisticsSource` for the statistics source. One type can implement it for several targets, and `PruningStatistics` too. +### `PagePruningAccessPlanFilter::new` is deprecated + +`PagePruningAccessPlanFilter::new` takes the Arrow schema only, so it cannot +find the Parquet leaf columns of the predicate. It builds its predicates again +for each file that it prunes. Use +`PagePruningAccessPlanFilter::new_with_parquet_schema`, which builds them one +time: + +```diff +-let filter = PagePruningAccessPlanFilter::new(&predicate, schema); ++let filter = PagePruningAccessPlanFilter::new_with_parquet_schema( ++ &predicate, ++ &schema, ++ parquet_metadata.file_metadata().schema_descr(), ++); +``` + +Build the filter for each file, and use it only with the page index of that +file. + ## Past Upgrade Guides The upgrade guides for released versions can be found here: From 8805aa9ca5f1ebd4766024d5a39c2eb3e0b3bf4b Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:53:47 -0800 Subject: [PATCH 6/6] feat: prune Parquet scans with struct field statistics Parquet keeps min/max values, null counts, a page index and a bloom filter for the leaf column of every struct field. A filter such as `s['a'] > 15` uses none of them, because the scan resolves only columns to leaf columns. Resolve `get_field(s, 'a')`, and chains of it, to the leaf column of the field. This is the one place that inspects the function. Row group statistics, bloom filters, the page index, full match detection and dynamic filters then work for struct fields as they do for columns, with no other change. A path through a map or a list has no target, and neither has a field of a nested type. The slt diff shows the effect on each access path. Co-Authored-By: Claude Fable 5.2 --- .../src/row_group_filter.rs | 50 +++++++ .../datasource-parquet/src/statistics_expr.rs | 123 +++++++++++++++--- .../parquet_struct_field_pruning.slt | 66 +++++----- .../test_files/projection_pushdown.slt | 16 +-- .../library-user-guide/upgrading/index.md | 2 + 5 files changed, 197 insertions(+), 60 deletions(-) diff --git a/datafusion/datasource-parquet/src/row_group_filter.rs b/datafusion/datasource-parquet/src/row_group_filter.rs index 5f711157f7743..e6e8954824d91 100644 --- a/datafusion/datasource-parquet/src/row_group_filter.rs +++ b/datafusion/datasource-parquet/src/row_group_filter.rs @@ -1832,4 +1832,54 @@ mod tests { fn assert_pruned(row_groups: RowGroupAccessPlanFilter, expected: ExpectedPruning) { expected.assert(&row_groups); } + + /// The public entry points take a predicate with column targets. They + /// bind it to the file, so it reads the statistics of struct fields too. + #[test] + fn prune_by_statistics_binds_the_predicate_to_the_file() { + use arrow::array::{ArrayRef, Int32Array, RecordBatch, StructArray}; + use arrow::datatypes::Fields; + use datafusion_functions::core::expr_fn::get_field; + use parquet::arrow::ArrowWriter; + use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder; + + // The values of `s.a`, for each row group + let row_groups = [[1, 2], [10, 11]]; + let fields = Fields::from(vec![Field::new("a", DataType::Int32, true)]); + let schema = Arc::new(Schema::new(vec![Field::new( + "s", + DataType::Struct(fields.clone()), + true, + )])); + let mut writer = + ArrowWriter::try_new(Vec::new(), Arc::clone(&schema), None).unwrap(); + for values in row_groups { + let a: ArrayRef = Arc::new(Int32Array::from(values.to_vec())); + let s = StructArray::new(fields.clone(), vec![a], None); + let batch = + RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(s)]).unwrap(); + writer.write(&batch).unwrap(); + writer.flush().unwrap(); + } + let file = bytes::Bytes::from(writer.into_inner().unwrap()); + let reader = ParquetRecordBatchReaderBuilder::try_new(file).unwrap(); + + let expr = logical2physical(&get_field(col("s"), "a").gt(lit(5)), &schema); + let predicate = PruningPredicateBuilder::new() + .with_file_schema(Arc::clone(&schema)) + .try_build(expr) + .unwrap(); + // With column targets, the predicate reads no statistics. + assert!(predicate.always_true()); + + let metrics = ParquetFileMetrics::new(0, "test", &ExecutionPlanMetricsSet::new()); + let mut filter = RowGroupAccessPlanFilter::new(ParquetAccessPlan::new_all(2)); + filter.prune_by_statistics_with_metadata( + &schema, + reader.metadata(), + &predicate, + &metrics, + ); + assert_eq!(filter.build().row_group_indexes(), vec![1]); + } } diff --git a/datafusion/datasource-parquet/src/statistics_expr.rs b/datafusion/datasource-parquet/src/statistics_expr.rs index fe7d8ae6b0ccc..523af21c2fd70 100644 --- a/datafusion/datasource-parquet/src/statistics_expr.rs +++ b/datafusion/datasource-parquet/src/statistics_expr.rs @@ -8,9 +8,14 @@ //! for each leaf column. An expression has these statistics when its values //! are the values of one leaf column: //! -//! | Expression | Leaf column | -//! |-------------------------------|-------------| -//! | A column of a non-nested type | The column | +//! | Expression | Leaf column | +//! |---------------------------------------------|-----------------| +//! | A column of a non-nested type | The column | +//! | `get_field(s, 'a')`, for a struct column `s` | The field `s.a` | +//! +//! A struct field is null in the rows where the struct is null, and the leaf +//! column stores a null for those rows too. So the null count of the leaf is +//! the null count of the expression. //! //! Two resolvers inspect an expression. No other code does. //! @@ -30,9 +35,10 @@ use std::sync::Arc; -use arrow::datatypes::{FieldRef, Schema}; -use datafusion_physical_expr::PhysicalExpr; -use datafusion_physical_expr::expressions::Column; +use arrow::datatypes::{DataType, FieldRef, Schema}; +use datafusion_functions::core::getfield::GetFieldFunc; +use datafusion_physical_expr::expressions::{Column, Literal}; +use datafusion_physical_expr::{PhysicalExpr, ScalarFunctionExpr}; use datafusion_pruning::StatisticsResolver; use parquet::arrow::arrow_reader::statistics::StatisticsConverter; use parquet::arrow::parquet_column; @@ -93,10 +99,13 @@ impl StatisticsResolver for ParquetStatisticsResolver<'_> { type Target = ParquetStatisticsTarget; fn resolve(&self, expr: &Arc) -> Option { - let (column, field) = statistics_field(self.arrow_schema, expr)?; - // `None` for a column of a nested type: it has no single leaf. - let (leaf, _) = - parquet_column(self.parquet_schema, self.arrow_schema, column.name())?; + let (column, path, field) = statistics_field(self.arrow_schema, expr)?; + let leaf = if path.is_empty() { + // `None` for a column of a nested type: it has no single leaf. + parquet_column(self.parquet_schema, self.arrow_schema, column.name())?.0 + } else { + struct_field_leaf(column, &path, self.parquet_schema)? + }; Some(ParquetStatisticsTarget { field: Arc::clone(field), leaf, @@ -124,28 +133,81 @@ impl StatisticsResolver for ArrowStatisticsResolver<'_> { type Target = FieldRef; fn resolve(&self, expr: &Arc) -> Option { - let (_, field) = statistics_field(self.arrow_schema, expr)?; + let (_, _, field) = statistics_field(self.arrow_schema, expr)?; Some(Arc::clone(field)) } } -/// Returns the column that `expr` reads, and the Arrow field of its values. +/// Returns the column that `expr` reads, the names of the struct fields that +/// it reads below the column, and the Arrow field of its values. /// /// Returns `None` if a file with `arrow_schema` cannot have statistics for /// `expr`. fn statistics_field<'e, 's>( arrow_schema: &'s Schema, expr: &'e Arc, -) -> Option<(&'e Column, &'s FieldRef)> { - let column = expr.downcast_ref::()?; - let (_, field) = arrow_schema.fields().find(column.name())?; - Some((column, field)) +) -> Option<(&'e Column, Vec<&'e str>, &'s FieldRef)> { + // A column is a path with no field names. + let (column, path) = match expr.downcast_ref::() { + Some(column) => (column, vec![]), + None => struct_field_path(expr)?, + }; + let (_, mut field) = arrow_schema.fields().find(column.name())?; + // Every step is a field of a struct. A path through a map is a key + // lookup, and a field below a list has statistics for each element, + // not for each row. + for name in &path { + let DataType::Struct(fields) = field.data_type() else { + return None; + }; + (_, field) = fields.find(name)?; + } + if !path.is_empty() && field.data_type().is_nested() { + return None; + } + Some((column, path, field)) +} + +/// Returns the struct column and the field path that `expr` reads, including +/// chained calls such as `get_field(get_field(s, 'a'), 'b')`. +/// +/// This is the only code in this crate that knows which function reads a +/// field with statistics. +fn struct_field_path(expr: &Arc) -> Option<(&Column, Vec<&str>)> { + let func = ScalarFunctionExpr::try_downcast_func::(expr.as_ref())?; + let (base, names) = func.args().split_first()?; + let (column, mut path) = match base.downcast_ref::() { + Some(column) => (column, vec![]), + None => struct_field_path(base)?, + }; + for name in names { + path.push(name.downcast_ref::()?.value().try_as_str()??); + } + (!path.is_empty()).then_some((column, path)) +} + +/// Returns the index of the leaf column at `path` in the struct column +/// `column`. +fn struct_field_leaf( + column: &Column, + path: &[&str], + parquet_schema: &SchemaDescriptor, +) -> Option { + parquet_schema.columns().iter().position(|leaf| { + let parts = leaf.path().parts(); + // A leaf below a list repeats within a row, and its statistics are + // for each element. + leaf.max_rep_level() == 0 + && parts.len() == path.len() + 1 + && parts[0] == column.name() + && parts[1..].iter().zip(path).all(|(part, name)| part == name) + }) } #[cfg(test)] mod tests { use super::*; - use arrow::datatypes::{DataType, Field, Fields}; + use arrow::datatypes::{Field, Fields}; use datafusion_expr::{Expr, col}; use datafusion_functions::core::expr_fn::get_field; use datafusion_physical_expr::planner::logical2physical; @@ -211,11 +273,36 @@ mod tests { } } + #[test] + fn struct_field_resolves_to_its_leaf() { + assert_eq!(resolve(&get_field(col("s"), "a")), leaf("a", 0)); + let b = get_field(get_field(col("s"), "inner"), "b"); + assert_eq!(resolve(&b), leaf("b", 1)); + } + #[test] fn column_resolves_to_its_leaf() { assert_eq!(resolve(&col("c")), leaf("c", 5)); } + #[test] + fn equal_expressions_resolve_to_equal_targets() { + let arrow_schema = schema(); + let parquet_schema = ArrowSchemaConverter::new().convert(&arrow_schema).unwrap(); + let resolver = ParquetStatisticsResolver::new(&arrow_schema, &parquet_schema); + let resolve = |expr: Expr| { + resolver + .resolve(&logical2physical(&expr, &arrow_schema)) + .unwrap() + }; + // Each expression is built two times. + let a = resolve(get_field(col("s"), "a")); + assert_eq!(a, resolve(get_field(col("s"), "a"))); + let c = resolve(col("c")); + assert_eq!(c, resolve(col("c"))); + assert_ne!(a, c); + } + #[test] fn nested_column_has_no_leaf() { // A file can hold `s`, but no single leaf column describes it. @@ -229,8 +316,6 @@ mod tests { #[test] fn expressions_without_statistics_have_no_target() { for expr in [ - // A struct field - get_field(col("s"), "a"), // A struct get_field(col("s"), "inner"), // A list diff --git a/datafusion/sqllogictest/test_files/parquet_struct_field_pruning.slt b/datafusion/sqllogictest/test_files/parquet_struct_field_pruning.slt index 26fe96be89e48..17cd92d671bf8 100644 --- a/datafusion/sqllogictest/test_files/parquet_struct_field_pruning.slt +++ b/datafusion/sqllogictest/test_files/parquet_struct_field_pruning.slt @@ -75,36 +75,36 @@ query TT EXPLAIN ANALYZE SELECT * FROM t WHERE s['a'] > 15; ---- Plan with Metrics -01)FilterExec: __datafusion_extracted_1@0 > 15, projection=[s@1, id@2], metrics=[output_rows=4, selectivity=33.33% (4/12)] -02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=12] -03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s, id], file_type=parquet, predicate=get_field(s@0, a) > 15, metrics=[output_rows=12, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 4 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=27.52% (926/3.37 K)] +01)FilterExec: __datafusion_extracted_1@0 > 15, projection=[s@1, id@2], metrics=[output_rows=4, selectivity=66.67% (4/6)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=6] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s, id], file_type=parquet, predicate=get_field(s@0, a) > 15, pruning_predicate=get_field(s@0, a)_null_count@1 != row_count@2 AND get_field(s@0, a)_max@0 > 15, required_guarantees=[], metrics=[output_rows=6, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 2 matched -> 1 fully matched, page_index_pages_pruned=1 total → 1 matched, page_index_pages_skipped_by_fully_matched=1, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=13.43% (452/3.37 K)] # Only row group 0 matches. query TT EXPLAIN ANALYZE SELECT * FROM t WHERE s['a'] <= 2; ---- Plan with Metrics -01)FilterExec: __datafusion_extracted_1@0 <= 2, projection=[s@1, id@2], metrics=[output_rows=2, selectivity=16.67% (2/12)] -02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=12] -03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s, id], file_type=parquet, predicate=get_field(s@0, a) <= 2, metrics=[output_rows=12, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 4 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=27.52% (926/3.37 K)] +01)FilterExec: __datafusion_extracted_1@0 <= 2, projection=[s@1, id@2], metrics=[output_rows=2, selectivity=66.67% (2/3)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=3] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s, id], file_type=parquet, predicate=get_field(s@0, a) <= 2, pruning_predicate=get_field(s@0, a)_null_count@1 != row_count@2 AND get_field(s@0, a)_min@0 <= 2, required_guarantees=[], metrics=[output_rows=3, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 1 matched, page_index_pages_pruned=1 total → 1 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=7.04% (237/3.37 K)] # Equality, with the literal on the left. query TT EXPLAIN ANALYZE SELECT * FROM t WHERE 11 = s['a']; ---- Plan with Metrics -01)FilterExec: __datafusion_extracted_1@0 = 11, projection=[s@1, id@2], metrics=[output_rows=1, selectivity=8.33% (1/12)] -02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=12] -03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s, id], file_type=parquet, predicate=get_field(s@0, a) = 11, metrics=[output_rows=12, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 4 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=27.52% (926/3.37 K)] +01)FilterExec: __datafusion_extracted_1@0 = 11, projection=[s@1, id@2], metrics=[output_rows=1, selectivity=33.33% (1/3)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=3] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s, id], file_type=parquet, predicate=get_field(s@0, a) = 11, pruning_predicate=get_field(s@0, a)_null_count@2 != row_count@3 AND get_field(s@0, a)_min@0 <= 11 AND 11 <= get_field(s@0, a)_max@1, required_guarantees=[], metrics=[output_rows=3, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 1 matched, page_index_pages_pruned=1 total → 1 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=7.04% (237/3.37 K)] # Row group 2 holds only one non-null `a`, so `s['a'] = 20` keeps it. query TT EXPLAIN ANALYZE SELECT * FROM t WHERE s['a'] = 20; ---- Plan with Metrics -01)FilterExec: __datafusion_extracted_1@0 = 20, projection=[s@1, id@2], metrics=[output_rows=1, selectivity=8.33% (1/12)] -02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=12] -03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s, id], file_type=parquet, predicate=get_field(s@0, a) = 20, metrics=[output_rows=12, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 4 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=27.52% (926/3.37 K)] +01)FilterExec: __datafusion_extracted_1@0 = 20, projection=[s@1, id@2], metrics=[output_rows=1, selectivity=33.33% (1/3)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=3] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s, id], file_type=parquet, predicate=get_field(s@0, a) = 20, pruning_predicate=get_field(s@0, a)_null_count@2 != row_count@3 AND get_field(s@0, a)_min@0 <= 20 AND 20 <= get_field(s@0, a)_max@1, required_guarantees=[], metrics=[output_rows=3, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 1 matched, page_index_pages_pruned=1 total → 1 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=6.39% (215/3.37 K)] # Two different struct fields in one comparison are not prunable. query TT @@ -120,9 +120,9 @@ query TT EXPLAIN ANALYZE SELECT * FROM t WHERE s['a'] > 25 OR id < 2; ---- Plan with Metrics -01)FilterExec: __datafusion_extracted_1@0 > 25 OR id@2 < 2, projection=[s@1, id@2], metrics=[output_rows=5, selectivity=41.67% (5/12)] -02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=12] -03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s, id], file_type=parquet, predicate=get_field(s@0, a) > 25 OR id@1 < 2, metrics=[output_rows=12, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 4 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=27.52% (926/3.37 K)] +01)FilterExec: __datafusion_extracted_1@0 > 25 OR id@2 < 2, projection=[s@1, id@2], metrics=[output_rows=5, selectivity=55.56% (5/9)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=9] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s, id], file_type=parquet, predicate=get_field(s@0, a) > 25 OR id@1 < 2, pruning_predicate=get_field(s@0, a)_null_count@1 != row_count@2 AND get_field(s@0, a)_max@0 > 25 OR id_null_count@4 != row_count@2 AND id_min@3 < 2, required_guarantees=[], metrics=[output_rows=9, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 3 matched -> 1 fully matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=20.48% (689/3.37 K)] # An IN list longer than 20 values uses the compact form, when the limit # allows it. Only row group 3 (`a` in [30, 32]) can match. A table reads @@ -139,9 +139,9 @@ query TT EXPLAIN ANALYZE SELECT * FROM t_in WHERE s['a'] IN (30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50); ---- Plan with Metrics -01)FilterExec: __datafusion_extracted_1@0 IN (SET) ([30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]), projection=[s@1, id@2], metrics=[output_rows=3, selectivity=25% (3/12)] -02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=12] -03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s, id], file_type=parquet, predicate=get_field(s@0, a) IN (SET) ([30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]), metrics=[output_rows=12, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 4 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=27.52% (926/3.37 K)] +01)FilterExec: __datafusion_extracted_1@0 IN (SET) ([30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]), projection=[s@1, id@2], metrics=[output_rows=3, selectivity=100% (3/3)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=3] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s, id], file_type=parquet, predicate=get_field(s@0, a) IN (SET) ([30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]), pruning_predicate=get_field(s@0, a)_null_count@3 != row_count@2 AND IN_SET_INTERSECTS(get_field(s@0, a)_min@0, get_field(s@0, a)_max@1, 21 values), required_guarantees=[], metrics=[output_rows=3, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 1 matched, page_index_pages_pruned=1 total → 1 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=7.04% (237/3.37 K)] statement ok DROP TABLE t_in; @@ -182,9 +182,9 @@ query TT EXPLAIN ANALYZE SELECT * FROM two_files WHERE s['a'] < 10; ---- Plan with Metrics -01)FilterExec: __datafusion_extracted_1@0 < 10, projection=[s@1], metrics=[output_rows=3, selectivity=50% (3/6)] -02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=2, metrics=[output_rows=6] -03)----DataSourceExec: file_groups={2 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/two_files/high.parquet], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/two_files/low.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s], file_type=parquet, predicate=get_field(s@0, a) < 10, metrics=[output_rows=6, files_ranges_pruned_statistics=2 total → 2 matched, row_groups_pruned_statistics=2 total → 2 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=26.69% (158/592)] +01)FilterExec: __datafusion_extracted_1@0 < 10, projection=[s@1], metrics=[output_rows=3, selectivity=100% (3/3)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=2, metrics=[output_rows=3] +03)----DataSourceExec: file_groups={2 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/two_files/high.parquet], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/two_files/low.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s], file_type=parquet, predicate=get_field(s@0, a) < 10, pruning_predicate=get_field(s@0, a)_null_count@1 != row_count@2 AND get_field(s@0, a)_min@0 < 10, required_guarantees=[], metrics=[output_rows=3, files_ranges_pruned_statistics=2 total → 2 matched, row_groups_pruned_statistics=2 total → 1 matched -> 1 fully matched, page_index_pages_pruned=0 total → 0 matched, page_index_pages_skipped_by_fully_matched=1, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=13.34% (79/592)] statement ok DROP TABLE two_files; @@ -215,9 +215,9 @@ query TT EXPLAIN ANALYZE SELECT * FROM pages WHERE s['a'] >= 85; ---- Plan with Metrics -01)FilterExec: __datafusion_extracted_1@0 >= 85, projection=[s@1], metrics=[output_rows=15, selectivity=15% (15/100)] -02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=100] -03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/pages.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s], file_type=parquet, predicate=get_field(s@0, a) >= 85, metrics=[output_rows=100, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=1 total → 1 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=43.97% (624/1.42 K)] +01)FilterExec: __datafusion_extracted_1@0 >= 85, projection=[s@1], metrics=[output_rows=15, selectivity=75% (15/20)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=20] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/pages.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s], file_type=parquet, predicate=get_field(s@0, a) >= 85, pruning_predicate=get_field(s@0, a)_null_count@1 != row_count@2 AND get_field(s@0, a)_max@0 >= 85, required_guarantees=[], metrics=[output_rows=20, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=1 total → 1 matched, page_index_pages_pruned=10 total → 2 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=18.32% (260/1.42 K)] statement ok DROP TABLE pages; @@ -266,7 +266,7 @@ EXPLAIN ANALYZE SELECT s['a'] FROM topk ORDER BY s['a'] DESC LIMIT 3; ---- Plan with Metrics 01)SortExec: TopK(fetch=3), expr=[topk.s[a]@0 DESC], preserve_partitioning=[false], filter=[topk.s[a]@0 IS NULL OR topk.s[a]@0 > 12], metrics=[output_rows=3] -02)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/topk.parquet]]}, projection=[get_field(s@0, a) as topk.s[a]], file_type=parquet, predicate=DynamicFilter [ get_field(s@0, a) IS NULL OR get_field(s@0, a) > 12 ], dynamic_rg_pruning=eligible, metrics=[output_rows=3, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=5 total → 5 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, row_groups_pruned_dynamic_filter=0, scan_efficiency_ratio=14.08% (387/2.75 K)] +02)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/topk.parquet]]}, projection=[get_field(s@0, a) as topk.s[a]], file_type=parquet, predicate=DynamicFilter [ get_field(s@0, a) IS NULL OR get_field(s@0, a) > 12 ], dynamic_rg_pruning=eligible, pruning_predicate=get_field(s@0, a)_null_count@0 > 0 OR get_field(s@0, a)_null_count@0 != row_count@2 AND get_field(s@0, a)_max@1 > 12, required_guarantees=[], metrics=[output_rows=3, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=5 total → 5 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, row_groups_pruned_dynamic_filter=4, scan_efficiency_ratio=2.87% (79/2.75 K)] statement ok reset datafusion.execution.parquet.pushdown_filters; @@ -306,9 +306,9 @@ query TT EXPLAIN ANALYZE SELECT * FROM drift WHERE s['a'] > 6.5; ---- Plan with Metrics -01)FilterExec: __datafusion_extracted_1@0 > 6.5, projection=[s@1], metrics=[output_rows=2, selectivity=22.22% (2/9)] -02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=9] -03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/drift/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s], file_type=parquet, predicate=get_field(s@0, a) > 6.5, metrics=[output_rows=9, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=3 total → 3 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=21.39% (213/996)] +01)FilterExec: __datafusion_extracted_1@0 > 6.5, projection=[s@1], metrics=[output_rows=2, selectivity=66.67% (2/3)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=3] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/drift/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s], file_type=parquet, predicate=get_field(s@0, a) > 6.5, pruning_predicate=get_field(s@0, a)_null_count@1 != row_count@2 AND get_field(s@0, a)_max@0 > 6.5, required_guarantees=[], metrics=[output_rows=3, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=3 total → 1 matched, page_index_pages_pruned=1 total → 1 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=7.13% (71/996)] statement ok DROP TABLE drift; @@ -347,9 +347,9 @@ query TT EXPLAIN ANALYZE SELECT * FROM bloom WHERE s['a'] = 50; ---- Plan with Metrics -01)FilterExec: __datafusion_extracted_1@0 = 50, projection=[s@1], metrics=[output_rows=0, selectivity=0% (0/4)] -02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=4] -03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/bloom.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s], file_type=parquet, predicate=get_field(s@0, a) = 50, metrics=[output_rows=4, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=2 total → 2 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=20.1% (560/2.79 K)] +01)FilterExec: __datafusion_extracted_1@0 = 50, projection=[s@1], metrics=[output_rows=0, selectivity=N/A (0/0)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=0] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/bloom.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s], file_type=parquet, predicate=get_field(s@0, a) = 50, pruning_predicate=get_field(s@0, a)_null_count@2 != row_count@3 AND get_field(s@0, a)_min@0 <= 50 AND 50 <= get_field(s@0, a)_max@1, required_guarantees=[], metrics=[output_rows=0, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=2 total → 2 matched, row_groups_pruned_bloom_filter=2 total → 0 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=3.37% (94/2.79 K)] # `!=` can never be proven false by a bloom filter. query I @@ -428,9 +428,9 @@ query TT EXPLAIN ANALYZE SELECT hj.v FROM u JOIN hj ON hj.s['a'] = u.id; ---- Plan with Metrics -01)HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(id@0, __datafusion_extracted_1@0)], projection=[v@2], metrics=[output_rows=3, avg_fanout=100% (3/3), probe_hit_rate=0.03% (3/10.00 K)] +01)HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(id@0, __datafusion_extracted_1@0)], projection=[v@2], metrics=[output_rows=3, avg_fanout=100% (3/3), probe_hit_rate=0.1% (3/3.00 K)] 02)--DataSourceExec: partitions=1, partition_sizes=[1], metrics=[] -03)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/hj.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, v], output_ordering=[v@1 ASC NULLS LAST], file_type=parquet, predicate=DynamicFilter [ get_field(s@0, a) >= 0 AND get_field(s@0, a) <= 9999 AND hash_lookup ], dynamic_rg_pruning=eligible, metrics=[output_rows=10.00 K, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=10 total → 10 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=92.57% (48.31 K/52.19 K)] +03)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/hj.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, v], output_ordering=[v@1 ASC NULLS LAST], file_type=parquet, predicate=DynamicFilter [ get_field(s@0, a) >= 0 AND get_field(s@0, a) <= 9999 AND hash_lookup ], dynamic_rg_pruning=eligible, pruning_predicate=get_field(s@0, a)_null_count@1 != row_count@2 AND get_field(s@0, a)_max@0 >= 0 AND get_field(s@0, a)_null_count@1 != row_count@2 AND get_field(s@0, a)_min@3 <= 9999 AND get_field(s@0, a)_null_count@1 != row_count@2 AND KEY_RANGE_BITMAP(get_field(s@0, a)_min@3, get_field(s@0, a)_max@0, 3/16384 buckets), required_guarantees=[], metrics=[output_rows=3.00 K, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=10 total → 3 matched, page_index_pages_pruned=3 total → 3 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=29.15% (15.21 K/52.19 K)] statement ok reset datafusion.optimizer.hash_join_inlist_pushdown_max_size; diff --git a/datafusion/sqllogictest/test_files/projection_pushdown.slt b/datafusion/sqllogictest/test_files/projection_pushdown.slt index 2d5a554430b94..7454d2e96e2f0 100644 --- a/datafusion/sqllogictest/test_files/projection_pushdown.slt +++ b/datafusion/sqllogictest/test_files/projection_pushdown.slt @@ -279,7 +279,7 @@ logical_plan physical_plan 01)ProjectionExec: expr=[id@0 as id, __datafusion_extracted_2@1 as simple_struct.s[label]] 02)--FilterExec: __datafusion_extracted_1@0 > 150, projection=[id@1, __datafusion_extracted_2@2] -03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/simple.parquet]]}, projection=[get_field(s@1, value) as __datafusion_extracted_1, id, get_field(s@1, label) as __datafusion_extracted_2], file_type=parquet, predicate=get_field(s@1, value) > 150 +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/simple.parquet]]}, projection=[get_field(s@1, value) as __datafusion_extracted_1, id, get_field(s@1, label) as __datafusion_extracted_2], file_type=parquet, predicate=get_field(s@1, value) > 150, pruning_predicate=get_field(s@1, value)_null_count@1 != row_count@2 AND get_field(s@1, value)_max@0 > 150, required_guarantees=[] # Verify correctness query IT @@ -839,7 +839,7 @@ logical_plan physical_plan 01)ProjectionExec: expr=[id@0 as id, __datafusion_extracted_2@1 as nullable_struct.s[label]] 02)--FilterExec: __datafusion_extracted_1@0 IS NOT NULL, projection=[id@1, __datafusion_extracted_2@2] -03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/nullable.parquet]]}, projection=[get_field(s@1, value) as __datafusion_extracted_1, id, get_field(s@1, label) as __datafusion_extracted_2], file_type=parquet, predicate=get_field(s@1, value) IS NOT NULL +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/nullable.parquet]]}, projection=[get_field(s@1, value) as __datafusion_extracted_1, id, get_field(s@1, label) as __datafusion_extracted_2], file_type=parquet, predicate=get_field(s@1, value) IS NOT NULL, pruning_predicate=get_field(s@1, value)_null_count@1 != row_count@0, required_guarantees=[] # Verify correctness query IT @@ -1447,7 +1447,7 @@ logical_plan physical_plan 01)HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(id@0, id@0)] 02)--FilterExec: __datafusion_extracted_1@0 > 150, projection=[id@1] -03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/simple.parquet]]}, projection=[get_field(s@1, value) as __datafusion_extracted_1, id], file_type=parquet, predicate=get_field(s@1, value) > 150 +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/simple.parquet]]}, projection=[get_field(s@1, value) as __datafusion_extracted_1, id], file_type=parquet, predicate=get_field(s@1, value) > 150, pruning_predicate=get_field(s@1, value)_null_count@1 != row_count@2 AND get_field(s@1, value)_max@0 > 150, required_guarantees=[] 04)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/join_right.parquet]]}, projection=[id], file_type=parquet, predicate=DynamicFilter [ empty ], dynamic_rg_pruning=eligible # Verify correctness - id matches and value > 150 @@ -1486,9 +1486,9 @@ logical_plan physical_plan 01)HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(id@0, id@0)] 02)--FilterExec: __datafusion_extracted_1@0 > 100, projection=[id@1] -03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/simple.parquet]]}, projection=[get_field(s@1, value) as __datafusion_extracted_1, id], file_type=parquet, predicate=get_field(s@1, value) > 100 +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/simple.parquet]]}, projection=[get_field(s@1, value) as __datafusion_extracted_1, id], file_type=parquet, predicate=get_field(s@1, value) > 100, pruning_predicate=get_field(s@1, value)_null_count@1 != row_count@2 AND get_field(s@1, value)_max@0 > 100, required_guarantees=[] 04)--FilterExec: __datafusion_extracted_2@0 > 3, projection=[id@1] -05)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/join_right.parquet]]}, projection=[get_field(s@1, level) as __datafusion_extracted_2, id], file_type=parquet, predicate=get_field(s@1, level) > 3 AND DynamicFilter [ empty ], dynamic_rg_pruning=eligible +05)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/join_right.parquet]]}, projection=[get_field(s@1, level) as __datafusion_extracted_2, id], file_type=parquet, predicate=get_field(s@1, level) > 3 AND DynamicFilter [ empty ], dynamic_rg_pruning=eligible, pruning_predicate=get_field(s@1, level)_null_count@1 != row_count@2 AND get_field(s@1, level)_max@0 > 3, required_guarantees=[] # Verify correctness - id matches, value > 100, and level > 3 # Matching ids where value > 100: 2(200), 3(150), 4(300), 5(250) @@ -1594,7 +1594,7 @@ physical_plan 01)ProjectionExec: expr=[id@0 as id, __datafusion_extracted_2@1 as simple_struct.s[value], __datafusion_extracted_3@2 as join_right.s[level]] 02)--HashJoinExec: mode=CollectLeft, join_type=Right, on=[(id@0, id@1)], projection=[id@3, __datafusion_extracted_2@2, __datafusion_extracted_3@1] 03)----FilterExec: __datafusion_extracted_1@0 > 5, projection=[id@1, __datafusion_extracted_3@2] -04)------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/join_right.parquet]]}, projection=[get_field(s@1, level) as __datafusion_extracted_1, id, get_field(s@1, level) as __datafusion_extracted_3], file_type=parquet, predicate=get_field(s@1, level) > 5 +04)------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/join_right.parquet]]}, projection=[get_field(s@1, level) as __datafusion_extracted_1, id, get_field(s@1, level) as __datafusion_extracted_3], file_type=parquet, predicate=get_field(s@1, level) > 5, pruning_predicate=get_field(s@1, level)_null_count@1 != row_count@2 AND get_field(s@1, level)_max@0 > 5, required_guarantees=[] 05)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/simple.parquet]]}, projection=[get_field(s@1, value) as __datafusion_extracted_2, id], file_type=parquet # Verify correctness - left join with level > 5 condition @@ -1727,7 +1727,7 @@ logical_plan 05)--------TableScan: simple_struct projection=[id, s], partial_filters=[get_field(simple_struct.s, Utf8("value")) > Int64(200)] physical_plan 01)FilterExec: __datafusion_extracted_1@0 > 200, projection=[id@1] -02)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/simple.parquet]]}, projection=[get_field(s@1, value) as __datafusion_extracted_1, id], file_type=parquet, predicate=get_field(s@1, value) > 200 +02)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/simple.parquet]]}, projection=[get_field(s@1, value) as __datafusion_extracted_1, id], file_type=parquet, predicate=get_field(s@1, value) > 200, pruning_predicate=get_field(s@1, value)_null_count@1 != row_count@2 AND get_field(s@1, value)_max@0 > 200, required_guarantees=[] # Verify correctness query I @@ -2557,7 +2557,7 @@ physical_plan 04)------SortExec: expr=[device@0 ASC NULLS LAST, timestamp@2 ASC NULLS LAST], preserve_partitioning=[false] 05)--------ProjectionExec: expr=[__datafusion_extracted_1@0 as device, __datafusion_extracted_2@1 as user, timestamp@2 as timestamp] 06)----------FilterExec: date@2 = 2025-01-03 AND __datafusion_extracted_1@0 IS NOT NULL AND __datafusion_extracted_1@0 != AND __datafusion_extracted_2@1 IS NOT NULL AND __datafusion_extracted_2@1 != , projection=[__datafusion_extracted_1@0, __datafusion_extracted_2@1, timestamp@3] -07)------------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/events.parquet]]}, projection=[get_field(ids@2, id1) as __datafusion_extracted_1, get_field(structs@3, var1) as __datafusion_extracted_2, date, timestamp], file_type=parquet, predicate=date@0 = 2025-01-03 AND get_field(ids@2, id1) IS NOT NULL AND get_field(ids@2, id1) != AND get_field(structs@3, var1) IS NOT NULL AND get_field(structs@3, var1) != , pruning_predicate=date_null_count@2 != row_count@3 AND date_min@0 <= 2025-01-03 AND 2025-01-03 <= date_max@1, required_guarantees=[date in (2025-01-03)] +07)------------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/events.parquet]]}, projection=[get_field(ids@2, id1) as __datafusion_extracted_1, get_field(structs@3, var1) as __datafusion_extracted_2, date, timestamp], file_type=parquet, predicate=date@0 = 2025-01-03 AND get_field(ids@2, id1) IS NOT NULL AND get_field(ids@2, id1) != AND get_field(structs@3, var1) IS NOT NULL AND get_field(structs@3, var1) != , pruning_predicate=date_null_count@2 != row_count@3 AND date_min@0 <= 2025-01-03 AND 2025-01-03 <= date_max@1 AND get_field(ids@2, id1)_null_count@4 != row_count@3 AND get_field(ids@2, id1)_null_count@4 != row_count@3 AND (get_field(ids@2, id1)_min@5 != OR != get_field(ids@2, id1)_max@6) AND get_field(structs@3, var1)_null_count@7 != row_count@3 AND get_field(structs@3, var1)_null_count@7 != row_count@3 AND (get_field(structs@3, var1)_min@8 != OR != get_field(structs@3, var1)_max@9), required_guarantees=[date in (2025-01-03)] statement ok DROP TABLE events_pq; diff --git a/docs/source/library-user-guide/upgrading/index.md b/docs/source/library-user-guide/upgrading/index.md index d29e2c8985fb0..febfc72727dd8 100644 --- a/docs/source/library-user-guide/upgrading/index.md +++ b/docs/source/library-user-guide/upgrading/index.md @@ -427,6 +427,8 @@ To prune with the statistics of expressions other than columns: 3. Implement `PruningStatisticsSource` for the statistics source. One type can implement it for several targets, and `PruningStatistics` too. +The Parquet scan does this for the fields of struct columns. + ### `PagePruningAccessPlanFilter::new` is deprecated `PagePruningAccessPlanFilter::new` takes the Arrow schema only, so it cannot