Apache DataFusion SQL Query Engine
ARROW-9788: [Rust] [DataFusion] Rename SelectionExec to FilterExec
Andy Grove8e4b1d91ea68
diff --git a/rust/datafusion/README.md b/rust/datafusion/README.mdindex 4b8856ec85..8dd8e37b51 100644--- a/rust/datafusion/README.md+++ b/rust/datafusion/README.md@@ -49,7 +49,7 @@ DataFusion includes a simple command-line interactive SQL utility. See the [CLI## SQL Support- [x] Projection-- [x] Selection+- [x] Filter (WHERE)- [x] Limit- [x] Aggregate- [x] UDFsdiff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rsindex aa6610b542..dac32156ca 100644--- a/rust/datafusion/src/execution/context.rs+++ b/rust/datafusion/src/execution/context.rs@@ -565,8 +565,8 @@ mod tests {}#[test]- fn parallel_selection() -> Result<()> {- let tmp_dir = TempDir::new("parallel_selection")?;+ fn parallel_query_with_filter() -> Result<()> {+ let tmp_dir = TempDir::new("parallel_query_with_filter")?;let partition_count = 4;let mut ctx = create_ctx(&tmp_dir, partition_count)?;diff --git a/rust/datafusion/src/execution/dataframe_impl.rs b/rust/datafusion/src/execution/dataframe_impl.rsindex 3d50692e98..61bb57613d 100644--- a/rust/datafusion/src/execution/dataframe_impl.rs+++ b/rust/datafusion/src/execution/dataframe_impl.rs@@ -67,9 +67,11 @@ impl DataFrame for DataFrameImpl {Ok(Arc::new(DataFrameImpl::new(self.ctx_state.clone(), &plan)))}- /// Create a selection based on a filter expression- fn filter(&self, expr: Expr) -> Result<Arc<dyn DataFrame>> {- let plan = LogicalPlanBuilder::from(&self.plan).filter(expr)?.build()?;+ /// Create a filter based on a predicate expression+ fn filter(&self, predicate: Expr) -> Result<Arc<dyn DataFrame>> {+ let plan = LogicalPlanBuilder::from(&self.plan)+ .filter(predicate)?+ .build()?;Ok(Arc::new(DataFrameImpl::new(self.ctx_state.clone(), &plan)))}diff --git a/rust/datafusion/src/execution/physical_plan/expressions.rs b/rust/datafusion/src/execution/physical_plan/expressions.rsindex dff913b916..28915522a5 100644--- a/rust/datafusion/src/execution/physical_plan/expressions.rs+++ b/rust/datafusion/src/execution/physical_plan/expressions.rs@@ -966,11 +966,32 @@ impl fmt::Display for BinaryExpr {impl PhysicalExpr for BinaryExpr {fn data_type(&self, input_schema: &Schema) -> Result<DataType> {- self.left.data_type(input_schema)+ Ok(match self.op {+ Operator::And+ | Operator::Or+ | Operator::Not+ | Operator::NotLike+ | Operator::Like+ | Operator::Lt+ | Operator::LtEq+ | Operator::Eq+ | Operator::NotEq+ | Operator::Gt+ | Operator::GtEq => DataType::Boolean,+ Operator::Plus+ | Operator::Minus+ | Operator::Multiply+ | Operator::Divide+ | Operator::Modulus => {+ // this assumes that the left and right expressions have already been co-coerced+ // to the same type+ self.left.data_type(input_schema)?+ }+ })}fn nullable(&self, _input_schema: &Schema) -> Result<bool> {- // binary operator should always return a boolean value+ // this is not correctOk(false)}diff --git a/rust/datafusion/src/execution/physical_plan/selection.rs b/rust/datafusion/src/execution/physical_plan/filter.rssimilarity index 61%rename from rust/datafusion/src/execution/physical_plan/selection.rsrename to rust/datafusion/src/execution/physical_plan/filter.rsindex 549b38f4e4..f771bd59e7 100644--- a/rust/datafusion/src/execution/physical_plan/selection.rs+++ b/rust/datafusion/src/execution/physical_plan/filter.rs@@ -15,7 +15,8 @@// specific language governing permissions and limitations// under the License.-//! Defines the selection execution plan. A selection filters rows based on a predicate+//! FilterExec evaluates a boolean predicate against all input batches to determine which rows to+//! include in its output batches.use std::sync::{Arc, Mutex};@@ -23,36 +24,43 @@ use crate::error::{ExecutionError, Result};use crate::execution::physical_plan::{ExecutionPlan, Partition, PhysicalExpr};use arrow::array::BooleanArray;use arrow::compute::filter;-use arrow::datatypes::SchemaRef;+use arrow::datatypes::{DataType, SchemaRef};use arrow::error::Result as ArrowResult;use arrow::record_batch::{RecordBatch, RecordBatchReader};-/// Execution plan for a Selection+/// FilterExec evaluates a boolean predicate against all input batches to determine which rows to+/// include in its output batches.#[derive(Debug)]-pub struct SelectionExec {- /// The selection predicate expression- expr: Arc<dyn PhysicalExpr>,+pub struct FilterExec {+ /// The expression to filter on. This expression must evaluate to a boolean value.+ predicate: Arc<dyn PhysicalExpr>,/// The input planinput: Arc<dyn ExecutionPlan>,}-impl SelectionExec {- /// Create a selection on an input+impl FilterExec {+ /// Create a FilterExec on an inputpub fn try_new(- expr: Arc<dyn PhysicalExpr>,+ predicate: Arc<dyn PhysicalExpr>,input: Arc<dyn ExecutionPlan>,) -> Result<Self> {- Ok(Self {- expr: expr.clone(),- input: input.clone(),- })+ match predicate.data_type(input.schema().as_ref())? {+ DataType::Boolean => Ok(Self {+ predicate: predicate.clone(),+ input: input.clone(),+ }),+ other => Err(ExecutionError::General(format!(+ "Filter predicate must return boolean values, not {:?}",+ other+ ))),+ }}}-impl ExecutionPlan for SelectionExec {+impl ExecutionPlan for FilterExec {/// Get the schema for this execution planfn schema(&self) -> SchemaRef {- // The selection operator does not make any changes to the schema of its input+ // The filter operator does not make any changes to the schema of its inputself.input.schema()}@@ -63,10 +71,10 @@ impl ExecutionPlan for SelectionExec {.partitions()?.iter().map(|p| {- let expr = self.expr.clone();- let partition: Arc<dyn Partition> = Arc::new(SelectionPartition {+ let expr = self.predicate.clone();+ let partition: Arc<dyn Partition> = Arc::new(FilterExecPartition {schema: self.input.schema(),- expr,+ predicate: expr,input: p.clone() as Arc<dyn Partition>,});@@ -78,33 +86,40 @@ impl ExecutionPlan for SelectionExec {}}-/// Represents a single partition of a Selection execution plan+/// Represents a single partition of a filter execution plan#[derive(Debug)]-struct SelectionPartition {+struct FilterExecPartition {+ /// Output schema, which is the same as the input schema for this operatorschema: SchemaRef,- expr: Arc<dyn PhysicalExpr>,+ /// The expression to filter on. This expression must evaluate to a boolean value.+ predicate: Arc<dyn PhysicalExpr>,+ /// The input partition to filter.input: Arc<dyn Partition>,}-impl Partition for SelectionPartition {- /// Execute the Selection+impl Partition for FilterExecPartition {+ /// Execute the filterfn execute(&self) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {- Ok(Arc::new(Mutex::new(SelectionIterator {+ Ok(Arc::new(Mutex::new(FilterExecIter {schema: self.schema.clone(),- expr: self.expr.clone(),+ predicate: self.predicate.clone(),input: self.input.execute()?,})))}}-/// Selection iterator-struct SelectionIterator {+/// The FilterExec iterator wraps the input iterator and applies the predicate expression to+/// determine which rows to include in its output batches+struct FilterExecIter {+ /// Output schema, which is the same as the input schema for this operatorschema: SchemaRef,- expr: Arc<dyn PhysicalExpr>,+ /// The expression to filter on. This expression must evaluate to a boolean value.+ predicate: Arc<dyn PhysicalExpr>,+ /// The input partition to filter.input: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,}-impl RecordBatchReader for SelectionIterator {+impl RecordBatchReader for FilterExecIter {/// Get the schemafn schema(&self) -> SchemaRef {self.schema.clone()@@ -115,16 +130,16 @@ impl RecordBatchReader for SelectionIterator {let mut input = self.input.lock().unwrap();match input.next_batch()? {Some(batch) => {- // evaluate the selection predicate to get a boolean array- let predicate_result = self- .expr+ // evaluate the filter predicate to get a boolean array indicating which rows+ // to include in the output+ let result = self+ .predicate.evaluate(&batch).map_err(ExecutionError::into_arrow_external_error)?;- if let Some(f) = predicate_result.as_any().downcast_ref::<BooleanArray>()- {+ if let Some(f) = result.as_any().downcast_ref::<BooleanArray>() {// filter each array- let mut filtered_arrays = vec![];+ let mut filtered_arrays = Vec::with_capacity(batch.num_columns());for i in 0..batch.num_columns() {let array = batch.column(i);let filtered_array = filter(array.as_ref(), f)?;@@ -136,7 +151,7 @@ impl RecordBatchReader for SelectionIterator {)?))} else {Err(ExecutionError::InternalError(- "Predicate evaluated to non-boolean value".to_string(),+ "Filter predicate evaluated to non-boolean value".to_string(),).into_arrow_external_error())}@@ -173,10 +188,10 @@ mod tests {binary(col("c2"), Operator::Lt, lit(ScalarValue::UInt32(4))),);- let selection: Arc<dyn ExecutionPlan> =- Arc::new(SelectionExec::try_new(predicate, Arc::new(csv))?);+ let filter: Arc<dyn ExecutionPlan> =+ Arc::new(FilterExec::try_new(predicate, Arc::new(csv))?);- let results = test::execute(selection.as_ref())?;+ let results = test::execute(filter.as_ref())?;results.iter()diff --git a/rust/datafusion/src/execution/physical_plan/mod.rs b/rust/datafusion/src/execution/physical_plan/mod.rsindex d30c4c70d2..98d2a91a49 100644--- a/rust/datafusion/src/execution/physical_plan/mod.rs+++ b/rust/datafusion/src/execution/physical_plan/mod.rs@@ -110,6 +110,7 @@ pub mod csv;pub mod datasource;pub mod explain;pub mod expressions;+pub mod filter;pub mod hash_aggregate;pub mod limit;pub mod math_expressions;@@ -118,6 +119,5 @@ pub mod merge;pub mod parquet;pub mod planner;pub mod projection;-pub mod selection;pub mod sort;pub mod udf;diff --git a/rust/datafusion/src/execution/physical_plan/planner.rs b/rust/datafusion/src/execution/physical_plan/planner.rsindex 1bcaef47e8..ddb078940d 100644--- a/rust/datafusion/src/execution/physical_plan/planner.rs+++ b/rust/datafusion/src/execution/physical_plan/planner.rs@@ -27,13 +27,13 @@ use crate::execution::physical_plan::explain::ExplainExec;use crate::execution::physical_plan::expressions::{Avg, BinaryExpr, CastExpr, Column, Count, Literal, Max, Min, PhysicalSortExpr, Sum,};+use crate::execution::physical_plan::filter::FilterExec;use crate::execution::physical_plan::hash_aggregate::HashAggregateExec;use crate::execution::physical_plan::limit::GlobalLimitExec;use crate::execution::physical_plan::memory::MemoryExec;use crate::execution::physical_plan::merge::MergeExec;use crate::execution::physical_plan::parquet::ParquetExec;use crate::execution::physical_plan::projection::ProjectionExec;-use crate::execution::physical_plan::selection::SelectionExec;use crate::execution::physical_plan::sort::SortExec;use crate::execution::physical_plan::udf::ScalarFunctionExpr;use crate::execution::physical_plan::{@@ -238,12 +238,17 @@ impl PhysicalPlanner for DefaultPhysicalPlanner {merge,)?))}- LogicalPlan::Selection { input, expr, .. } => {+ LogicalPlan::Filter {+ input, predicate, ..+ } => {let input = self.create_physical_plan(input, ctx_state.clone())?;let input_schema = input.as_ref().schema().clone();- let runtime_expr =- self.create_physical_expr(expr, &input_schema, ctx_state.clone())?;- Ok(Arc::new(SelectionExec::try_new(runtime_expr, input)?))+ let runtime_expr = self.create_physical_expr(+ predicate,+ &input_schema,+ ctx_state.clone(),+ )?;+ Ok(Arc::new(FilterExec::try_new(runtime_expr, input)?))}LogicalPlan::Sort { expr, input, .. } => {let input = self.create_physical_plan(input, ctx_state.clone())?;diff --git a/rust/datafusion/src/lib.rs b/rust/datafusion/src/lib.rsindex b276cf4c81..ea88e335c6 100644--- a/rust/datafusion/src/lib.rs+++ b/rust/datafusion/src/lib.rs@@ -24,7 +24,7 @@//! and also provides a query optimizer and execution engine capable of parallel execution//! against partitioned data sources (CSV and Parquet) using threads.//!-//! DataFusion currently supports simple projection, selection, and aggregate queries.+//! DataFusion currently supports simple projection, filter, and aggregate queries.//!/// [ExecutionContext](../execution/context/struct.ExecutionContext.html) is the main interface/// for executing queries with DataFusion.diff --git a/rust/datafusion/src/logicalplan.rs b/rust/datafusion/src/logicalplan.rsindex 9aaa135e1b..a2e1979036 100644--- a/rust/datafusion/src/logicalplan.rs+++ b/rust/datafusion/src/logicalplan.rs@@ -740,7 +740,7 @@ impl fmt::Debug for Expr {}/// The LogicalPlan represents different types of relations (such as Projection,-/// Selection, etc) and can be created by the SQL query planner and the DataFrame API.+/// Filter, etc) and can be created by the SQL query planner and the DataFrame API.#[derive(Clone)]pub enum LogicalPlan {/// Evaluates an arbitrary list of expressions (essentially a@@ -757,13 +757,13 @@ pub enum LogicalPlan {/// expression (essentially a WHERE clause with a predicate/// expression).///- /// Semantically, `<expr>` is evaluated for each row of the input;- /// If the value of `<expr>` is true, the input row is passed to- /// the output. If the value of `<expr>` is false, the row is+ /// Semantically, `<predicate>` is evaluated for each row of the input;+ /// If the value of `<predicate>` is true, the input row is passed to+ /// the output. If the value of `<predicate>` is false, the row is/// discarded.- Selection {- /// The expression. Must have Boolean type.- expr: Expr,+ Filter {+ /// The predicate expression, which must have Boolean type.+ predicate: Expr,/// The incoming logical planinput: Box<LogicalPlan>,},@@ -894,7 +894,7 @@ impl LogicalPlan {projected_schema, ..} => &projected_schema,LogicalPlan::Projection { schema, .. } => &schema,- LogicalPlan::Selection { input, .. } => input.schema(),+ LogicalPlan::Filter { input, .. } => input.schema(),LogicalPlan::Aggregate { schema, .. } => &schema,LogicalPlan::Sort { input, .. } => input.schema(),LogicalPlan::Limit { input, .. } => input.schema(),@@ -954,12 +954,12 @@ impl LogicalPlan {}input.fmt_with_indent(f, indent + 1)}- LogicalPlan::Selection {- ref expr,+ LogicalPlan::Filter {+ predicate: ref expr,ref input,..} => {- write!(f, "Selection: {:?}", expr)?;+ write!(f, "Filter: {:?}", expr)?;input.fmt_with_indent(f, indent + 1)}LogicalPlan::Aggregate {@@ -1186,8 +1186,8 @@ impl LogicalPlanBuilder {/// Apply a filterpub fn filter(&self, expr: Expr) -> Result<Self> {- Ok(Self::from(&LogicalPlan::Selection {- expr,+ Ok(Self::from(&LogicalPlan::Filter {+ predicate: expr,input: Box::new(self.plan.clone()),}))}@@ -1298,7 +1298,7 @@ mod tests {.build()?;let expected = "Projection: #id\- \n Selection: #state Eq Utf8(\"CO\")\+ \n Filter: #state Eq Utf8(\"CO\")\\n TableScan: employee.csv projection=Some([0, 3])";assert_eq!(expected, format!("{:?}", plan));@@ -1318,7 +1318,7 @@ mod tests {.build()?;let expected = "Projection: #id\- \n Selection: #state Eq Utf8(\"CO\")\+ \n Filter: #state Eq Utf8(\"CO\")\\n CsvScan: employee.csv projection=Some([0, 3])";assert_eq!(expected, format!("{:?}", plan));diff --git a/rust/datafusion/src/optimizer/filter_push_down.rs b/rust/datafusion/src/optimizer/filter_push_down.rsindex 79c51262d0..9d522a6e14 100644--- a/rust/datafusion/src/optimizer/filter_push_down.rs+++ b/rust/datafusion/src/optimizer/filter_push_down.rs@@ -43,13 +43,13 @@ This optimizer commutes filters with filter-commutative operations to push the fto the maximum possible depth, consequently re-writing the filter expressions by everyprojection that changes the filter's expression.- Selection: #b Gt Int64(10)+ Filter: #b Gt Int64(10)Projection: #a AS bis optimized toProjection: #a AS b- Selection: #a Gt Int64(10) <--- changed from #b to #a+ Filter: #a Gt Int64(10) <--- changed from #b to #aTo perform such optimization, we first analyze the plan to identify three items:@@ -84,20 +84,20 @@ impl OptimizerRule for FilterPushDown {}let max_depth = *max_depth.unwrap(); // unwrap is safe by previous if- // construct optimized position of each of the new selections+ // construct optimized position of each of the new filters// E.g. when we have a filter (c1 + c2 > 2), c1's max depth is 10 and c2 is 11, we// can push the filter to depth 10- let mut new_selections: BTreeMap<usize, Expr> = BTreeMap::new();- for (selection_depth, expr) in result.selections {+ let mut new_filtersnew_filters: BTreeMap<usize, Expr> = BTreeMap::new();+ for (filter_depth, expr) in result.filters {// get all columns on the filter expression- let mut selection_columns: HashSet<String> = HashSet::new();- utils::expr_to_column_names(&expr, &mut selection_columns)?;+ let mut filter_columns: HashSet<String> = HashSet::new();+ utils::expr_to_column_names(&expr, &mut filter_columns)?;- // identify the depths that are filter-commutable with this selection- let mut new_depth = selection_depth;- for depth in selection_depth..max_depth {+ // identify the depths that are filter-commutable with this filter+ let mut new_depth = filter_depth;+ for depth in filter_depth..max_depth {if let Some(break_columns) = break_points.get(&depth) {- if selection_columns+ if filter_columns.intersection(break_columns).peekable().peek()@@ -113,23 +113,23 @@ impl OptimizerRule for FilterPushDown {}}- // re-write the new selections based on all projections that it crossed.- // E.g. in `Selection: #b\n Projection: #a > 1 as b`, we can swap them, but the selection must be "#a > 1"+ // re-write the new filters based on all projections that it crossed.+ // E.g. in `Filter: #b\n Projection: #a > 1 as b`, we can swap them, but the filter must be "#a > 1"let mut new_expression = expr.clone();- for depth_i in selection_depth..new_depth {+ for depth_i in filter_depth..new_depth {if let Some(projection) = result.projections.get(&depth_i) {new_expression = rewrite(&new_expression, projection)?;}}// AND filter expressions that would be placed on the same depth- if let Some(existing_expression) = new_selections.get(&new_depth) {+ if let Some(existing_expression) = new_filtersnew_filters.get(&new_depth) {new_expression = and(existing_expression, &new_expression)}- new_selections.insert(new_depth, new_expression);+ new_filtersnew_filters.insert(new_depth, new_expression);}- optimize_plan(plan, &new_selections, 0)+ optimize_plan(plan, &new_filtersnew_filters, 0)}}@@ -141,7 +141,7 @@ struct AnalysisResult {/// depths not in here indicate that the node is commutativepub break_points: BTreeMap<usize, HashSet<String>>,/// maps the depths of filter nodes to expressions- pub selections: BTreeMap<usize, Expr>,+ pub filters: BTreeMap<usize, Expr>,/// maps the depths of projection nodes to their expressionspub projections: BTreeMap<usize, HashMap<String, Expr>>,}@@ -149,9 +149,9 @@ struct AnalysisResult {/// Recursively transverses the logical plan looking for depths that break filter pushdownfn analyze_plan(plan: &LogicalPlan, depth: usize) -> Result<AnalysisResult> {match plan {- LogicalPlan::Selection { input, expr } => {+ LogicalPlan::Filter { input, predicate } => {let mut result = analyze_plan(&input, depth + 1)?;- result.selections.insert(depth, expr.clone());+ result.filters.insert(depth, predicate.clone());Ok(result)}LogicalPlan::Projection {@@ -164,7 +164,7 @@ fn analyze_plan(plan: &LogicalPlan, depth: usize) -> Result<AnalysisResult> {// collect projection.let mut projection = HashMap::new();schema.fields().iter().enumerate().for_each(|(i, field)| {- // strip alias, as they should not be part of selections+ // strip alias, as they should not be part of filterslet expr = match &expr[i] {Expr::Alias(expr, _) => expr.as_ref().clone(),expr => expr.clone(),@@ -224,7 +224,7 @@ fn analyze_plan(plan: &LogicalPlan, depth: usize) -> Result<AnalysisResult> {break_points.insert(depth, columns);Ok(AnalysisResult {break_points,- selections: BTreeMap::new(),+ filters: BTreeMap::new(),projections: BTreeMap::new(),})}@@ -241,14 +241,14 @@ impl FilterPushDown {/// Returns a re-written logical plan where all old filters are removed and the new ones are added.fn optimize_plan(plan: &LogicalPlan,- new_selections: &BTreeMap<usize, Expr>,+ new_filters: &BTreeMap<usize, Expr>,depth: usize,) -> Result<LogicalPlan> {// optimize the plan recursively:let new_plan = match plan {- LogicalPlan::Selection { input, .. } => {- // ignore old selections- Ok(optimize_plan(&input, new_selections, depth + 1)?)+ LogicalPlan::Filter { input, .. } => {+ // ignore old filters+ Ok(optimize_plan(&input, new_filters, depth + 1)?)}_ => {// all other nodes are copied, optimizing recursively.@@ -257,17 +257,17 @@ fn optimize_plan(let inputs = utils::inputs(plan);let new_inputs = inputs.iter()- .map(|plan| optimize_plan(plan, new_selections, depth + 1))+ .map(|plan| optimize_plan(plan, new_filters, depth + 1)).collect::<Result<Vec<_>>>()?;utils::from_plan(plan, &expr, &new_inputs)}}?;- // if a new selection is to be applied, apply it- if let Some(expr) = new_selections.get(&depth) {- return Ok(LogicalPlan::Selection {- expr: expr.clone(),+ // if a new filter is to be applied, apply it+ if let Some(expr) = new_filters.get(&depth) {+ return Ok(LogicalPlan::Filter {+ predicate: expr.clone(),input: Box::new(new_plan),});} else {@@ -317,10 +317,10 @@ mod tests {.project(vec![col("a"), col("b")])?.filter(col("a").eq(lit(1i64)))?.build()?;- // selection is before projection+ // filter is before projectionlet expected = "\Projection: #a, #b\- \n Selection: #a Eq Int64(1)\+ \n Filter: #a Eq Int64(1)\\n TableScan: test projection=None";assert_optimized_plan_eq(&plan, expected);Ok(())@@ -334,9 +334,9 @@ mod tests {.limit(10)?.filter(col("a").eq(lit(1i64)))?.build()?;- // selection is before single projection+ // filter is before single projectionlet expected = "\- Selection: #a Eq Int64(1)\+ Filter: #a Eq Int64(1)\\n Limit: 10\\n Projection: #a, #b\\n TableScan: test projection=None";@@ -352,11 +352,11 @@ mod tests {.project(vec![col("c"), col("b")])?.filter(col("a").eq(lit(1i64)))?.build()?;- // selection is before double projection+ // filter is before double projectionlet expected = "\Projection: #c, #b\\n Projection: #a, #b, #c\- \n Selection: #a Eq Int64(1)\+ \n Filter: #a Eq Int64(1)\\n TableScan: test projection=None";assert_optimized_plan_eq(&plan, expected);Ok(())@@ -372,10 +372,10 @@ mod tests {)?.filter(col("a").gt(lit(10i64)))?.build()?;- // selection of key aggregation is commutative+ // filter of key aggregation is commutativelet expected = "\Aggregate: groupBy=[[#a]], aggr=[[SUM(#b) AS total_salary]]\- \n Selection: #a Gt Int64(10)\+ \n Filter: #a Gt Int64(10)\\n TableScan: test projection=None";assert_optimized_plan_eq(&plan, expected);Ok(())@@ -391,9 +391,9 @@ mod tests {)?.filter(col("b").gt(lit(10i64)))?.build()?;- // selection of aggregate is after aggregation since they are non-commutative+ // filter of aggregate is after aggregation since they are non-commutativelet expected = "\- Selection: #b Gt Int64(10)\+ Filter: #b Gt Int64(10)\\n Aggregate: groupBy=[[#a]], aggr=[[SUM(#b) AS b]]\\n TableScan: test projection=None";assert_optimized_plan_eq(&plan, expected);@@ -408,10 +408,10 @@ mod tests {.project(vec![col("a").alias("b"), col("c")])?.filter(col("b").eq(lit(1i64)))?.build()?;- // selection is before projection+ // filter is before projectionlet expected = "\Projection: #a AS b, #c\- \n Selection: #a Eq Int64(1)\+ \n Filter: #a Eq Int64(1)\\n TableScan: test projection=None";assert_optimized_plan_eq(&plan, expected);Ok(())@@ -449,15 +449,15 @@ mod tests {assert_eq!(format!("{:?}", plan),"\- Selection: #b Eq Int64(1)\+ Filter: #b Eq Int64(1)\\n Projection: #a Multiply Int32(2) Plus #c AS b, #c\\n TableScan: test projection=None");- // selection is before projection+ // filter is before projectionlet expected = "\Projection: #a Multiply Int32(2) Plus #c AS b, #c\- \n Selection: #a Multiply Int32(2) Plus #c Eq Int64(1)\+ \n Filter: #a Multiply Int32(2) Plus #c Eq Int64(1)\\n TableScan: test projection=None";assert_optimized_plan_eq(&plan, expected);Ok(())@@ -481,17 +481,17 @@ mod tests {assert_eq!(format!("{:?}", plan),"\- Selection: #a Eq Int64(1)\+ Filter: #a Eq Int64(1)\\n Projection: #b Multiply Int32(3) AS a, #c\\n Projection: #a Multiply Int32(2) Plus #c AS b, #c\\n TableScan: test projection=None");- // selection is before the projections+ // filter is before the projectionslet expected = "\Projection: #b Multiply Int32(3) AS a, #c\\n Projection: #a Multiply Int32(2) Plus #c AS b, #c\- \n Selection: #a Multiply Int32(2) Plus #c Multiply Int32(3) Eq Int64(1)\+ \n Filter: #a Multiply Int32(2) Plus #c Multiply Int32(3) Eq Int64(1)\\n TableScan: test projection=None";assert_optimized_plan_eq(&plan, expected);Ok(())@@ -514,19 +514,19 @@ mod tests {assert_eq!(format!("{:?}", plan),"\- Selection: #SUM(c) Gt Int64(10)\- \n Selection: #b Gt Int64(10)\+ Filter: #SUM(c) Gt Int64(10)\+ \n Filter: #b Gt Int64(10)\\n Aggregate: groupBy=[[#b]], aggr=[[SUM(#c)]]\\n Projection: #a AS b, #c\\n TableScan: test projection=None");- // selection is before the projections+ // filter is before the projectionslet expected = "\- Selection: #SUM(c) Gt Int64(10)\+ Filter: #SUM(c) Gt Int64(10)\\n Aggregate: groupBy=[[#b]], aggr=[[SUM(#c)]]\\n Projection: #a AS b, #c\- \n Selection: #a Gt Int64(10)\+ \n Filter: #a Gt Int64(10)\\n TableScan: test projection=None";assert_optimized_plan_eq(&plan, expected);@@ -544,10 +544,10 @@ mod tests {.project(vec![col("a"), col("b")])?.filter(col("a").eq(lit(1i64)))?.build()?;- // selection does not just any of the limits+ // filter does not just any of the limitslet expected = "\Projection: #a, #b\- \n Selection: #a Eq Int64(1)\+ \n Filter: #a Eq Int64(1)\\n Limit: 10\\n Limit: 20\\n Projection: #a, #b\@@ -572,20 +572,20 @@ mod tests {// not part of the testassert_eq!(format!("{:?}", plan),- "Selection: #a GtEq Int64(1)\+ "Filter: #a GtEq Int64(1)\\n Projection: #a\\n Limit: 1\- \n Selection: #a LtEq Int64(1)\+ \n Filter: #a LtEq Int64(1)\\n Projection: #a\\n TableScan: test projection=None");let expected = "\Projection: #a\- \n Selection: #a GtEq Int64(1)\+ \n Filter: #a GtEq Int64(1)\\n Limit: 1\\n Projection: #a\- \n Selection: #a LtEq Int64(1)\+ \n Filter: #a LtEq Int64(1)\\n TableScan: test projection=None";assert_optimized_plan_eq(&plan, expected);@@ -607,15 +607,15 @@ mod tests {assert_eq!(format!("{:?}", plan),"Projection: #a\- \n Selection: #a GtEq Int64(1)\- \n Selection: #a LtEq Int64(1)\+ \n Filter: #a GtEq Int64(1)\+ \n Filter: #a LtEq Int64(1)\\n Limit: 1\\n TableScan: test projection=None");let expected = "\Projection: #a\- \n Selection: #a GtEq Int64(1) And #a LtEq Int64(1)\+ \n Filter: #a GtEq Int64(1) And #a LtEq Int64(1)\\n Limit: 1\\n TableScan: test projection=None";diff --git a/rust/datafusion/src/optimizer/projection_push_down.rs b/rust/datafusion/src/optimizer/projection_push_down.rsindex 5550427d02..956b5330e1 100644--- a/rust/datafusion/src/optimizer/projection_push_down.rs+++ b/rust/datafusion/src/optimizer/projection_push_down.rs@@ -255,7 +255,7 @@ mod tests {}#[test]- fn aggregate_no_group_by_with_selection() -> Result<()> {+ fn aggregate_no_group_by_with_filter() -> Result<()> {let table_scan = test_table_scan()?;let plan = LogicalPlanBuilder::from(&table_scan)@@ -264,7 +264,7 @@ mod tests {.build()?;let expected = "Aggregate: groupBy=[[]], aggr=[[MAX(#b)]]\- \n Selection: #c\+ \n Filter: #c\\n TableScan: test projection=Some([1, 2])";assert_optimized_plan_eq(&plan, expected);diff --git a/rust/datafusion/src/optimizer/type_coercion.rs b/rust/datafusion/src/optimizer/type_coercion.rsindex 517f228741..df4818c5b2 100644--- a/rust/datafusion/src/optimizer/type_coercion.rs+++ b/rust/datafusion/src/optimizer/type_coercion.rs@@ -182,7 +182,7 @@ mod tests {Sort: #c1Aggregate: groupBy=[[#c1]], aggr=[[SUM(#c2)]]Projection: #c1, #c2- Selection: #c7 Lt CAST(UInt8(5) AS Int64)";+ Filter: #c7 Lt CAST(UInt8(5) AS Int64)";assert!(plan_str.starts_with(expected_plan_str));Ok(())@@ -202,9 +202,7 @@ mod tests {let mut rule = TypeCoercionRule::new(Arc::new(Mutex::new(scalar_functions)));let plan = rule.optimize(&plan)?;- assert!(- format!("{:?}", plan).starts_with("Selection: CAST(#c7 AS Float64) Lt #c12")- );+ assert!(format!("{:?}", plan).starts_with("Filter: CAST(#c7 AS Float64) Lt #c12"));Ok(())}diff --git a/rust/datafusion/src/optimizer/utils.rs b/rust/datafusion/src/optimizer/utils.rsindex 1916302d85..695bb0ea4f 100644--- a/rust/datafusion/src/optimizer/utils.rs+++ b/rust/datafusion/src/optimizer/utils.rs@@ -217,7 +217,7 @@ pub fn optimize_explain(pub fn expressions(plan: &LogicalPlan) -> Vec<Expr> {match plan {LogicalPlan::Projection { expr, .. } => expr.clone(),- LogicalPlan::Selection { expr, .. } => vec![expr.clone()],+ LogicalPlan::Filter { predicate, .. } => vec![predicate.clone()],LogicalPlan::Aggregate {group_expr,aggr_expr,@@ -244,7 +244,7 @@ pub fn expressions(plan: &LogicalPlan) -> Vec<Expr> {pub fn inputs(plan: &LogicalPlan) -> Vec<&LogicalPlan> {match plan {LogicalPlan::Projection { input, .. } => vec![input],- LogicalPlan::Selection { input, .. } => vec![input],+ LogicalPlan::Filter { input, .. } => vec![input],LogicalPlan::Aggregate { input, .. } => vec![input],LogicalPlan::Sort { input, .. } => vec![input],LogicalPlan::Limit { input, .. } => vec![input],@@ -271,8 +271,8 @@ pub fn from_plan(input: Box::new(inputs[0].clone()),schema: schema.clone(),}),- LogicalPlan::Selection { .. } => Ok(LogicalPlan::Selection {- expr: expr[0].clone(),+ LogicalPlan::Filter { .. } => Ok(LogicalPlan::Filter {+ predicate: expr[0].clone(),input: Box::new(inputs[0].clone()),}),LogicalPlan::Aggregate {diff --git a/rust/datafusion/src/sql/planner.rs b/rust/datafusion/src/sql/planner.rsindex 34f6f8ecd3..c66d238621 100644--- a/rust/datafusion/src/sql/planner.rs+++ b/rust/datafusion/src/sql/planner.rs@@ -239,7 +239,7 @@ impl<S: SchemaProvider> SqlToRel<S> {let plan = self.from_join_to_plan(&select.from)?;- // selection first+ // filter (also known as selection) firstlet plan = self.filter(&plan, &select.selection)?;let projection_expr: Vec<Expr> = select@@ -267,11 +267,11 @@ impl<S: SchemaProvider> SqlToRel<S> {fn filter(&self,plan: &LogicalPlan,- selection: &Option<SQLExpr>,+ predicate: &Option<SQLExpr>,) -> Result<LogicalPlan> {- match *selection {- Some(ref filter_expr) => LogicalPlanBuilder::from(&plan)- .filter(self.sql_to_rex(filter_expr, &plan.schema())?)?+ match *predicate {+ Some(ref predicate_expr) => LogicalPlanBuilder::from(&plan)+ .filter(self.sql_to_rex(predicate_expr, &plan.schema())?)?.build(),_ => Ok(plan.clone()),}@@ -598,41 +598,41 @@ mod tests {}#[test]- fn select_simple_selection() {+ fn select_simple_filter() {let sql = "SELECT id, first_name, last_name \FROM person WHERE state = 'CO'";let expected = "Projection: #id, #first_name, #last_name\- \n Selection: #state Eq Utf8(\"CO\")\+ \n Filter: #state Eq Utf8(\"CO\")\\n TableScan: person projection=None";quick_test(sql, expected);}#[test]- fn select_neg_selection() {+ fn select_neg_filter() {let sql = "SELECT id, first_name, last_name \FROM person WHERE NOT state";let expected = "Projection: #id, #first_name, #last_name\- \n Selection: NOT #state\+ \n Filter: NOT #state\\n TableScan: person projection=None";quick_test(sql, expected);}#[test]- fn select_compound_selection() {+ fn select_compound_filter() {let sql = "SELECT id, first_name, last_name \FROM person WHERE state = 'CO' AND age >= 21 AND age <= 65";let expected = "Projection: #id, #first_name, #last_name\- \n Selection: #state Eq Utf8(\"CO\") And #age GtEq Int64(21) And #age LtEq Int64(65)\+ \n Filter: #state Eq Utf8(\"CO\") And #age GtEq Int64(21) And #age LtEq Int64(65)\\n TableScan: person projection=None";quick_test(sql, expected);}#[test]- fn test_timestamp_selection() {+ fn test_timestamp_filter() {let sql = "SELECT state FROM person WHERE birth_date < CAST (158412331400600000 as timestamp)";let expected = "Projection: #state\- \n Selection: #birth_date Lt CAST(Int64(158412331400600000) AS Timestamp(Nanosecond, None))\+ \n Filter: #birth_date Lt CAST(Int64(158412331400600000) AS Timestamp(Nanosecond, None))\\n TableScan: person projection=None";quick_test(sql, expected);@@ -649,7 +649,7 @@ mod tests {AND age < 65 \AND age <= 65";let expected = "Projection: #age, #first_name, #last_name\- \n Selection: #age Eq Int64(21) \+ \n Filter: #age Eq Int64(21) \And #age NotEq Int64(21) \And #age Gt Int64(21) \And #age GtEq Int64(21) \diff --git a/rust/datafusion/tests/sql.rs b/rust/datafusion/tests/sql.rsindex d2d5349d5e..2f5bc9df52 100644--- a/rust/datafusion/tests/sql.rs+++ b/rust/datafusion/tests/sql.rs@@ -436,7 +436,7 @@ fn csv_explain() {register_aggregate_csv_by_sql(&mut ctx);let sql = "EXPLAIN SELECT c1 FROM aggregate_test_100 where c2 > 10";let actual = execute(&mut ctx, sql).join("\n");- let expected = "\"logical_plan\"\t\"Projection: #c1\\n Selection: #c2 Gt Int64(10)\\n TableScan: aggregate_test_100 projection=None\"".to_string();+ let expected = "\"logical_plan\"\t\"Projection: #c1\\n Filter: #c2 Gt Int64(10)\\n TableScan: aggregate_test_100 projection=None\"".to_string();assert_eq!(expected, actual);// Also, expect same result with lowercase explain