Apache DataFusion SQL Query Engine
ARROW-9828: [Rust] [DataFusion] Support filter pushdown optimisation for TableProvider implementations
Ruan Pearce-Authers4177dc6b29ff
diff --git a/rust/datafusion/src/datasource/csv.rs b/rust/datafusion/src/datasource/csv.rsindex 8fc27bd1cc..5dfb9ea9f0 100644--- a/rust/datafusion/src/datasource/csv.rs+++ b/rust/datafusion/src/datasource/csv.rs@@ -41,6 +41,7 @@ use std::sync::Arc;use crate::datasource::datasource::Statistics;use crate::datasource::TableProvider;use crate::error::{DataFusionError, Result};+use crate::logical_plan::Expr;use crate::physical_plan::csv::CsvExec;pub use crate::physical_plan::csv::CsvReadOptions;use crate::physical_plan::{common, ExecutionPlan};@@ -95,6 +96,7 @@ impl TableProvider for CsvFile {&self,projection: &Option<Vec<usize>>,batch_size: usize,+ _filters: &[Expr],) -> Result<Arc<dyn ExecutionPlan>> {Ok(Arc::new(CsvExec::try_new(&self.path,diff --git a/rust/datafusion/src/datasource/datasource.rs b/rust/datafusion/src/datasource/datasource.rsindex af77346c38..93877f96ba 100644--- a/rust/datafusion/src/datasource/datasource.rs+++ b/rust/datafusion/src/datasource/datasource.rs@@ -22,6 +22,7 @@ use std::sync::Arc;use crate::arrow::datatypes::SchemaRef;use crate::error::Result;+use crate::logical_plan::Expr;use crate::physical_plan::ExecutionPlan;/// This table statistics are estimates.@@ -34,6 +35,23 @@ pub struct Statistics {pub total_byte_size: Option<usize>,}+/// Indicates whether and how a filter expression can be handled by a+/// TableProvider for table scans.+#[derive(Debug, Clone)]+pub enum TableProviderFilterPushDown {+ /// The expression cannot be used by the provider.+ Unsupported,+ /// The expression can be used to help minimise the data retrieved,+ /// but the provider cannot guarantee that all returned tuples+ /// satisfy the filter. The Filter plan node containing this expression+ /// will be preserved.+ Inexact,+ /// The provider guarantees that all returned data satisfies this+ /// filter expression. The Filter plan node containing this expression+ /// will be removed.+ Exact,+}+/// Source tablepub trait TableProvider {/// Returns the table provider as [`Any`](std::any::Any) so that it can be@@ -48,9 +66,19 @@ pub trait TableProvider {&self,projection: &Option<Vec<usize>>,batch_size: usize,+ filters: &[Expr],) -> Result<Arc<dyn ExecutionPlan>>;/// Returns the table Statistics/// Statistics should be optional because not all data sources can provide statistics.fn statistics(&self) -> Statistics;++ /// Tests whether the table provider can make use of a filter expression+ /// to optimise data retrieval.+ fn supports_filter_pushdown(+ &self,+ _filter: &Expr,+ ) -> Result<TableProviderFilterPushDown> {+ Ok(TableProviderFilterPushDown::Unsupported)+ }}diff --git a/rust/datafusion/src/datasource/empty.rs b/rust/datafusion/src/datasource/empty.rsindex d8467d931b..52529c409e 100644--- a/rust/datafusion/src/datasource/empty.rs+++ b/rust/datafusion/src/datasource/empty.rs@@ -25,6 +25,7 @@ use arrow::datatypes::*;use crate::datasource::datasource::Statistics;use crate::datasource::TableProvider;use crate::error::Result;+use crate::logical_plan::Expr;use crate::physical_plan::{empty::EmptyExec, ExecutionPlan};/// A table with a schema but no data.@@ -52,6 +53,7 @@ impl TableProvider for EmptyTable {&self,projection: &Option<Vec<usize>>,_batch_size: usize,+ _filters: &[Expr],) -> Result<Arc<dyn ExecutionPlan>> {// even though there is no data, projections applylet projection = match projection.clone() {diff --git a/rust/datafusion/src/datasource/memory.rs b/rust/datafusion/src/datasource/memory.rsindex e34e2d13e0..fe230abcb3 100644--- a/rust/datafusion/src/datasource/memory.rs+++ b/rust/datafusion/src/datasource/memory.rs@@ -28,6 +28,7 @@ use arrow::record_batch::RecordBatch;use crate::datasource::datasource::Statistics;use crate::datasource::TableProvider;use crate::error::{DataFusionError, Result};+use crate::logical_plan::Expr;use crate::physical_plan::common;use crate::physical_plan::memory::MemoryExec;use crate::physical_plan::ExecutionPlan;@@ -69,7 +70,7 @@ impl MemTable {/// Create a mem table by reading from another data sourcepub async fn load(t: &dyn TableProvider, batch_size: usize) -> Result<Self> {let schema = t.schema();- let exec = t.scan(&None, batch_size)?;+ let exec = t.scan(&None, batch_size, &[])?;let partition_count = exec.output_partitioning().partition_count();let tasks = (0..partition_count)@@ -108,6 +109,7 @@ impl TableProvider for MemTable {&self,projection: &Option<Vec<usize>>,_batch_size: usize,+ _filters: &[Expr],) -> Result<Arc<dyn ExecutionPlan>> {let columns: Vec<usize> = match projection {Some(p) => p.clone(),@@ -177,7 +179,7 @@ mod tests {assert_eq!(provider.statistics().num_rows, Some(3));// scan with projection- let exec = provider.scan(&Some(vec![2, 1]), 1024)?;+ let exec = provider.scan(&Some(vec![2, 1]), 1024, &[])?;let mut it = exec.execute(0).await?;let batch2 = it.next().await.unwrap()?;assert_eq!(2, batch2.schema().fields().len());@@ -207,7 +209,7 @@ mod tests {let provider = MemTable::try_new(schema, vec![vec![batch]])?;- let exec = provider.scan(&None, 1024)?;+ let exec = provider.scan(&None, 1024, &[])?;let mut it = exec.execute(0).await?;let batch1 = it.next().await.unwrap()?;assert_eq!(3, batch1.schema().fields().len());@@ -237,7 +239,7 @@ mod tests {let projection: Vec<usize> = vec![0, 4];- match provider.scan(&Some(projection), 1024) {+ match provider.scan(&Some(projection), 1024, &[]) {Err(DataFusionError::Internal(e)) => {assert_eq!("\"Projection index out of range\"", format!("{:?}", e))}diff --git a/rust/datafusion/src/datasource/parquet.rs b/rust/datafusion/src/datasource/parquet.rsindex c067b24f1e..3666042540 100644--- a/rust/datafusion/src/datasource/parquet.rs+++ b/rust/datafusion/src/datasource/parquet.rs@@ -27,6 +27,7 @@ use parquet::file::metadata::RowGroupMetaData;use crate::datasource::datasource::Statistics;use crate::datasource::TableProvider;use crate::error::Result;+use crate::logical_plan::Expr;use crate::physical_plan::parquet::ParquetExec;use crate::physical_plan::ExecutionPlan;@@ -82,6 +83,7 @@ impl TableProvider for ParquetTable {&self,projection: &Option<Vec<usize>>,batch_size: usize,+ _filters: &[Expr],) -> Result<Arc<dyn ExecutionPlan>> {Ok(Arc::new(ParquetExec::try_new(&self.path,@@ -110,7 +112,7 @@ mod tests {async fn read_small_batches() -> Result<()> {let table = load_table("alltypes_plain.parquet")?;let projection = None;- let exec = table.scan(&projection, 2)?;+ let exec = table.scan(&projection, 2, &[])?;let stream = exec.execute(0).await?;let count = stream@@ -335,7 +337,7 @@ mod tests {table: Box<dyn TableProvider>,projection: &Option<Vec<usize>>,) -> Result<RecordBatch> {- let exec = table.scan(projection, 1024)?;+ let exec = table.scan(projection, 1024, &[])?;let mut it = exec.execute(0).await?;it.next().awaitdiff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rsindex f06d6e5ea0..7be35a7951 100644--- a/rust/datafusion/src/execution/context.rs+++ b/rust/datafusion/src/execution/context.rs@@ -232,6 +232,7 @@ impl ExecutionContext {source: provider,projected_schema: schema.to_dfschema_ref()?,projection: None,+ filters: vec![],};Ok(Arc::new(DataFrameImpl::new(self.state.clone(),@@ -285,6 +286,7 @@ impl ExecutionContext {source: Arc::clone(provider),projected_schema: schema.to_dfschema_ref()?,projection: None,+ filters: vec![],};Ok(Arc::new(DataFrameImpl::new(self.state.clone(),diff --git a/rust/datafusion/src/logical_plan/builder.rs b/rust/datafusion/src/logical_plan/builder.rsindex 75a6798df1..3a98f67632 100644--- a/rust/datafusion/src/logical_plan/builder.rs+++ b/rust/datafusion/src/logical_plan/builder.rs@@ -115,6 +115,7 @@ impl LogicalPlanBuilder {source: provider,projected_schema,projection,+ filters: vec![],};Ok(Self::from(&table_scan))diff --git a/rust/datafusion/src/logical_plan/plan.rs b/rust/datafusion/src/logical_plan/plan.rsindex bdc8c8541e..9caabac0cf 100644--- a/rust/datafusion/src/logical_plan/plan.rs+++ b/rust/datafusion/src/logical_plan/plan.rs@@ -120,6 +120,8 @@ pub enum LogicalPlan {projection: Option<Vec<usize>>,/// The schema description of the outputprojected_schema: DFSchemaRef,+ /// Optional expressions to be used as filters by the table provider+ filters: Vec<Expr>,},/// Produces no rows: An empty relation with an empty schemaEmptyRelation {@@ -467,6 +469,7 @@ impl LogicalPlan {LogicalPlan::TableScan {ref table_name,ref projection,+ ref filters,..} => {let sep = " ".repeat(min(1, table_name.len()));@@ -474,7 +477,13 @@ impl LogicalPlan {f,"TableScan: {}{}projection={:?}",table_name, sep, projection- )+ )?;++ if !filters.is_empty() {+ write!(f, ", filters={:?}", filters)?;+ }++ Ok(())}LogicalPlan::Projection { ref expr, .. } => {write!(f, "Projection: ")?;diff --git a/rust/datafusion/src/optimizer/filter_push_down.rs b/rust/datafusion/src/optimizer/filter_push_down.rsindex c128b249d3..421bffa978 100644--- a/rust/datafusion/src/optimizer/filter_push_down.rs+++ b/rust/datafusion/src/optimizer/filter_push_down.rs@@ -14,6 +14,7 @@//! Filter Push Down optimizer rule ensures that filters are applied as early as possible in the plan+use crate::datasource::datasource::TableProviderFilterPushDown;use crate::logical_plan::{and, LogicalPlan};use crate::logical_plan::{DFSchema, Expr};use crate::optimizer::optimizer::OptimizerRule;@@ -338,6 +339,45 @@ fn optimize(plan: &LogicalPlan, mut state: State) -> Result<LogicalPlan> {Ok(plan)}}+ LogicalPlan::TableScan {+ source,+ projected_schema,+ filters,+ projection,+ table_name,+ } => {+ let mut used_columns = HashSet::new();+ let mut new_filters = filters.clone();++ for (filter_expr, cols) in &state.filters {+ let (preserve_filter_node, add_to_provider) =+ match source.supports_filter_pushdown(filter_expr)? {+ TableProviderFilterPushDown::Unsupported => (true, false),+ TableProviderFilterPushDown::Inexact => (true, true),+ TableProviderFilterPushDown::Exact => (false, true),+ };++ if preserve_filter_node {+ used_columns.extend(cols.clone());+ }++ if add_to_provider {+ new_filters.push(filter_expr.clone());+ }+ }++ issue_filters(+ state,+ used_columns,+ &LogicalPlan::TableScan {+ source: source.clone(),+ projection: projection.clone(),+ projected_schema: projected_schema.clone(),+ table_name: table_name.clone(),+ filters: new_filters,+ },+ )+ }_ => {// all other plans are _not_ filter-commutablelet used_columns = plan@@ -389,9 +429,13 @@ fn rewrite(expr: &Expr, projection: &HashMap<String, Expr>) -> Result<Expr> {#[cfg(test)]mod tests {use super::*;- use crate::logical_plan::{lit, sum, Expr, LogicalPlanBuilder, Operator};+ use crate::datasource::datasource::Statistics;+ use crate::datasource::TableProvider;+ use crate::logical_plan::{lit, sum, DFSchema, Expr, LogicalPlanBuilder, Operator};+ use crate::physical_plan::ExecutionPlan;use crate::test::*;use crate::{logical_plan::col, prelude::JoinType};+ use arrow::datatypes::SchemaRef;fn assert_optimized_plan_eq(plan: &LogicalPlan, expected: &str) {let mut rule = FilterPushDown::new();@@ -871,7 +915,101 @@ mod tests {\n TableScan: test projection=None\\n Projection: #a, #c\\n TableScan: test projection=None";+ assert_optimized_plan_eq(&plan, expected);+ Ok(())+ }++ struct PushDownProvider {+ pub filter_support: TableProviderFilterPushDown,+ }+ impl TableProvider for PushDownProvider {+ fn schema(&self) -> SchemaRef {+ Arc::new(arrow::datatypes::Schema::new(vec![+ arrow::datatypes::Field::new(+ "a",+ arrow::datatypes::DataType::Int32,+ true,+ ),+ ]))+ }++ fn scan(+ &self,+ _: &Option<Vec<usize>>,+ _: usize,+ _: &[Expr],+ ) -> Result<Arc<dyn ExecutionPlan>> {+ unimplemented!()+ }++ fn supports_filter_pushdown(+ &self,+ _: &Expr,+ ) -> Result<TableProviderFilterPushDown> {+ Ok(self.filter_support.clone())+ }++ fn as_any(&self) -> &dyn std::any::Any {+ self+ }++ fn statistics(&self) -> Statistics {+ Statistics::default()+ }+ }++ fn table_scan_with_pushdown_provider(+ filter_support: TableProviderFilterPushDown,+ ) -> Result<LogicalPlan> {+ let test_provider = PushDownProvider { filter_support };++ let table_scan = LogicalPlan::TableScan {+ table_name: "".into(),+ filters: vec![],+ projected_schema: Arc::new(DFSchema::try_from_qualified(+ "",+ &*test_provider.schema(),+ )?),+ projection: None,+ source: Arc::new(test_provider),+ };++ LogicalPlanBuilder::from(&table_scan)+ .filter(col("a").eq(lit(1i64)))?+ .build()+ }++ #[test]+ fn filter_with_table_provider_exact() -> Result<()> {+ let plan = table_scan_with_pushdown_provider(TableProviderFilterPushDown::Exact)?;++ let expected = "\+ TableScan: projection=None, filters=[#a Eq Int64(1)]";+ assert_optimized_plan_eq(&plan, expected);+ Ok(())+ }++ #[test]+ fn filter_with_table_provider_inexact() -> Result<()> {+ let plan =+ table_scan_with_pushdown_provider(TableProviderFilterPushDown::Inexact)?;++ let expected = "\+ Filter: #a Eq Int64(1)\+ \n TableScan: projection=None, filters=[#a Eq Int64(1)]";+ assert_optimized_plan_eq(&plan, expected);+ Ok(())+ }++ #[test]+ fn filter_with_table_provider_unsupported() -> Result<()> {+ let plan =+ table_scan_with_pushdown_provider(TableProviderFilterPushDown::Unsupported)?;++ let expected = "\+ Filter: #a Eq Int64(1)\+ \n TableScan: projection=None";assert_optimized_plan_eq(&plan, expected);Ok(())}diff --git a/rust/datafusion/src/optimizer/projection_push_down.rs b/rust/datafusion/src/optimizer/projection_push_down.rsindex 0084d68d5c..7f1c358a91 100644--- a/rust/datafusion/src/optimizer/projection_push_down.rs+++ b/rust/datafusion/src/optimizer/projection_push_down.rs@@ -243,6 +243,7 @@ fn optimize_plan(table_name,source,projection,+ filters,..} => {let (projection, projected_schema) = get_projected_schema(@@ -258,6 +259,7 @@ fn optimize_plan(source: source.clone(),projection: Some(projection),projected_schema,+ filters: filters.clone(),})}LogicalPlan::Explain {diff --git a/rust/datafusion/src/physical_plan/planner.rs b/rust/datafusion/src/physical_plan/planner.rsindex a1fb5b1877..f02fc4e8de 100644--- a/rust/datafusion/src/physical_plan/planner.rs+++ b/rust/datafusion/src/physical_plan/planner.rs@@ -137,8 +137,11 @@ impl DefaultPhysicalPlanner {match logical_plan {LogicalPlan::TableScan {- source, projection, ..- } => source.scan(projection, batch_size),+ source,+ projection,+ filters,+ ..+ } => source.scan(projection, batch_size, filters),LogicalPlan::Aggregate {input,group_expr,diff --git a/rust/datafusion/tests/custom_sources.rs b/rust/datafusion/tests/custom_sources.rsindex fd041782fd..979bde4ef0 100644--- a/rust/datafusion/tests/custom_sources.rs+++ b/rust/datafusion/tests/custom_sources.rs@@ -27,7 +27,7 @@ use datafusion::{};use datafusion::execution::context::ExecutionContext;-use datafusion::logical_plan::{col, LogicalPlan, LogicalPlanBuilder};+use datafusion::logical_plan::{col, Expr, LogicalPlan, LogicalPlanBuilder};use datafusion::physical_plan::{ExecutionPlan, Partitioning, RecordBatchStream, SendableRecordBatchStream,};@@ -143,6 +143,7 @@ impl TableProvider for CustomTableProvider {&self,projection: &Option<Vec<usize>>,_batch_size: usize,+ _filters: &[Expr],) -> Result<Arc<dyn ExecutionPlan>> {Ok(Arc::new(CustomExecutionPlan {projection: projection.clone(),diff --git a/rust/datafusion/tests/provider_filter_pushdown.rs b/rust/datafusion/tests/provider_filter_pushdown.rsnew file mode 100644index 0000000000..b4f0bfb61b--- /dev/null+++ b/rust/datafusion/tests/provider_filter_pushdown.rs@@ -0,0 +1,176 @@+// 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.++use arrow::array::{as_primitive_array, Int32Builder, UInt64Array};+use arrow::datatypes::{DataType, Field, Schema, SchemaRef};+use arrow::record_batch::RecordBatch;+use async_trait::async_trait;+use datafusion::datasource::datasource::{+ Statistics, TableProvider, TableProviderFilterPushDown,+};+use datafusion::error::Result;+use datafusion::execution::context::ExecutionContext;+use datafusion::logical_plan::Expr;+use datafusion::physical_plan::common::SizedRecordBatchStream;+use datafusion::physical_plan::{ExecutionPlan, Partitioning, SendableRecordBatchStream};+use datafusion::prelude::*;+use datafusion::scalar::ScalarValue;+use std::sync::Arc;++fn create_batch(value: i32, num_rows: usize) -> Result<RecordBatch> {+ let mut builder = Int32Builder::new(num_rows);+ for _ in 0..num_rows {+ builder.append_value(value)?;+ }++ Ok(RecordBatch::try_new(+ Arc::new(Schema::new(vec![Field::new(+ "flag",+ DataType::Int32,+ false,+ )])),+ vec![Arc::new(builder.finish())],+ )?)+}++#[derive(Debug)]+struct CustomPlan {+ schema: SchemaRef,+ batches: Vec<Arc<RecordBatch>>,+}++#[async_trait]+impl ExecutionPlan for CustomPlan {+ fn as_any(&self) -> &dyn std::any::Any {+ self+ }++ fn schema(&self) -> SchemaRef {+ self.schema.clone()+ }++ fn output_partitioning(&self) -> Partitioning {+ Partitioning::UnknownPartitioning(1)+ }++ fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {+ vec![]+ }++ fn with_new_children(+ &self,+ _: Vec<Arc<dyn ExecutionPlan>>,+ ) -> Result<Arc<dyn ExecutionPlan>> {+ unreachable!()+ }++ async fn execute(&self, _: usize) -> Result<SendableRecordBatchStream> {+ Ok(Box::pin(SizedRecordBatchStream::new(+ self.schema(),+ self.batches.clone(),+ )))+ }+}++#[derive(Clone)]+struct CustomProvider {+ zero_batch: RecordBatch,+ one_batch: RecordBatch,+}++impl TableProvider for CustomProvider {+ fn as_any(&self) -> &dyn std::any::Any {+ self+ }++ fn schema(&self) -> SchemaRef {+ self.zero_batch.schema()+ }++ fn scan(+ &self,+ _: &Option<Vec<usize>>,+ _: usize,+ filters: &[Expr],+ ) -> Result<Arc<dyn ExecutionPlan>> {+ match &filters[0] {+ Expr::BinaryExpr { right, .. } => {+ let int_value = match &**right {+ Expr::Literal(ScalarValue::Int64(i)) => i.unwrap(),+ _ => unimplemented!(),+ };++ Ok(Arc::new(CustomPlan {+ schema: self.zero_batch.schema(),+ batches: match int_value {+ 0 => vec![Arc::new(self.zero_batch.clone())],+ 1 => vec![Arc::new(self.one_batch.clone())],+ _ => vec![],+ },+ }))+ }+ _ => Ok(Arc::new(CustomPlan {+ schema: self.zero_batch.schema(),+ batches: vec![],+ })),+ }+ }++ fn statistics(&self) -> Statistics {+ Statistics::default()+ }++ fn supports_filter_pushdown(&self, _: &Expr) -> Result<TableProviderFilterPushDown> {+ Ok(TableProviderFilterPushDown::Exact)+ }+}++async fn assert_provider_row_count(value: i64, expected_count: u64) -> Result<()> {+ let provider = CustomProvider {+ zero_batch: create_batch(0, 10)?,+ one_batch: create_batch(1, 5)?,+ };++ let mut ctx = ExecutionContext::new();+ let df = ctx+ .read_table(Arc::new(provider.clone()))?+ .filter(col("flag").eq(lit(value)))?+ .aggregate(vec![], vec![count(col("flag"))])?;++ let results = df.collect().await?;+ let result_col: &UInt64Array = as_primitive_array(results[0].column(0));+ assert_eq!(result_col.value(0), expected_count);++ ctx.register_table("data", Box::new(provider));+ let sql_results = ctx+ .sql(&format!("select count(*) from data where flag = {}", value))?+ .collect()+ .await?;++ let sql_result_col: &UInt64Array = as_primitive_array(sql_results[0].column(0));+ assert_eq!(sql_result_col.value(0), expected_count);++ Ok(())+}++#[tokio::test]+async fn test_filter_pushdown_results() -> Result<()> {+ assert_provider_row_count(0, 10).await?;+ assert_provider_row_count(1, 5).await?;+ assert_provider_row_count(2, 0).await?;+ Ok(())+}