Skip to main content

common_recordbatch/
filter.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Precise single-column predicates and record batch filtering.
16
17mod predicate;
18#[cfg(test)]
19mod tests;
20mod timestamp;
21
22use std::borrow::Borrow;
23use std::sync::Arc;
24
25use datafusion::error::Result as DfResult;
26use datafusion::logical_expr::{Expr, Literal, Operator, utils};
27use datafusion::physical_plan::PhysicalExpr;
28use datafusion_common::arrow::array::{ArrayRef, Datum, Scalar};
29use datafusion_common::arrow::buffer::BooleanBuffer;
30use datafusion_common::cast::{as_boolean_array, as_null_array};
31use datafusion_common::{DataFusionError, ScalarValue, internal_err};
32use datatypes::arrow::array::{Array, BooleanArray, BooleanBufferBuilder, RecordBatch};
33use datatypes::arrow::compute::filter_record_batch;
34use datatypes::arrow::datatypes::DataType;
35use datatypes::data_type::{ConcreteDataType, DataType as _};
36use datatypes::value::Value;
37use datatypes::vectors::VectorRef;
38use snafu::ResultExt;
39
40pub use self::predicate::{CompiledRegex, regexp_is_match_dictionary, regexp_is_match_scalar};
41pub use self::timestamp::timestamp_scalar_value;
42use crate::error::{Result, ToArrowScalarSnafu};
43use crate::filter::predicate::SimplePredicate;
44
45/// Prunes candidates using known metadata columns. Missing columns and unsupported
46/// predicates cannot exclude a candidate. Complete SQL predicates must still run
47/// after pruning.
48#[derive(Debug, Clone, Default)]
49pub struct MetadataFilter {
50    filters: Arc<[SimpleFilterEvaluator]>,
51}
52
53impl MetadataFilter {
54    /// Builds supported conjuncts once for reuse across scan stages; regex patterns compile on
55    /// first evaluation. OR is never split: an unknown alternative might match the candidate.
56    pub fn new(expressions: &[Expr]) -> Self {
57        Self {
58            filters: expressions
59                .iter()
60                .flat_map(utils::split_conjunction)
61                .filter_map(SimpleFilterEvaluator::try_new)
62                .collect(),
63        }
64    }
65
66    /// Returns false only when known metadata proves a conjunct cannot match.
67    /// `None` means unavailable metadata, distinct from a known SQL NULL scalar.
68    /// Values may be borrowed so repeated predicates can reuse allocated strings.
69    pub fn matches<T: Borrow<ScalarValue>>(
70        &self,
71        mut value: impl FnMut(&str) -> Option<T>,
72    ) -> bool {
73        self.filters.iter().all(|filter| {
74            value(filter.column_name())
75                .is_none_or(|value| filter.evaluate_scalar(value.borrow()).unwrap_or(true))
76        })
77    }
78}
79
80/// Evaluates supported single-column predicates with lazily compiled regular expressions.
81/// Compound predicates preserve SQL null semantics until conversion to a scan mask.
82/// Float comparisons treat `-0.0` and `+0.0` as equal, as DataFusion does.
83#[derive(Debug, Clone)]
84pub struct SimpleFilterEvaluator {
85    column_name: String,
86    predicate: SimplePredicate,
87}
88
89impl SimpleFilterEvaluator {
90    pub fn new<T: Literal>(column_name: String, lit: T, op: Operator) -> Option<Self> {
91        if !matches!(
92            op,
93            Operator::Eq
94                | Operator::NotEq
95                | Operator::Lt
96                | Operator::LtEq
97                | Operator::Gt
98                | Operator::GtEq
99        ) {
100            return None;
101        }
102        let Expr::Literal(value, _) = lit.lit() else {
103            return None;
104        };
105        Some(Self {
106            column_name,
107            predicate: SimplePredicate::Comparison {
108                literal: datafusion_common::utils::normalize_float_zero_scalar(value)
109                    .to_scalar()
110                    .ok()?,
111                op,
112                regex: None,
113                regex_negative: false,
114            },
115        })
116    }
117
118    pub fn try_new(predicate: &Expr) -> Option<Self> {
119        Self::try_new_with_column_type(predicate, &|_| None)
120    }
121
122    /// Recognizes single-column filters, including lossless string dictionary casts
123    /// when the caller can resolve the column's type.
124    pub fn try_new_with_column_type(
125        predicate: &Expr,
126        column_type: &impl Fn(&str) -> Option<DataType>,
127    ) -> Option<Self> {
128        let columns = predicate.column_refs();
129        if columns.len() != 1 {
130            return None;
131        }
132        let column_name = columns.into_iter().next()?.name.clone();
133        let column_type = column_type(&column_name);
134        Some(Self {
135            column_name,
136            predicate: SimplePredicate::try_new(predicate, column_type.as_ref())?,
137        })
138    }
139
140    /// Returns the referenced column name.
141    pub fn column_name(&self) -> &str {
142        &self.column_name
143    }
144
145    pub fn is_eq(&self) -> bool {
146        matches!(
147            self.predicate,
148            SimplePredicate::Comparison {
149                op: Operator::Eq,
150                ..
151            }
152        )
153    }
154    pub fn is_not_eq(&self) -> bool {
155        matches!(
156            self.predicate,
157            SimplePredicate::Comparison {
158                op: Operator::NotEq,
159                ..
160            }
161        )
162    }
163    pub fn is_lt(&self) -> bool {
164        matches!(
165            self.predicate,
166            SimplePredicate::Comparison {
167                op: Operator::Lt,
168                ..
169            }
170        )
171    }
172    pub fn is_lt_eq(&self) -> bool {
173        matches!(
174            self.predicate,
175            SimplePredicate::Comparison {
176                op: Operator::LtEq,
177                ..
178            }
179        )
180    }
181    pub fn is_gt(&self) -> bool {
182        matches!(
183            self.predicate,
184            SimplePredicate::Comparison {
185                op: Operator::Gt,
186                ..
187            }
188        )
189    }
190    pub fn is_gt_eq(&self) -> bool {
191        matches!(
192            self.predicate,
193            SimplePredicate::Comparison {
194                op: Operator::GtEq,
195                ..
196            }
197        )
198    }
199
200    /// Returns true for an OR chain of equality comparisons.
201    pub fn is_or_eq_chain(&self) -> bool {
202        matches!(self.predicate, SimplePredicate::OrEqChain { .. })
203    }
204
205    /// Returns the literal of a bare comparison, without discarding compound conditions.
206    pub fn literal_value(&self) -> Option<Value> {
207        let SimplePredicate::Comparison { literal, .. } = &self.predicate else {
208            return None;
209        };
210        Value::try_from(ScalarValue::try_from_array(literal.get().0, 0).ok()?).ok()
211    }
212
213    /// Returns equality-OR literals, or None for other predicates or unsupported values.
214    pub fn literal_list_values(&self) -> Option<Vec<Value>> {
215        let SimplePredicate::OrEqChain { literals } = &self.predicate else {
216            return None;
217        };
218        literals
219            .iter()
220            .map(|literal| {
221                Value::try_from(ScalarValue::try_from_array(literal.get().0, 0).ok()?).ok()
222            })
223            .collect()
224    }
225
226    pub fn evaluate_scalar(&self, input: &ScalarValue) -> Result<bool> {
227        let input = input
228            .to_scalar()
229            .with_context(|_| ToArrowScalarSnafu { v: input.clone() })?;
230        let input = Scalar::new(datafusion_common::utils::normalize_float_zero(
231            &input.into_inner(),
232        ));
233        Ok(self.evaluate_datum(&input, 1)?.value(0))
234    }
235
236    pub fn evaluate_array(&self, input: &ArrayRef) -> Result<BooleanBuffer> {
237        let input = datafusion_common::utils::normalize_float_zero(input);
238        self.evaluate_datum(&input, input.len())
239    }
240
241    pub fn evaluate_vector(&self, input: &VectorRef) -> Result<BooleanBuffer> {
242        self.evaluate_array(&input.to_arrow_array())
243    }
244
245    fn evaluate_datum(&self, input: &impl Datum, len: usize) -> Result<BooleanBuffer> {
246        let result = self.predicate.evaluate(input, len)?;
247        Ok(boolean_array_to_scan_mask(&result).values().clone())
248    }
249
250    /// Adapts timestamp predicates to an older SST's timestamp unit without rounding
251    /// away boundary rows. Nonrepresentable equality literals cannot match a row.
252    pub fn cast_timestamp_unit(&self, target: &ConcreteDataType) -> Option<TimestampUnitCast> {
253        let DataType::Timestamp(target_unit, _) = target.as_arrow_type() else {
254            return None;
255        };
256        Some(match self.predicate.cast_timestamp_unit(target_unit)? {
257            SimplePredicate::Constant(Some(true)) => TimestampUnitCast::Matched,
258            SimplePredicate::Constant(_) => TimestampUnitCast::Pruned,
259            predicate => TimestampUnitCast::Filter(Self {
260                column_name: self.column_name.clone(),
261                predicate,
262            }),
263        })
264    }
265}
266
267/// The result of casting a [`SimpleFilterEvaluator`] to a different timestamp
268/// unit, preserving the predicate's semantics on rows stored in that unit.
269/// See [`SimpleFilterEvaluator::cast_timestamp_unit`].
270#[derive(Debug, Clone)]
271pub enum TimestampUnitCast {
272    /// The cast filter; evaluates column values stored in the target unit.
273    Filter(SimpleFilterEvaluator),
274    /// No value in the target unit satisfies the filter.
275    Pruned,
276    /// Every value in the target unit satisfies the filter.
277    Matched,
278}
279
280/// Evaluate the predicate on the input [RecordBatch], and return a new [RecordBatch].
281/// Copy from datafusion::physical_plan::src::filter.rs
282pub fn batch_filter(
283    batch: &RecordBatch,
284    predicate: &Arc<dyn PhysicalExpr>,
285) -> DfResult<RecordBatch> {
286    predicate
287        .evaluate(batch)
288        .and_then(|v| v.into_array(batch.num_rows()))
289        .and_then(|array| {
290            let filter_array = match as_boolean_array(&array) {
291                Ok(boolean_array) => Ok(boolean_array.clone()),
292                Err(_) => {
293                    let Ok(null_array) = as_null_array(&array) else {
294                        return internal_err!(
295                            "Cannot create filter_array from non-boolean predicates"
296                        );
297                    };
298
299                    // if the predicate is null, then the result is also null
300                    Ok::<BooleanArray, DataFusionError>(BooleanArray::new_null(null_array.len()))
301                }
302            }?;
303            Ok(filter_record_batch(
304                batch,
305                &boolean_array_to_scan_mask(&filter_array),
306            )?)
307        })
308}
309
310/// Converts nullable SQL predicate values to a scan mask, where `NULL` is `false`.
311fn boolean_array_to_scan_mask(array: &BooleanArray) -> BooleanArray {
312    if array.null_count() == 0 {
313        return array.clone();
314    }
315
316    let mut values = BooleanBufferBuilder::new(array.len());
317    for index in 0..array.len() {
318        values.append(array.is_valid(index) && array.value(index));
319    }
320    BooleanArray::new(values.into(), None)
321}