Skip to content

Apache DataFusion SQL Query Engine

ARROW-11927: [Rust][DataFusion] Support Limit push down optimization

Heres, Danielb5eb1e799747
diff --git a/rust/datafusion/src/datasource/csv.rs b/rust/datafusion/src/datasource/csv.rs
index bf8f781574..6f6c9abe07 100644
--- a/rust/datafusion/src/datasource/csv.rs
+++ b/rust/datafusion/src/datasource/csv.rs
@@ -121,6 +121,7 @@ impl TableProvider for CsvFile {
projection: &Option<Vec<usize>>,
batch_size: usize,
_filters: &[Expr],
+ limit: Option<usize>,
) -> Result<Arc<dyn ExecutionPlan>> {
Ok(Arc::new(CsvExec::try_new(
&self.path,
@@ -130,7 +131,10 @@ impl TableProvider for CsvFile {
.delimiter(self.delimiter)
.file_extension(self.file_extension.as_str()),
projection.clone(),
- batch_size,
+ limit
+ .map(|l| std::cmp::min(l, batch_size))
+ .unwrap_or(batch_size),
+ limit,
)?))
}
diff --git a/rust/datafusion/src/datasource/datasource.rs b/rust/datafusion/src/datasource/datasource.rs
index 7fe9f6af15..4e6ad36160 100644
--- a/rust/datafusion/src/datasource/datasource.rs
+++ b/rust/datafusion/src/datasource/datasource.rs
@@ -81,6 +81,11 @@ pub trait TableProvider {
projection: &Option<Vec<usize>>,
batch_size: usize,
filters: &[Expr],
+ // limit can be used to reduce the amount scanned
+ // from the datasource as a performance optimization.
+ // If set, it contains the amount of rows needed by the `LogicalPlan`,
+ // The datasource should return *at least* this number of rows if available.
+ limit: Option<usize>,
) -> Result<Arc<dyn ExecutionPlan>>;
/// Returns the table Statistics
diff --git a/rust/datafusion/src/datasource/empty.rs b/rust/datafusion/src/datasource/empty.rs
index c33572b24e..e6140cdb8d 100644
--- a/rust/datafusion/src/datasource/empty.rs
+++ b/rust/datafusion/src/datasource/empty.rs
@@ -54,6 +54,7 @@ impl TableProvider for EmptyTable {
projection: &Option<Vec<usize>>,
_batch_size: usize,
_filters: &[Expr],
+ _limit: Option<usize>,
) -> Result<Arc<dyn ExecutionPlan>> {
// even though there is no data, projections apply
let projection = match projection.clone() {
diff --git a/rust/datafusion/src/datasource/memory.rs b/rust/datafusion/src/datasource/memory.rs
index 51caa2eaba..514eac6dcd 100644
--- a/rust/datafusion/src/datasource/memory.rs
+++ b/rust/datafusion/src/datasource/memory.rs
@@ -115,7 +115,7 @@ impl MemTable {
output_partitions: Option<usize>,
) -> Result<Self> {
let schema = t.schema();
- let exec = t.scan(&None, batch_size, &[])?;
+ let exec = t.scan(&None, batch_size, &[], None)?;
let partition_count = exec.output_partitioning().partition_count();
let tasks = (0..partition_count)
@@ -177,6 +177,7 @@ impl TableProvider for MemTable {
projection: &Option<Vec<usize>>,
_batch_size: usize,
_filters: &[Expr],
+ _limit: Option<usize>,
) -> Result<Arc<dyn ExecutionPlan>> {
let columns: Vec<usize> = match projection {
Some(p) => p.clone(),
@@ -278,7 +279,7 @@ mod tests {
);
// scan with projection
- let exec = provider.scan(&Some(vec![2, 1]), 1024, &[])?;
+ let exec = provider.scan(&Some(vec![2, 1]), 1024, &[], None)?;
let mut it = exec.execute(0).await?;
let batch2 = it.next().await.unwrap()?;
assert_eq!(2, batch2.schema().fields().len());
@@ -308,7 +309,7 @@ mod tests {
let provider = MemTable::try_new(schema, vec![vec![batch]])?;
- let exec = provider.scan(&None, 1024, &[])?;
+ let exec = provider.scan(&None, 1024, &[], None)?;
let mut it = exec.execute(0).await?;
let batch1 = it.next().await.unwrap()?;
assert_eq!(3, batch1.schema().fields().len());
@@ -338,7 +339,7 @@ mod tests {
let projection: Vec<usize> = vec![0, 4];
- match provider.scan(&Some(projection), 1024, &[]) {
+ match provider.scan(&Some(projection), 1024, &[], None) {
Err(DataFusionError::Internal(e)) => {
assert_eq!("\"Projection index out of range\"", format!("{:?}", e))
}
@@ -459,7 +460,7 @@ mod tests {
let provider =
MemTable::try_new(Arc::new(merged_schema), vec![vec![batch1, batch2]])?;
- let exec = provider.scan(&None, 1024, &[])?;
+ let exec = provider.scan(&None, 1024, &[], None)?;
let mut it = exec.execute(0).await?;
let batch1 = it.next().await.unwrap()?;
assert_eq!(3, batch1.schema().fields().len());
diff --git a/rust/datafusion/src/datasource/parquet.rs b/rust/datafusion/src/datasource/parquet.rs
index 888103e6db..ed45230c0f 100644
--- a/rust/datafusion/src/datasource/parquet.rs
+++ b/rust/datafusion/src/datasource/parquet.rs
@@ -43,7 +43,7 @@ pub struct ParquetTable {
impl ParquetTable {
/// Attempt to initialize a new `ParquetTable` from a file path.
pub fn try_new(path: &str, max_concurrency: usize) -> Result<Self> {
- let parquet_exec = ParquetExec::try_from_path(path, None, None, 0, 1)?;
+ let parquet_exec = ParquetExec::try_from_path(path, None, None, 0, 1, None)?;
let schema = parquet_exec.schema();
Ok(Self {
path: path.to_string(),
@@ -83,14 +83,18 @@ impl TableProvider for ParquetTable {
projection: &Option<Vec<usize>>,
batch_size: usize,
filters: &[Expr],
+ limit: Option<usize>,
) -> Result<Arc<dyn ExecutionPlan>> {
let predicate = combine_filters(filters);
Ok(Arc::new(ParquetExec::try_from_path(
&self.path,
projection.clone(),
predicate,
- batch_size,
+ limit
+ .map(|l| std::cmp::min(l, batch_size))
+ .unwrap_or(batch_size),
self.max_concurrency,
+ limit,
)?))
}
@@ -113,7 +117,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, &[], None)?;
let stream = exec.execute(0).await?;
let count = stream
@@ -337,7 +341,7 @@ mod tests {
table: Arc<dyn TableProvider>,
projection: &Option<Vec<usize>>,
) -> Result<RecordBatch> {
- let exec = table.scan(projection, 1024, &[])?;
+ let exec = table.scan(projection, 1024, &[], None)?;
let mut it = exec.execute(0).await?;
it.next()
.await
diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rs
index 850ce745c8..ad5beef41e 100644
--- a/rust/datafusion/src/execution/context.rs
+++ b/rust/datafusion/src/execution/context.rs
@@ -42,6 +42,7 @@ use crate::logical_plan::{
};
use crate::optimizer::constant_folding::ConstantFolding;
use crate::optimizer::filter_push_down::FilterPushDown;
+use crate::optimizer::limit_push_down::LimitPushDown;
use crate::optimizer::optimizer::OptimizerRule;
use crate::optimizer::projection_push_down::ProjectionPushDown;
use crate::physical_plan::csv::CsvReadOptions;
@@ -244,6 +245,7 @@ impl ExecutionContext {
projected_schema: schema.to_dfschema_ref()?,
projection: None,
filters: vec![],
+ limit: None,
};
Ok(Arc::new(DataFrameImpl::new(
self.state.clone(),
@@ -316,6 +318,7 @@ impl ExecutionContext {
projected_schema: schema.to_dfschema_ref()?,
projection: None,
filters: vec![],
+ limit: None,
};
Ok(Arc::new(DataFrameImpl::new(
self.state.clone(),
@@ -519,6 +522,7 @@ impl ExecutionConfig {
Arc::new(ProjectionPushDown::new()),
Arc::new(FilterPushDown::new()),
Arc::new(HashBuildProbeOrder::new()),
+ Arc::new(LimitPushDown::new()),
],
query_planner: Arc::new(DefaultQueryPlanner {}),
}
diff --git a/rust/datafusion/src/logical_plan/builder.rs b/rust/datafusion/src/logical_plan/builder.rs
index a573b3f097..1f017b6f3c 100644
--- a/rust/datafusion/src/logical_plan/builder.rs
+++ b/rust/datafusion/src/logical_plan/builder.rs
@@ -120,6 +120,7 @@ impl LogicalPlanBuilder {
projected_schema,
projection,
filters: vec![],
+ limit: None,
};
Ok(Self::from(&table_scan))
diff --git a/rust/datafusion/src/logical_plan/plan.rs b/rust/datafusion/src/logical_plan/plan.rs
index b1219a9588..8aec9e668a 100644
--- a/rust/datafusion/src/logical_plan/plan.rs
+++ b/rust/datafusion/src/logical_plan/plan.rs
@@ -132,6 +132,8 @@ pub enum LogicalPlan {
projected_schema: DFSchemaRef,
/// Optional expressions to be used as filters by the table provider
filters: Vec<Expr>,
+ /// Optional limit to skip reading
+ limit: Option<usize>,
},
/// Produces no rows: An empty relation with an empty schema
EmptyRelation {
@@ -584,6 +586,7 @@ impl LogicalPlan {
ref table_name,
ref projection,
ref filters,
+ ref limit,
..
} => {
let sep = " ".repeat(min(1, table_name.len()));
@@ -597,6 +600,10 @@ impl LogicalPlan {
write!(f, ", filters={:?}", filters)?;
}
+ if let Some(n) = limit {
+ write!(f, ", limit={}", n)?;
+ }
+
Ok(())
}
LogicalPlan::Projection { ref expr, .. } => {
diff --git a/rust/datafusion/src/optimizer/filter_push_down.rs b/rust/datafusion/src/optimizer/filter_push_down.rs
index 41596c5bee..0ae8e06015 100644
--- a/rust/datafusion/src/optimizer/filter_push_down.rs
+++ b/rust/datafusion/src/optimizer/filter_push_down.rs
@@ -346,6 +346,7 @@ fn optimize(plan: &LogicalPlan, mut state: State) -> Result<LogicalPlan> {
filters,
projection,
table_name,
+ limit,
} => {
let mut used_columns = HashSet::new();
let mut new_filters = filters.clone();
@@ -376,6 +377,7 @@ fn optimize(plan: &LogicalPlan, mut state: State) -> Result<LogicalPlan> {
projected_schema: projected_schema.clone(),
table_name: table_name.clone(),
filters: new_filters,
+ limit: *limit,
},
)
}
@@ -940,6 +942,7 @@ mod tests {
_: &Option<Vec<usize>>,
_: usize,
_: &[Expr],
+ _: Option<usize>,
) -> Result<Arc<dyn ExecutionPlan>> {
unimplemented!()
}
@@ -974,6 +977,7 @@ mod tests {
)?),
projection: None,
source: Arc::new(test_provider),
+ limit: None,
};
LogicalPlanBuilder::from(&table_scan)
diff --git a/rust/datafusion/src/optimizer/hash_build_probe_order.rs b/rust/datafusion/src/optimizer/hash_build_probe_order.rs
index a47195aba2..cb6d5c440e 100644
--- a/rust/datafusion/src/optimizer/hash_build_probe_order.rs
+++ b/rust/datafusion/src/optimizer/hash_build_probe_order.rs
@@ -204,6 +204,7 @@ mod tests {
_projection: &Option<Vec<usize>>,
_batch_size: usize,
_filters: &[Expr],
+ _limit: Option<usize>,
) -> Result<std::sync::Arc<dyn crate::physical_plan::ExecutionPlan>> {
unimplemented!()
}
@@ -233,6 +234,7 @@ mod tests {
source: Arc::new(TestTableProvider { num_rows: 1000 }),
projected_schema: Arc::new(DFSchema::empty()),
filters: vec![],
+ limit: None,
};
let lp_right = LogicalPlan::TableScan {
@@ -241,6 +243,7 @@ mod tests {
source: Arc::new(TestTableProvider { num_rows: 100 }),
projected_schema: Arc::new(DFSchema::empty()),
filters: vec![],
+ limit: None,
};
assert!(should_swap_join_order(&lp_left, &lp_right));
diff --git a/rust/datafusion/src/optimizer/limit_push_down.rs b/rust/datafusion/src/optimizer/limit_push_down.rs
new file mode 100644
index 0000000000..67af69bc6b
--- /dev/null
+++ b/rust/datafusion/src/optimizer/limit_push_down.rs
@@ -0,0 +1,204 @@
+// 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.
+
+//! Optimizer rule to push down LIMIT in the query plan
+//! It will push down through projection, limits (taking the smaller limit)
+use std::sync::Arc;
+
+use super::utils;
+use crate::error::Result;
+use crate::logical_plan::LogicalPlan;
+use crate::optimizer::optimizer::OptimizerRule;
+
+/// Optimization rule that tries pushes down LIMIT n
+/// where applicable to reduce the amount of scanned / processed data
+pub struct LimitPushDown {}
+
+impl LimitPushDown {
+ #[allow(missing_docs)]
+ pub fn new() -> Self {
+ Self {}
+ }
+}
+
+fn limit_push_down(
+ upper_limit: Option<usize>,
+ plan: &LogicalPlan,
+) -> Result<LogicalPlan> {
+ match plan {
+ LogicalPlan::Limit { n, input } => {
+ let smallest = upper_limit.map(|x| std::cmp::min(x, *n)).unwrap_or(*n);
+ Ok(LogicalPlan::Limit {
+ n: smallest,
+ // push down limit to plan (minimum of upper limit and current limit)
+ input: Arc::new(limit_push_down(Some(smallest), input.as_ref())?),
+ })
+ }
+ LogicalPlan::TableScan {
+ table_name,
+ source,
+ projection,
+ filters,
+ limit,
+ projected_schema,
+ } => {
+ if let Some(n) = upper_limit {
+ Ok(LogicalPlan::TableScan {
+ table_name: table_name.clone(),
+ source: source.clone(),
+ projection: projection.clone(),
+ filters: filters.clone(),
+ limit: limit.map(|x| std::cmp::min(x, n)).or(Some(n)),
+ projected_schema: projected_schema.clone(),
+ })
+ } else {
+ Ok(plan.clone())
+ }
+ }
+ LogicalPlan::Projection {
+ expr,
+ input,
+ schema,
+ } => {
+ // Push down limit directly (projection doesn't change number of rows)
+ Ok(LogicalPlan::Projection {
+ expr: expr.clone(),
+ input: Arc::new(limit_push_down(upper_limit, input.as_ref())?),
+ schema: schema.clone(),
+ })
+ }
+ // For other nodes we can't push down the limit
+ // But try to recurse and find other limit nodes to push down
+ _ => {
+ let expr = plan.expressions();
+
+ // apply the optimization to all inputs of the plan
+ let inputs = plan.inputs();
+ let new_inputs = inputs
+ .iter()
+ .map(|plan| limit_push_down(None, plan))
+ .collect::<Result<Vec<_>>>()?;
+
+ utils::from_plan(plan, &expr, &new_inputs)
+ }
+ }
+}
+
+impl OptimizerRule for LimitPushDown {
+ fn optimize(&self, plan: &LogicalPlan) -> Result<LogicalPlan> {
+ limit_push_down(None, plan)
+ }
+
+ fn name(&self) -> &str {
+ "limit_push_down"
+ }
+}
+#[cfg(test)]
+mod test {
+ use super::*;
+ use crate::{
+ logical_plan::{col, max, LogicalPlan, LogicalPlanBuilder},
+ test::*,
+ };
+
+ fn assert_optimized_plan_eq(plan: &LogicalPlan, expected: &str) {
+ let rule = LimitPushDown::new();
+ let optimized_plan = rule.optimize(plan).expect("failed to optimize plan");
+ let formatted_plan = format!("{:?}", optimized_plan);
+ assert_eq!(formatted_plan, expected);
+ }
+
+ #[test]
+ fn limit_pushdown_projection_table_provider() -> Result<()> {
+ let table_scan = test_table_scan()?;
+
+ let plan = LogicalPlanBuilder::from(&table_scan)
+ .project(&[col("a")])?
+ .limit(1000)?
+ .build()?;
+
+ // Should push the limit down to table provider
+ // When it has a select
+ let expected = "Limit: 1000\
+ \n Projection: #a\
+ \n TableScan: test projection=None, limit=1000";
+
+ assert_optimized_plan_eq(&plan, expected);
+
+ Ok(())
+ }
+ #[test]
+ fn limit_push_down_take_smaller_limit() -> Result<()> {
+ let table_scan = test_table_scan()?;
+
+ let plan = LogicalPlanBuilder::from(&table_scan)
+ .limit(1000)?
+ .limit(10)?
+ .build()?;
+
+ // Should push down the smallest limit
+ // Towards table scan
+ // This rule doesn't replace multiple limits
+ let expected = "Limit: 10\
+ \n Limit: 10\
+ \n TableScan: test projection=None, limit=10";
+
+ assert_optimized_plan_eq(&plan, expected);
+
+ Ok(())
+ }
+
+ #[test]
+ fn limit_doesnt_push_down_aggregation() -> Result<()> {
+ let table_scan = test_table_scan()?;
+
+ let plan = LogicalPlanBuilder::from(&table_scan)
+ .aggregate(&[col("a")], &[max(col("b"))])?
+ .limit(1000)?
+ .build()?;
+
+ // Limit should *not* push down aggregate node
+ let expected = "Limit: 1000\
+ \n Aggregate: groupBy=[[#a]], aggr=[[MAX(#b)]]\
+ \n TableScan: test projection=None";
+
+ assert_optimized_plan_eq(&plan, expected);
+
+ Ok(())
+ }
+
+ #[test]
+ fn multi_stage_limit_recurses_to_deeper_limit() -> Result<()> {
+ let table_scan = test_table_scan()?;
+
+ let plan = LogicalPlanBuilder::from(&table_scan)
+ .limit(1000)?
+ .aggregate(&[col("a")], &[max(col("b"))])?
+ .limit(10)?
+ .build()?;
+
+ // Limit should use deeper LIMIT 1000, but Limit 10 shouldn't push down aggregation
+ let expected = "Limit: 10\
+ \n Aggregate: groupBy=[[#a]], aggr=[[MAX(#b)]]\
+ \n Limit: 1000\
+ \n TableScan: test projection=None, limit=1000";
+
+ assert_optimized_plan_eq(&plan, expected);
+
+ Ok(())
+ }
+}
diff --git a/rust/datafusion/src/optimizer/mod.rs b/rust/datafusion/src/optimizer/mod.rs
index d8dc74a64a..87dc62da2a 100644
--- a/rust/datafusion/src/optimizer/mod.rs
+++ b/rust/datafusion/src/optimizer/mod.rs
@@ -21,6 +21,8 @@
pub mod constant_folding;
pub mod filter_push_down;
pub mod hash_build_probe_order;
+pub mod limit_push_down;
pub mod optimizer;
pub mod projection_push_down;
+
pub mod utils;
diff --git a/rust/datafusion/src/optimizer/projection_push_down.rs b/rust/datafusion/src/optimizer/projection_push_down.rs
index 115da4b301..6da63ee9a8 100644
--- a/rust/datafusion/src/optimizer/projection_push_down.rs
+++ b/rust/datafusion/src/optimizer/projection_push_down.rs
@@ -244,6 +244,7 @@ fn optimize_plan(
source,
projection,
filters,
+ limit,
..
} => {
let (projection, projected_schema) = get_projected_schema(
@@ -260,6 +261,7 @@ fn optimize_plan(
projection: Some(projection),
projected_schema,
filters: filters.clone(),
+ limit: *limit,
})
}
LogicalPlan::Explain {
diff --git a/rust/datafusion/src/physical_plan/csv.rs b/rust/datafusion/src/physical_plan/csv.rs
index d62d18756f..7ee5ae3fd9 100644
--- a/rust/datafusion/src/physical_plan/csv.rs
+++ b/rust/datafusion/src/physical_plan/csv.rs
@@ -127,6 +127,8 @@ pub struct CsvExec {
projected_schema: SchemaRef,
/// Batch size
batch_size: usize,
+ /// Limit in nr. of rows
+ limit: Option<usize>,
}
impl CsvExec {
@@ -136,6 +138,7 @@ impl CsvExec {
options: CsvReadOptions,
projection: Option<Vec<usize>>,
batch_size: usize,
+ limit: Option<usize>,
) -> Result<Self> {
let file_extension = String::from(options.file_extension);
@@ -169,6 +172,7 @@ impl CsvExec {
projection,
projected_schema: Arc::new(projected_schema),
batch_size,
+ limit,
})
}
@@ -212,6 +216,11 @@ impl CsvExec {
self.batch_size
}
+ /// Limit
+ pub fn limit(&self) -> Option<usize> {
+ self.limit
+ }
+
/// Infer schema for given CSV dataset
pub fn try_infer_schema(
filenames: &[String],
@@ -270,6 +279,7 @@ impl ExecutionPlan for CsvExec {
self.delimiter,
&self.projection,
self.batch_size,
+ self.limit,
)?))
}
}
@@ -289,15 +299,19 @@ impl CsvStream {
delimiter: Option<u8>,
projection: &Option<Vec<usize>>,
batch_size: usize,
+ limit: Option<usize>,
) -> Result<Self> {
let file = File::open(filename)?;
+ let start_line = if has_header { 1 } else { 0 };
+ let bounds = limit.map(|x| (0, x + start_line));
+
let reader = csv::Reader::new(
file,
schema,
has_header,
delimiter,
batch_size,
- None,
+ bounds,
projection.clone(),
);
@@ -340,6 +354,7 @@ mod tests {
CsvReadOptions::new().schema(&schema),
Some(vec![0, 2, 4]),
1024,
+ None,
)?;
assert_eq!(13, csv.schema.fields().len());
assert_eq!(3, csv.projected_schema.fields().len());
@@ -362,8 +377,13 @@ mod tests {
let testdata = arrow::util::test_util::arrow_test_data();
let filename = "aggregate_test_100.csv";
let path = format!("{}/csv/{}", testdata, filename);
- let csv =
- CsvExec::try_new(&path, CsvReadOptions::new().schema(&schema), None, 1024)?;
+ let csv = CsvExec::try_new(
+ &path,
+ CsvReadOptions::new().schema(&schema),
+ None,
+ 1024,
+ None,
+ )?;
assert_eq!(13, csv.schema.fields().len());
assert_eq!(13, csv.projected_schema.fields().len());
assert_eq!(13, csv.file_schema().fields().len());
diff --git a/rust/datafusion/src/physical_plan/filter.rs b/rust/datafusion/src/physical_plan/filter.rs
index 1db74e1f44..61af78db8e 100644
--- a/rust/datafusion/src/physical_plan/filter.rs
+++ b/rust/datafusion/src/physical_plan/filter.rs
@@ -199,8 +199,13 @@ mod tests {
let partitions = 4;
let path = test::create_partitioned_csv("aggregate_test_100.csv", partitions)?;
- let csv =
- CsvExec::try_new(&path, CsvReadOptions::new().schema(&schema), None, 1024)?;
+ let csv = CsvExec::try_new(
+ &path,
+ CsvReadOptions::new().schema(&schema),
+ None,
+ 1024,
+ None,
+ )?;
let predicate: Arc<dyn PhysicalExpr> = binary(
binary(
diff --git a/rust/datafusion/src/physical_plan/limit.rs b/rust/datafusion/src/physical_plan/limit.rs
index 70fb2b25f7..35be89a5aa 100644
--- a/rust/datafusion/src/physical_plan/limit.rs
+++ b/rust/datafusion/src/physical_plan/limit.rs
@@ -267,8 +267,13 @@ mod tests {
let path =
test::create_partitioned_csv("aggregate_test_100.csv", num_partitions)?;
- let csv =
- CsvExec::try_new(&path, CsvReadOptions::new().schema(&schema), None, 1024)?;
+ let csv = CsvExec::try_new(
+ &path,
+ CsvReadOptions::new().schema(&schema),
+ None,
+ 1024,
+ None,
+ )?;
// input should have 4 partitions
assert_eq!(csv.output_partitioning().partition_count(), num_partitions);
diff --git a/rust/datafusion/src/physical_plan/merge.rs b/rust/datafusion/src/physical_plan/merge.rs
index 0bfd11bdaa..c66532b73c 100644
--- a/rust/datafusion/src/physical_plan/merge.rs
+++ b/rust/datafusion/src/physical_plan/merge.rs
@@ -195,8 +195,13 @@ mod tests {
let path =
test::create_partitioned_csv("aggregate_test_100.csv", num_partitions)?;
- let csv =
- CsvExec::try_new(&path, CsvReadOptions::new().schema(&schema), None, 1024)?;
+ let csv = CsvExec::try_new(
+ &path,
+ CsvReadOptions::new().schema(&schema),
+ None,
+ 1024,
+ None,
+ )?;
// input should have 4 partitions
assert_eq!(csv.output_partitioning().partition_count(), num_partitions);
diff --git a/rust/datafusion/src/physical_plan/parquet.rs b/rust/datafusion/src/physical_plan/parquet.rs
index 99b7933e99..5e9b156275 100644
--- a/rust/datafusion/src/physical_plan/parquet.rs
+++ b/rust/datafusion/src/physical_plan/parquet.rs
@@ -81,6 +81,8 @@ pub struct ParquetExec {
statistics: Statistics,
/// Optional predicate builder
predicate_builder: Option<RowGroupPredicateBuilder>,
+ /// Optional limit of the number of rows
+ limit: Option<usize>,
}
/// Represents one partition of a Parquet data set and this currently means one Parquet file.
@@ -109,6 +111,7 @@ impl ParquetExec {
predicate: Option<Expr>,
batch_size: usize,
max_concurrency: usize,
+ limit: Option<usize>,
) -> Result<Self> {
// build a list of filenames from the specified path, which could be a single file or
// a directory containing one or more parquet files
@@ -130,6 +133,7 @@ impl ParquetExec {
predicate,
batch_size,
max_concurrency,
+ limit,
)
}
}
@@ -142,6 +146,7 @@ impl ParquetExec {
predicate: Option<Expr>,
batch_size: usize,
max_concurrency: usize,
+ limit: Option<usize>,
) -> Result<Self> {
// build a list of Parquet partitions with statistics and gather all unique schemas
// used in this data set
@@ -152,10 +157,13 @@ impl ParquetExec {
let mut num_rows = 0;
let mut total_byte_size = 0;
let mut null_counts = Vec::new();
-
+ let mut limit_exhausted = false;
for chunk in chunks {
- let filenames: Vec<String> = chunk.iter().map(|x| x.to_string()).collect();
+ let mut filenames: Vec<String> =
+ chunk.iter().map(|x| x.to_string()).collect();
+ let mut total_files = 0;
for filename in &filenames {
+ total_files += 1;
let file = File::open(filename)?;
let file_reader = Arc::new(SerializedFileReader::new(file)?);
let mut arrow_reader = ParquetFileArrowReader::new(file_reader);
@@ -181,6 +189,10 @@ impl ParquetExec {
for (i, cnt) in columns_null_counts.enumerate() {
null_counts[i] += cnt
}
+ if limit.map(|x| num_rows >= x as i64).unwrap_or(false) {
+ limit_exhausted = true;
+ break;
+ }
}
}
@@ -199,10 +211,15 @@ impl ParquetExec {
total_byte_size: Some(total_byte_size as usize),
column_statistics: Some(column_stats),
};
+ // remove files that are not needed in case of limit
+ filenames.truncate(total_files);
partitions.push(ParquetPartition {
filenames,
statistics,
});
+ if limit_exhausted {
+ break;
+ }
}
// we currently get the schema information from the first file rather than do
@@ -226,6 +243,7 @@ impl ParquetExec {
projection,
predicate_builder,
batch_size,
+ limit,
))
}
@@ -236,6 +254,7 @@ impl ParquetExec {
projection: Option<Vec<usize>>,
predicate_builder: Option<RowGroupPredicateBuilder>,
batch_size: usize,
+ limit: Option<usize>,
) -> Self {
let projection = match projection {
Some(p) => p,
@@ -299,6 +318,7 @@ impl ParquetExec {
predicate_builder,
batch_size,
statistics,
+ limit,
}
}
@@ -835,6 +855,7 @@ impl ExecutionPlan for ParquetExec {
let projection = self.projection.clone();
let predicate_builder = self.predicate_builder.clone();
let batch_size = self.batch_size;
+ let limit = self.limit;
task::spawn_blocking(move || {
if let Err(e) = read_files(
@@ -843,6 +864,7 @@ impl ExecutionPlan for ParquetExec {
&predicate_builder,
batch_size,
response_tx,
+ limit,
) {
println!("Parquet reader thread terminated due to error: {:?}", e);
}
@@ -872,8 +894,10 @@ fn read_files(
predicate_builder: &Option<RowGroupPredicateBuilder>,
batch_size: usize,
response_tx: Sender<ArrowResult<RecordBatch>>,
+ limit: Option<usize>,
) -> Result<()> {
- for filename in filenames {
+ let mut total_rows = 0;
+ 'outer: for filename in filenames {
let file = File::open(&filename)?;
let mut file_reader = SerializedFileReader::new(file)?;
if let Some(predicate_builder) = predicate_builder {
@@ -888,7 +912,11 @@ fn read_files(
match batch_reader.next() {
Some(Ok(batch)) => {
//println!("ParquetExec got new batch from {}", filename);
- send_result(&response_tx, Ok(batch))?
+ total_rows += batch.num_rows();
+ send_result(&response_tx, Ok(batch))?;
+ if limit.map(|l| total_rows >= l).unwrap_or(false) {
+ break 'outer;
+ }
}
None => {
break;
@@ -994,8 +1022,14 @@ mod tests {
async fn test() -> Result<()> {
let testdata = arrow::util::test_util::parquet_test_data();
let filename = format!("{}/alltypes_plain.parquet", testdata);
- let parquet_exec =
- ParquetExec::try_from_path(&filename, Some(vec![0, 1, 2]), None, 1024, 4)?;
+ let parquet_exec = ParquetExec::try_from_path(
+ &filename,
+ Some(vec![0, 1, 2]),
+ None,
+ 1024,
+ 4,
+ None,
+ )?;
assert_eq!(parquet_exec.output_partitioning().partition_count(), 1);
let mut results = parquet_exec.execute(0).await?;
diff --git a/rust/datafusion/src/physical_plan/planner.rs b/rust/datafusion/src/physical_plan/planner.rs
index c83b639c23..ef1cb1160a 100644
--- a/rust/datafusion/src/physical_plan/planner.rs
+++ b/rust/datafusion/src/physical_plan/planner.rs
@@ -176,8 +176,9 @@ impl DefaultPhysicalPlanner {
source,
projection,
filters,
+ limit,
..
- } => source.scan(projection, batch_size, filters),
+ } => source.scan(projection, batch_size, filters, *limit),
LogicalPlan::Aggregate {
input,
group_expr,
diff --git a/rust/datafusion/src/physical_plan/projection.rs b/rust/datafusion/src/physical_plan/projection.rs
index b22f477bdb..a881beb453 100644
--- a/rust/datafusion/src/physical_plan/projection.rs
+++ b/rust/datafusion/src/physical_plan/projection.rs
@@ -197,8 +197,13 @@ mod tests {
let partitions = 4;
let path = test::create_partitioned_csv("aggregate_test_100.csv", partitions)?;
- let csv =
- CsvExec::try_new(&path, CsvReadOptions::new().schema(&schema), None, 1024)?;
+ let csv = CsvExec::try_new(
+ &path,
+ CsvReadOptions::new().schema(&schema),
+ None,
+ 1024,
+ None,
+ )?;
// pick column c1 and name it column c1 in the output schema
let projection =
diff --git a/rust/datafusion/src/physical_plan/sort.rs b/rust/datafusion/src/physical_plan/sort.rs
index 042b9f1da8..b35ed688a8 100644
--- a/rust/datafusion/src/physical_plan/sort.rs
+++ b/rust/datafusion/src/physical_plan/sort.rs
@@ -271,8 +271,13 @@ mod tests {
let schema = test::aggr_test_schema();
let partitions = 4;
let path = test::create_partitioned_csv("aggregate_test_100.csv", partitions)?;
- let csv =
- CsvExec::try_new(&path, CsvReadOptions::new().schema(&schema), None, 1024)?;
+ let csv = CsvExec::try_new(
+ &path,
+ CsvReadOptions::new().schema(&schema),
+ None,
+ 1024,
+ None,
+ )?;
let sort_exec = Arc::new(SortExec::try_new(
vec![
diff --git a/rust/datafusion/tests/custom_sources.rs b/rust/datafusion/tests/custom_sources.rs
index 9778fead20..0bc699ceff 100644
--- a/rust/datafusion/tests/custom_sources.rs
+++ b/rust/datafusion/tests/custom_sources.rs
@@ -144,6 +144,7 @@ impl TableProvider for CustomTableProvider {
projection: &Option<Vec<usize>>,
_batch_size: usize,
_filters: &[Expr],
+ _limit: Option<usize>,
) -> 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.rs
index fe648bd3a1..a64f7fb74f 100644
--- a/rust/datafusion/tests/provider_filter_pushdown.rs
+++ b/rust/datafusion/tests/provider_filter_pushdown.rs
@@ -106,6 +106,7 @@ impl TableProvider for CustomProvider {
_: &Option<Vec<usize>>,
_: usize,
filters: &[Expr],
+ _: Option<usize>,
) -> Result<Arc<dyn ExecutionPlan>> {
match &filters[0] {
Expr::BinaryExpr { right, .. } => {