-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Simplify predicates in PushDownFilter
optimizer rule
#16362
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
xudong963
wants to merge
8
commits into
apache:main
Choose a base branch
from
xudong963:simplify_predicates
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+513
−8
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
577e66a
Simplify predicates in filter
xudong963 29481a1
add slt test
xudong963 0ee6f6a
Use BtreeMap to make tests stable
xudong963 2aeae2e
process edge coner
xudong963 253bdb8
add doc for simplify_predicates.rs
xudong963 fc32e8e
add as_literal to make code neat
xudong963 ac0ec27
reorgnize file
xudong963 123ef69
reduce clone call
xudong963 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
247 changes: 247 additions & 0 deletions
247
datafusion/optimizer/src/simplify_expressions/simplify_predicates.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,247 @@ | ||
// Licensed to the Apache Software Foundation (ASF) under one | ||
// or more contributor license agreements. See the NOTICE file | ||
// distributed with this work for additional information | ||
// regarding copyright ownership. The ASF licenses this file | ||
// to you under the Apache License, Version 2.0 (the | ||
// "License"); you may not use this file except in compliance | ||
// with the License. You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, | ||
// software distributed under the License is distributed on an | ||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
// KIND, either express or implied. See the License for the | ||
// specific language governing permissions and limitations | ||
// under the License. | ||
|
||
//! Simplifies predicates by reducing redundant or overlapping conditions. | ||
//! | ||
//! This module provides functionality to optimize logical predicates used in query planning | ||
//! by eliminating redundant conditions, thus reducing the number of predicates to evaluate. | ||
//! Unlike the simplifier in `simplify_expressions/simplify_exprs.rs`, which focuses on | ||
//! general expression simplification (e.g., constant folding and algebraic simplifications), | ||
//! this module specifically targets predicate optimization by handling containment relationships. | ||
//! For example, it can simplify `x > 5 AND x > 6` to just `x > 6`, as the latter condition | ||
//! encompasses the former, resulting in fewer checks during query execution. | ||
|
||
use datafusion_common::{Column, Result, ScalarValue}; | ||
use datafusion_expr::{BinaryExpr, Cast, Expr, Operator}; | ||
use std::collections::BTreeMap; | ||
|
||
/// Simplifies a list of predicates by removing redundancies. | ||
/// | ||
/// This function takes a vector of predicate expressions and groups them by the column they reference. | ||
/// Predicates that reference a single column and are comparison operations (e.g., >, >=, <, <=, =) | ||
/// are analyzed to remove redundant conditions. For instance, `x > 5 AND x > 6` is simplified to | ||
/// `x > 6`. Other predicates that do not fit this pattern are retained as-is. | ||
/// | ||
/// # Arguments | ||
/// * `predicates` - A vector of `Expr` representing the predicates to simplify. | ||
/// | ||
/// # Returns | ||
/// A `Result` containing a vector of simplified `Expr` predicates. | ||
pub fn simplify_predicates(predicates: Vec<Expr>) -> Result<Vec<Expr>> { | ||
// Early return for simple cases | ||
if predicates.len() <= 1 { | ||
return Ok(predicates); | ||
} | ||
|
||
// Group predicates by their column reference | ||
let mut column_predicates: BTreeMap<Column, Vec<Expr>> = BTreeMap::new(); | ||
let mut other_predicates = Vec::new(); | ||
|
||
for pred in predicates { | ||
match &pred { | ||
Expr::BinaryExpr(BinaryExpr { | ||
left, | ||
op: | ||
Operator::Gt | ||
| Operator::GtEq | ||
| Operator::Lt | ||
| Operator::LtEq | ||
| Operator::Eq, | ||
right, | ||
}) => { | ||
let left_col = extract_column_from_expr(left); | ||
let right_col = extract_column_from_expr(right); | ||
if let (Some(col), Some(_)) = (&left_col, right.as_literal()) { | ||
column_predicates.entry(col.clone()).or_default().push(pred); | ||
} else if let (Some(_), Some(col)) = (left.as_literal(), &right_col) { | ||
column_predicates.entry(col.clone()).or_default().push(pred); | ||
} else { | ||
other_predicates.push(pred); | ||
} | ||
} | ||
_ => other_predicates.push(pred), | ||
} | ||
} | ||
|
||
// Process each column's predicates to remove redundancies | ||
let mut result = other_predicates; | ||
for (_, preds) in column_predicates { | ||
let simplified = simplify_column_predicates(preds)?; | ||
result.extend(simplified); | ||
} | ||
|
||
Ok(result) | ||
} | ||
|
||
/// Simplifies predicates related to a single column. | ||
/// | ||
/// This function processes a list of predicates that all reference the same column and | ||
/// simplifies them based on their operators. It groups predicates into greater-than (>, >=), | ||
/// less-than (<, <=), and equality (=) categories, then selects the most restrictive condition | ||
/// in each category to reduce redundancy. For example, among `x > 5` and `x > 6`, only `x > 6` | ||
/// is retained as it is more restrictive. | ||
/// | ||
/// # Arguments | ||
/// * `predicates` - A vector of `Expr` representing predicates for a single column. | ||
/// | ||
/// # Returns | ||
/// A `Result` containing a vector of simplified `Expr` predicates for the column. | ||
fn simplify_column_predicates(predicates: Vec<Expr>) -> Result<Vec<Expr>> { | ||
if predicates.len() <= 1 { | ||
return Ok(predicates); | ||
} | ||
|
||
// Group by operator type, but combining similar operators | ||
let mut greater_predicates = Vec::new(); // Combines > and >= | ||
let mut less_predicates = Vec::new(); // Combines < and <= | ||
let mut eq_predicates = Vec::new(); | ||
|
||
for pred in predicates { | ||
match &pred { | ||
Expr::BinaryExpr(BinaryExpr { left: _, op, right }) => { | ||
match (op, right.as_literal().is_some()) { | ||
(Operator::Gt, true) | ||
| (Operator::Lt, false) | ||
| (Operator::GtEq, true) | ||
| (Operator::LtEq, false) => greater_predicates.push(pred), | ||
(Operator::Lt, true) | ||
| (Operator::Gt, false) | ||
| (Operator::LtEq, true) | ||
| (Operator::GtEq, false) => less_predicates.push(pred), | ||
(Operator::Eq, _) => eq_predicates.push(pred), | ||
_ => unreachable!("Unexpected operator: {}", op), | ||
} | ||
} | ||
_ => unreachable!("Unexpected predicate {}", pred.to_string()), | ||
} | ||
} | ||
|
||
let mut result = Vec::new(); | ||
|
||
if !eq_predicates.is_empty() { | ||
// If there are many equality predicates, we can only keep one if they are all the same | ||
if eq_predicates.len() == 1 | ||
|| eq_predicates.iter().all(|e| e == &eq_predicates[0]) | ||
{ | ||
result.push(eq_predicates.pop().unwrap()); | ||
} else { | ||
// If they are not the same, add a false predicate | ||
result.push(Expr::Literal(ScalarValue::Boolean(Some(false)), None)); | ||
} | ||
} | ||
|
||
// Handle all greater-than-style predicates (keep the most restrictive - highest value) | ||
if !greater_predicates.is_empty() { | ||
if let Some(most_restrictive) = | ||
find_most_restrictive_predicate(&greater_predicates, true)? | ||
{ | ||
result.push(most_restrictive); | ||
} else { | ||
result.extend(greater_predicates); | ||
} | ||
} | ||
|
||
// Handle all less-than-style predicates (keep the most restrictive - lowest value) | ||
if !less_predicates.is_empty() { | ||
if let Some(most_restrictive) = | ||
find_most_restrictive_predicate(&less_predicates, false)? | ||
{ | ||
result.push(most_restrictive); | ||
} else { | ||
result.extend(less_predicates); | ||
} | ||
} | ||
|
||
Ok(result) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As a follow on, once a |
||
} | ||
|
||
/// Finds the most restrictive predicate from a list based on literal values. | ||
/// | ||
/// This function iterates through a list of predicates to identify the most restrictive one | ||
/// by comparing their literal values. For greater-than predicates, the highest value is most | ||
/// restrictive, while for less-than predicates, the lowest value is most restrictive. | ||
/// | ||
/// # Arguments | ||
/// * `predicates` - A slice of `Expr` representing predicates to compare. | ||
/// * `find_greater` - A boolean indicating whether to find the highest value (true for >, >=) | ||
/// or the lowest value (false for <, <=). | ||
/// | ||
/// # Returns | ||
/// A `Result` containing an `Option<Expr>` with the most restrictive predicate, if any. | ||
fn find_most_restrictive_predicate( | ||
predicates: &[Expr], | ||
find_greater: bool, | ||
) -> Result<Option<Expr>> { | ||
if predicates.is_empty() { | ||
return Ok(None); | ||
} | ||
|
||
let mut most_restrictive_idx = 0; | ||
let mut best_value: Option<&ScalarValue> = None; | ||
|
||
for (idx, pred) in predicates.iter().enumerate() { | ||
if let Expr::BinaryExpr(BinaryExpr { left, op: _, right }) = pred { | ||
// Extract the literal value based on which side has it | ||
let scalar_value = match (right.as_literal(), left.as_literal()) { | ||
(Some(scalar), _) => Some(scalar), | ||
(_, Some(scalar)) => Some(scalar), | ||
_ => None, | ||
}; | ||
|
||
if let Some(scalar) = scalar_value { | ||
if let Some(current_best) = best_value { | ||
if let Some(comparison) = scalar.partial_cmp(current_best) { | ||
let is_better = if find_greater { | ||
comparison == std::cmp::Ordering::Greater | ||
} else { | ||
comparison == std::cmp::Ordering::Less | ||
}; | ||
|
||
if is_better { | ||
best_value = Some(scalar); | ||
most_restrictive_idx = idx; | ||
} | ||
} | ||
} else { | ||
best_value = Some(scalar); | ||
most_restrictive_idx = idx; | ||
} | ||
} | ||
} | ||
} | ||
|
||
Ok(Some(predicates[most_restrictive_idx].clone())) | ||
} | ||
|
||
/// Extracts a column reference from an expression, if present. | ||
/// | ||
/// This function checks if the given expression is a column reference or contains one, | ||
/// such as within a cast operation. It returns the `Column` if found. | ||
/// | ||
/// # Arguments | ||
/// * `expr` - A reference to an `Expr` to inspect for a column reference. | ||
/// | ||
/// # Returns | ||
/// An `Option<Column>` containing the column reference if found, otherwise `None`. | ||
fn extract_column_from_expr(expr: &Expr) -> Option<Column> { | ||
match expr { | ||
Expr::Column(col) => Some(col.clone()), | ||
// Handle cases where the column might be wrapped in a cast or other operation | ||
Expr::Cast(Cast { expr, .. }) => extract_column_from_expr(expr), | ||
_ => None, | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
new_predicates
operates oncol comparison_operator literal
sometimes these are tied in conjuncts:
a > -5 AND a < 5
or disjuncts:a < -5 OR a > 5
would it make sense to be able to process per-column predicates in both forms?
To do that we could have a function Expr -> captured per-column predicates and then be able to combine such functions on AND and on OR
This might be related https://github.com/trinodb/trino/blob/232916b75d415a5eb643cf922492eb8513d99aae/core/trino-main/src/main/java/io/trino/sql/planner/DomainTranslator.java#L365
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
a > -5 AND a < 5
will be split to [a > -5
,a < 5
], it seems that the two split predicates can't be simplified, that is, we shoud keep the two.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sure, but if I can have
a < -5 OR a > 5
then maybe I can havea < -5 OR a > 5 OR a < -10 OR a > 10
. This is simplifiable.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Okay, good point, we can do this as the following PR
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think we could use the cp_solver approach to handle expressions more generally and I also agree this could / should be done in a follow on PR
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I open an issue to track: #16511