|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +use arrow::array::{ArrayRef, BooleanArray, Int32Array}; |
| 19 | +use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; |
| 20 | +use datafusion::common::{DFSchema, ScalarValue}; |
| 21 | +use datafusion::execution::context::ExecutionProps; |
| 22 | +use datafusion::physical_expr::create_physical_expr; |
| 23 | +use datafusion::physical_optimizer::pruning::{PruningPredicate, PruningStatistics}; |
| 24 | +use datafusion::prelude::*; |
| 25 | +use std::collections::HashSet; |
| 26 | +use std::sync::Arc; |
| 27 | + |
| 28 | +/// This example shows how to use DataFusion's `PruningPredicate` to prove |
| 29 | +/// filter expressions can never be true based on statistics such as min/max |
| 30 | +/// values of columns. |
| 31 | +/// |
| 32 | +/// The process is called "pruning" and is commonly used in query engines to |
| 33 | +/// quickly eliminate entire files / partitions / row groups of data from |
| 34 | +/// consideration using statistical information from a catalog or other |
| 35 | +/// metadata. |
| 36 | +#[tokio::main] |
| 37 | +async fn main() { |
| 38 | + // In this example, we'll use the PruningPredicate to determine if |
| 39 | + // the expression `x = 5 AND y = 10` can never be true based on statistics |
| 40 | + |
| 41 | + // Start with the expression `x = 5 AND y = 10` |
| 42 | + let expr = col("x").eq(lit(5)).and(col("y").eq(lit(10))); |
| 43 | + |
| 44 | + // We can analyze this predicate using information provided by the |
| 45 | + // `PruningStatistics` trait, in this case we'll use a simple catalog that |
| 46 | + // models three files. For all rows in each file: |
| 47 | + // |
| 48 | + // File 1: x has values between `4` and `6` |
| 49 | + // y has the value 10 |
| 50 | + // |
| 51 | + // File 2: x has values between `4` and `6` |
| 52 | + // y has the value of `7` |
| 53 | + // |
| 54 | + // File 3: x has the value 1 |
| 55 | + // nothing is known about the value of y |
| 56 | + let my_catalog = MyCatalog::new(); |
| 57 | + |
| 58 | + // Create a `PruningPredicate`. |
| 59 | + // |
| 60 | + // Note the predicate does not automatically coerce types or simplify |
| 61 | + // expressions. See expr_api.rs examples for how to do this if required |
| 62 | + let predicate = create_pruning_predicate(expr, &my_catalog.schema); |
| 63 | + |
| 64 | + // Evaluate the predicate for the three files in the catalog |
| 65 | + let prune_results = predicate.prune(&my_catalog).unwrap(); |
| 66 | + println!("Pruning results: {prune_results:?}"); |
| 67 | + |
| 68 | + // The result is a `Vec` of bool values, one for each file in the catalog |
| 69 | + assert_eq!( |
| 70 | + prune_results, |
| 71 | + vec![ |
| 72 | + // File 1: `x = 5 AND y = 10` can evaluate to true if x has values |
| 73 | + // between `4` and `6`, y has the value `10`, so the file can not be |
| 74 | + // skipped |
| 75 | + // |
| 76 | + // NOTE this doesn't mean there actually are rows that evaluate to |
| 77 | + // true, but the pruning predicate can't prove there aren't any. |
| 78 | + true, |
| 79 | + // File 2: `x = 5 AND y = 10` can never evaluate to true because y |
| 80 | + // has only the value of 7. Thus this file can be skipped. |
| 81 | + false, |
| 82 | + // File 3: `x = 5 AND y = 10` can never evaluate to true because x |
| 83 | + // has the value `1`, and for any value of `y` the expression will |
| 84 | + // evaluate to false (`x = 5 AND y = 10 -->` false AND null` --> `false`). Thus this file can also be |
| 85 | + // skipped. |
| 86 | + false |
| 87 | + ] |
| 88 | + ); |
| 89 | +} |
| 90 | + |
| 91 | +/// A simple model catalog that has information about the three files that store |
| 92 | +/// data for a table with two columns (x and y). |
| 93 | +struct MyCatalog { |
| 94 | + schema: SchemaRef, |
| 95 | + // (min, max) for x |
| 96 | + x_values: Vec<(Option<i32>, Option<i32>)>, |
| 97 | + // (min, max) for y |
| 98 | + y_values: Vec<(Option<i32>, Option<i32>)>, |
| 99 | +} |
| 100 | +impl MyCatalog { |
| 101 | + fn new() -> Self { |
| 102 | + MyCatalog { |
| 103 | + schema: Arc::new(Schema::new(vec![ |
| 104 | + Field::new("x", DataType::Int32, false), |
| 105 | + Field::new("y", DataType::Int32, false), |
| 106 | + ])), |
| 107 | + x_values: vec![ |
| 108 | + // File 1: x has values between `4` and `6` |
| 109 | + (Some(4), Some(6)), |
| 110 | + // File 2: x has values between `4` and `6` |
| 111 | + (Some(4), Some(6)), |
| 112 | + // File 3: x has the value 1 |
| 113 | + (Some(1), Some(1)), |
| 114 | + ], |
| 115 | + y_values: vec![ |
| 116 | + // File 1: y has the value 10 |
| 117 | + (Some(10), Some(10)), |
| 118 | + // File 2: y has the value of `7` |
| 119 | + (Some(7), Some(7)), |
| 120 | + // File 3: nothing is known about the value of y. This is |
| 121 | + // represented as (None, None). |
| 122 | + // |
| 123 | + // Note, returning null means the value isn't known, NOT |
| 124 | + // that we know the entire column is null. |
| 125 | + (None, None), |
| 126 | + ], |
| 127 | + } |
| 128 | + } |
| 129 | +} |
| 130 | + |
| 131 | +/// We communicate the statistical information to DataFusion by implementing the |
| 132 | +/// PruningStatistics trait. |
| 133 | +impl PruningStatistics for MyCatalog { |
| 134 | + fn num_containers(&self) -> usize { |
| 135 | + // there are 3 files in this "catalog", and thus each array returned |
| 136 | + // from min_values and max_values also has 3 elements |
| 137 | + 3 |
| 138 | + } |
| 139 | + |
| 140 | + fn min_values(&self, column: &Column) -> Option<ArrayRef> { |
| 141 | + // The pruning predicate evaluates the bounds for multiple expressions |
| 142 | + // at once, so return an array with an element for the minimum value in |
| 143 | + // each file |
| 144 | + match column.name.as_str() { |
| 145 | + "x" => Some(i32_array(self.x_values.iter().map(|(min, _)| min))), |
| 146 | + "y" => Some(i32_array(self.y_values.iter().map(|(min, _)| min))), |
| 147 | + name => panic!("unknown column name: {name}"), |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + fn max_values(&self, column: &Column) -> Option<ArrayRef> { |
| 152 | + // similarly to min_values, return an array with an element for the |
| 153 | + // maximum value in each file |
| 154 | + match column.name.as_str() { |
| 155 | + "x" => Some(i32_array(self.x_values.iter().map(|(_, max)| max))), |
| 156 | + "y" => Some(i32_array(self.y_values.iter().map(|(_, max)| max))), |
| 157 | + name => panic!("unknown column name: {name}"), |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + fn null_counts(&self, _column: &Column) -> Option<ArrayRef> { |
| 162 | + // In this example, we know nothing about the number of nulls |
| 163 | + None |
| 164 | + } |
| 165 | + |
| 166 | + fn contained( |
| 167 | + &self, |
| 168 | + _column: &Column, |
| 169 | + _values: &HashSet<ScalarValue>, |
| 170 | + ) -> Option<BooleanArray> { |
| 171 | + // this method can be used to implement Bloom filter like filtering |
| 172 | + // but we do not illustrate that here |
| 173 | + None |
| 174 | + } |
| 175 | +} |
| 176 | + |
| 177 | +fn create_pruning_predicate(expr: Expr, schema: &SchemaRef) -> PruningPredicate { |
| 178 | + let df_schema = DFSchema::try_from(schema.as_ref().clone()).unwrap(); |
| 179 | + let props = ExecutionProps::new(); |
| 180 | + let physical_expr = create_physical_expr(&expr, &df_schema, &props).unwrap(); |
| 181 | + PruningPredicate::try_new(physical_expr, schema.clone()).unwrap() |
| 182 | +} |
| 183 | + |
| 184 | +fn i32_array<'a>(values: impl Iterator<Item = &'a Option<i32>>) -> ArrayRef { |
| 185 | + Arc::new(Int32Array::from_iter(values.cloned())) |
| 186 | +} |
0 commit comments