Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions datafusion/core/tests/parquet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down
98 changes: 98 additions & 0 deletions datafusion/core/tests/parquet/struct_field_pruning.rs
Original file line number Diff line number Diff line change
@@ -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)),
);
}
120 changes: 95 additions & 25 deletions datafusion/datasource-parquet/src/bloom_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -23,6 +25,9 @@ use parquet::data_type::Decimal;
pub struct BloomFilterStatistics {
/// Per-column Bloom filters keyed by predicate column name.
column_sbbf: HashMap<String, ColumnBloomFilter>,
/// Bloom filters keyed by the index of their Parquet leaf column. A
/// predicate that reads leaf columns finds its filters here.
leaf_sbbf: HashMap<usize, ColumnBloomFilter>,
}

#[derive(Debug, Clone)]
Expand All @@ -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
Expand All @@ -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`.
Expand Down Expand Up @@ -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<ScalarValue>) -> 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<ArrayRef> {
None
Expand All @@ -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<ScalarValue>,
) -> Option<BooleanArray> {
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<ParquetStatisticsTarget> for BloomFilterStatistics {
fn min_values(&self, _target: &ParquetStatisticsTarget) -> Option<ArrayRef> {
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<ArrayRef> {
None
}

fn num_containers(&self) -> usize {
1
}

fn null_counts(&self, _target: &ParquetStatisticsTarget) -> Option<ArrayRef> {
None
}

fn row_counts(&self) -> Option<ArrayRef> {
None
}

Some(BooleanArray::from(vec![contains]))
fn contained(
&self,
target: &ParquetStatisticsTarget,
values: &HashSet<ScalarValue>,
) -> Option<BooleanArray> {
let leaf_bloom_filter = self.leaf_sbbf.get(&target.leaf())?;
Some(leaf_bloom_filter.contained(values))
}
}

Expand Down
2 changes: 2 additions & 0 deletions datafusion/datasource-parquet/src/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down
Loading