|
| 1 | +//! An implementation of parquet row group skipping using data skipping predicates over footer stats. |
| 2 | +use crate::engine::parquet_stats_skipping::{col_name_to_path, ParquetStatsSkippingFilter}; |
| 3 | +use crate::expressions::{Expression, Scalar}; |
| 4 | +use crate::schema::{DataType, PrimitiveType}; |
| 5 | +use parquet::arrow::arrow_reader::ArrowReaderBuilder; |
| 6 | +use parquet::file::metadata::RowGroupMetaData; |
| 7 | +use parquet::file::statistics::Statistics; |
| 8 | +use parquet::schema::types::{ColumnDescPtr, ColumnPath}; |
| 9 | +use std::collections::{HashMap, HashSet}; |
| 10 | + |
| 11 | +/// An extension trait for [`ArrowReaderBuilder`] that injects row group skipping capability. |
| 12 | +pub(crate) trait ParquetRowGroupSkipping { |
| 13 | + /// Instructs the parquet reader to perform row group skipping, eliminating any row group whose |
| 14 | + /// stats prove that none of the group's rows can satisfy the given `predicate`. |
| 15 | + fn with_row_group_filter(self, predicate: &Expression) -> Self; |
| 16 | +} |
| 17 | +impl<T> ParquetRowGroupSkipping for ArrowReaderBuilder<T> { |
| 18 | + fn with_row_group_filter(self, predicate: &Expression) -> Self { |
| 19 | + let indices = self |
| 20 | + .metadata() |
| 21 | + .row_groups() |
| 22 | + .iter() |
| 23 | + .enumerate() |
| 24 | + .filter_map(|(index, row_group)| { |
| 25 | + RowGroupFilter::apply(predicate, row_group).then_some(index) |
| 26 | + }) |
| 27 | + .collect(); |
| 28 | + self.with_row_groups(indices) |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +/// A ParquetStatsSkippingFilter for row group skipping. It obtains stats from a parquet |
| 33 | +/// [`RowGroupMetaData`] and pre-computes the mapping of each referenced column path to its |
| 34 | +/// corresponding field index, for O(1) stats lookups. |
| 35 | +struct RowGroupFilter<'a> { |
| 36 | + row_group: &'a RowGroupMetaData, |
| 37 | + field_indices: HashMap<ColumnPath, usize>, |
| 38 | +} |
| 39 | + |
| 40 | +impl<'a> RowGroupFilter<'a> { |
| 41 | + /// Applies a filtering expression to a row group. Return value false means to skip it. |
| 42 | + fn apply(filter: &Expression, row_group: &'a RowGroupMetaData) -> bool { |
| 43 | + let field_indices = compute_field_indices(row_group.schema_descr().columns(), filter); |
| 44 | + let result = Self { |
| 45 | + row_group, |
| 46 | + field_indices, |
| 47 | + } |
| 48 | + .apply_sql_where(filter); |
| 49 | + !matches!(result, Some(false)) |
| 50 | + } |
| 51 | + |
| 52 | + fn get_stats(&self, col: &ColumnPath) -> Option<&Statistics> { |
| 53 | + let field_index = self.field_indices.get(col)?; |
| 54 | + self.row_group.column(*field_index).statistics() |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +impl<'a> ParquetStatsSkippingFilter for RowGroupFilter<'a> { |
| 59 | + // Extracts a stat value, converting from its physical type to the requested logical type. |
| 60 | + // |
| 61 | + // NOTE: This code is highly redundant with [`get_min_stat_value`], but parquet |
| 62 | + // ValueStatistics<T> requires T to impl a private trait, so we can't factor out any kind of |
| 63 | + // helper method. And macros are hard enough to read that it's not worth defining one. |
| 64 | + fn get_min_stat_value(&self, col: &ColumnPath, data_type: &DataType) -> Option<Scalar> { |
| 65 | + use PrimitiveType::*; |
| 66 | + let value = match (data_type.as_primitive_opt()?, self.get_stats(col)?) { |
| 67 | + (String, Statistics::ByteArray(s)) => s.min_opt()?.as_utf8().ok()?.into(), |
| 68 | + (String, Statistics::FixedLenByteArray(s)) => s.min_opt()?.as_utf8().ok()?.into(), |
| 69 | + (String, _) => None?, |
| 70 | + (Long, Statistics::Int64(s)) => s.min_opt()?.into(), |
| 71 | + (Long, Statistics::Int32(s)) => (*s.min_opt()? as i64).into(), |
| 72 | + (Long, _) => None?, |
| 73 | + (Integer, Statistics::Int32(s)) => s.min_opt()?.into(), |
| 74 | + (Integer, _) => None?, |
| 75 | + (Short, Statistics::Int32(s)) => (*s.min_opt()? as i16).into(), |
| 76 | + (Short, _) => None?, |
| 77 | + (Byte, Statistics::Int32(s)) => (*s.min_opt()? as i8).into(), |
| 78 | + (Byte, _) => None?, |
| 79 | + (Float, Statistics::Float(s)) => s.min_opt()?.into(), |
| 80 | + (Float, _) => None?, |
| 81 | + (Double, Statistics::Double(s)) => s.min_opt()?.into(), |
| 82 | + (Double, _) => None?, |
| 83 | + (Boolean, Statistics::Boolean(s)) => s.min_opt()?.into(), |
| 84 | + (Boolean, _) => None?, |
| 85 | + (Binary, Statistics::ByteArray(s)) => s.min_opt()?.data().into(), |
| 86 | + (Binary, Statistics::FixedLenByteArray(s)) => s.min_opt()?.data().into(), |
| 87 | + (Binary, _) => None?, |
| 88 | + (Date, Statistics::Int32(s)) => Scalar::Date(*s.min_opt()?), |
| 89 | + (Date, _) => None?, |
| 90 | + (Timestamp, Statistics::Int64(s)) => Scalar::Timestamp(*s.min_opt()?), |
| 91 | + (Timestamp, _) => None?, // TODO: Int96 timestamps |
| 92 | + (TimestampNtz, Statistics::Int64(s)) => Scalar::TimestampNtz(*s.min_opt()?), |
| 93 | + (TimestampNtz, _) => None?, // TODO: Int96 timestamps |
| 94 | + (Decimal(..), _) => None?, // TODO: Decimal (Int32, Int64, FixedLenByteArray) |
| 95 | + }; |
| 96 | + Some(value) |
| 97 | + } |
| 98 | + |
| 99 | + fn get_max_stat_value(&self, col: &ColumnPath, data_type: &DataType) -> Option<Scalar> { |
| 100 | + use PrimitiveType::*; |
| 101 | + let value = match (data_type.as_primitive_opt()?, self.get_stats(col)?) { |
| 102 | + (String, Statistics::ByteArray(s)) => s.max_opt()?.as_utf8().ok()?.into(), |
| 103 | + (String, Statistics::FixedLenByteArray(s)) => s.max_opt()?.as_utf8().ok()?.into(), |
| 104 | + (String, _) => None?, |
| 105 | + (Long, Statistics::Int64(s)) => s.max_opt()?.into(), |
| 106 | + (Long, Statistics::Int32(s)) => (*s.max_opt()? as i64).into(), |
| 107 | + (Long, _) => None?, |
| 108 | + (Integer, Statistics::Int32(s)) => s.max_opt()?.into(), |
| 109 | + (Integer, _) => None?, |
| 110 | + (Short, Statistics::Int32(s)) => (*s.max_opt()? as i16).into(), |
| 111 | + (Short, _) => None?, |
| 112 | + (Byte, Statistics::Int32(s)) => (*s.max_opt()? as i8).into(), |
| 113 | + (Byte, _) => None?, |
| 114 | + (Float, Statistics::Float(s)) => s.max_opt()?.into(), |
| 115 | + (Float, _) => None?, |
| 116 | + (Double, Statistics::Double(s)) => s.max_opt()?.into(), |
| 117 | + (Double, _) => None?, |
| 118 | + (Boolean, Statistics::Boolean(s)) => s.max_opt()?.into(), |
| 119 | + (Boolean, _) => None?, |
| 120 | + (Binary, Statistics::ByteArray(s)) => s.max_opt()?.data().into(), |
| 121 | + (Binary, Statistics::FixedLenByteArray(s)) => s.max_opt()?.data().into(), |
| 122 | + (Binary, _) => None?, |
| 123 | + (Date, Statistics::Int32(s)) => Scalar::Date(*s.max_opt()?), |
| 124 | + (Date, _) => None?, |
| 125 | + (Timestamp, Statistics::Int64(s)) => Scalar::Timestamp(*s.max_opt()?), |
| 126 | + (Timestamp, _) => None?, // TODO: Int96 timestamps |
| 127 | + (TimestampNtz, Statistics::Int64(s)) => Scalar::TimestampNtz(*s.max_opt()?), |
| 128 | + (TimestampNtz, _) => None?, // TODO: Int96 timestamps |
| 129 | + (Decimal(..), _) => None?, // TODO: Decimal (Int32, Int64, FixedLenByteArray) |
| 130 | + }; |
| 131 | + Some(value) |
| 132 | + } |
| 133 | + |
| 134 | + // Parquet nullcount stats always have the same type (u64), so we can directly return the value |
| 135 | + // instead of wrapping it in a Scalar. We can safely cast it from u64 to i64, because the |
| 136 | + // nullcount can never be larger than the rowcount, and the parquet rowcount stat is i64. |
| 137 | + fn get_nullcount_stat_value(&self, col: &ColumnPath) -> Option<i64> { |
| 138 | + Some(self.get_stats(col)?.null_count_opt()? as i64) |
| 139 | + } |
| 140 | + |
| 141 | + fn get_rowcount_stat_value(&self) -> i64 { |
| 142 | + self.row_group.num_rows() |
| 143 | + } |
| 144 | +} |
| 145 | + |
| 146 | +/// Given a filter expression of interest and a set of parquet column descriptors, build a column -> |
| 147 | +/// index mapping for columns the expression references. This ensures O(1) lookup times, for an |
| 148 | +/// overall O(n) cost to evaluate an expression tree with n nodes. |
| 149 | +pub(crate) fn compute_field_indices( |
| 150 | + fields: &[ColumnDescPtr], |
| 151 | + expression: &Expression, |
| 152 | +) -> HashMap<ColumnPath, usize> { |
| 153 | + fn do_recurse(expression: &Expression, cols: &mut HashSet<ColumnPath>) { |
| 154 | + use Expression::*; |
| 155 | + let mut recurse = |expr| do_recurse(expr, cols); // less arg passing below |
| 156 | + match expression { |
| 157 | + Literal(_) => {} |
| 158 | + Column(name) => drop(cols.insert(col_name_to_path(name))), |
| 159 | + Struct(fields) => fields.iter().for_each(recurse), |
| 160 | + UnaryOperation { expr, .. } => recurse(expr), |
| 161 | + BinaryOperation { left, right, .. } => [left, right].iter().for_each(|e| recurse(e)), |
| 162 | + VariadicOperation { exprs, .. } => exprs.iter().for_each(recurse), |
| 163 | + } |
| 164 | + } |
| 165 | + |
| 166 | + // Build up a set of requested column paths, then take each found path as the corresponding map |
| 167 | + // key (avoids unnecessary cloning). |
| 168 | + // |
| 169 | + // NOTE: If a requested column was not available, it is silently ignored. |
| 170 | + let mut requested_columns = HashSet::new(); |
| 171 | + do_recurse(expression, &mut requested_columns); |
| 172 | + fields |
| 173 | + .iter() |
| 174 | + .enumerate() |
| 175 | + .filter_map(|(i, f)| requested_columns.take(f.path()).map(|path| (path, i))) |
| 176 | + .collect() |
| 177 | +} |
0 commit comments