Skip to content

Apache DataFusion SQL Query Engine

Enable repartitioning on MemTable. (#15409)

wiedld58f61c831e31
diff --git a/datafusion/common/src/config.rs b/datafusion/common/src/config.rs
index 08e9a0c453..d6530931cb 100644
--- a/datafusion/common/src/config.rs
+++ b/datafusion/common/src/config.rs
@@ -638,13 +638,20 @@ config_namespace! {
/// long runner execution, all types of joins may encounter out-of-memory errors.
pub allow_symmetric_joins_without_pruning: bool, default = true
- /// When set to `true`, file groups will be repartitioned to achieve maximum parallelism.
- /// Currently Parquet and CSV formats are supported.
+ /// When set to `true`, datasource partitions will be repartitioned to achieve maximum parallelism.
+ /// This applies to both in-memory partitions and FileSource's file groups (1 group is 1 partition).
///
- /// If set to `true`, all files will be repartitioned evenly (i.e., a single large file
+ /// For FileSources, only Parquet and CSV formats are currently supported.
+ ///
+ /// If set to `true` for a FileSource, all files will be repartitioned evenly (i.e., a single large file
/// might be partitioned into smaller chunks) for parallel scanning.
- /// If set to `false`, different files will be read in parallel, but repartitioning won't
+ /// If set to `false` for a FileSource, different files will be read in parallel, but repartitioning won't
/// happen within a single file.
+ ///
+ /// If set to `true` for an in-memory source, all memtable's partitions will have their batches
+ /// repartitioned evenly to the desired number of `target_partitions`. Repartitioning can change
+ /// the total number of partitions and batches per partition, but does not slice the initial
+ /// record tables provided to the MemTable on creation.
pub repartition_file_scans: bool, default = true
/// Should DataFusion repartition data using the partitions keys to execute window
diff --git a/datafusion/core/tests/fuzz_cases/aggregate_fuzz.rs b/datafusion/core/tests/fuzz_cases/aggregate_fuzz.rs
index 8c70b02a54..98373ce4eb 100644
--- a/datafusion/core/tests/fuzz_cases/aggregate_fuzz.rs
+++ b/datafusion/core/tests/fuzz_cases/aggregate_fuzz.rs
@@ -512,7 +512,9 @@ async fn group_by_string_test(
let expected = compute_counts(&input, column_name);
let schema = input[0].schema();
- let session_config = SessionConfig::new().with_batch_size(50);
+ let session_config = SessionConfig::new()
+ .with_batch_size(50)
+ .with_repartition_file_scans(false);
let ctx = SessionContext::new_with_config(session_config);
let provider = MemTable::try_new(schema.clone(), vec![input]).unwrap();
diff --git a/datafusion/core/tests/fuzz_cases/sort_fuzz.rs b/datafusion/core/tests/fuzz_cases/sort_fuzz.rs
index 0b0f0aa2f1..e47a983779 100644
--- a/datafusion/core/tests/fuzz_cases/sort_fuzz.rs
+++ b/datafusion/core/tests/fuzz_cases/sort_fuzz.rs
@@ -248,7 +248,7 @@ impl SortTest {
let exec = MemorySourceConfig::try_new_exec(&input, schema, None).unwrap();
let sort = Arc::new(SortExec::new(sort_ordering, exec));
- let session_config = SessionConfig::new();
+ let session_config = SessionConfig::new().with_repartition_file_scans(false);
let session_ctx = if let Some(pool_size) = self.pool_size {
// Make sure there is enough space for the initial spill
// reservation
diff --git a/datafusion/core/tests/memory_limit/mod.rs b/datafusion/core/tests/memory_limit/mod.rs
index c8beedb8c2..3a4817941f 100644
--- a/datafusion/core/tests/memory_limit/mod.rs
+++ b/datafusion/core/tests/memory_limit/mod.rs
@@ -458,7 +458,9 @@ async fn test_stringview_external_sort() {
.with_memory_pool(Arc::new(FairSpillPool::new(60 * 1024 * 1024)));
let runtime = builder.build_arc().unwrap();
- let config = SessionConfig::new().with_sort_spill_reservation_bytes(40 * 1024 * 1024);
+ let config = SessionConfig::new()
+ .with_sort_spill_reservation_bytes(40 * 1024 * 1024)
+ .with_repartition_file_scans(false);
let ctx = SessionContext::new_with_config_rt(config, runtime);
ctx.register_table("t", Arc::new(table)).unwrap();
diff --git a/datafusion/core/tests/physical_optimizer/enforce_distribution.rs b/datafusion/core/tests/physical_optimizer/enforce_distribution.rs
index bc6957ff7b..64aa799324 100644
--- a/datafusion/core/tests/physical_optimizer/enforce_distribution.rs
+++ b/datafusion/core/tests/physical_optimizer/enforce_distribution.rs
@@ -19,19 +19,25 @@ use std::fmt::Debug;
use std::ops::Deref;
use std::sync::Arc;
-use crate::physical_optimizer::test_utils::parquet_exec_with_sort;
use crate::physical_optimizer::test_utils::{
check_integrity, coalesce_partitions_exec, repartition_exec, schema,
sort_merge_join_exec, sort_preserving_merge_exec,
};
+use crate::physical_optimizer::test_utils::{
+ parquet_exec_with_sort, parquet_exec_with_stats,
+};
+use arrow::array::{RecordBatch, UInt64Array, UInt8Array};
use arrow::compute::SortOptions;
+use arrow_schema::{DataType, Field, Schema, SchemaRef};
use datafusion::config::ConfigOptions;
use datafusion::datasource::file_format::file_compression_type::FileCompressionType;
use datafusion::datasource::listing::PartitionedFile;
use datafusion::datasource::object_store::ObjectStoreUrl;
use datafusion::datasource::physical_plan::{CsvSource, ParquetSource};
use datafusion::datasource::source::DataSourceExec;
+use datafusion::datasource::MemTable;
+use datafusion::prelude::{SessionConfig, SessionContext};
use datafusion_common::error::Result;
use datafusion_common::tree_node::{Transformed, TransformedResult, TreeNode};
use datafusion_common::ScalarValue;
@@ -3473,6 +3479,106 @@ fn optimize_away_unnecessary_repartition2() -> Result<()> {
Ok(())
}
+/// Ensures that `DataSourceExec` has been repartitioned into `target_partitions` file groups
+#[tokio::test]
+async fn test_distribute_sort_parquet() -> Result<()> {
+ let test_config: TestConfig =
+ TestConfig::default().with_prefer_repartition_file_scans(1000);
+ assert!(
+ test_config.config.optimizer.repartition_file_scans,
+ "should enable scans to be repartitioned"
+ );
+
+ let schema = schema();
+ let sort_key = LexOrdering::new(vec![PhysicalSortExpr {
+ expr: col("c", &schema).unwrap(),
+ options: SortOptions::default(),
+ }]);
+ let physical_plan = sort_exec(sort_key, parquet_exec_with_stats(10000 * 8192), false);
+
+ // prior to optimization, this is the starting plan
+ let starting = &[
+ "SortExec: expr=[c@2 ASC], preserve_partitioning=[false]",
+ " DataSourceExec: file_groups={1 group: [[x]]}, projection=[a, b, c, d, e], file_type=parquet",
+ ];
+ plans_matches_expected!(starting, physical_plan.clone());
+
+ // what the enforce distribution run does.
+ let expected = &[
+ "SortExec: expr=[c@2 ASC], preserve_partitioning=[false]",
+ " CoalescePartitionsExec",
+ " DataSourceExec: file_groups={10 groups: [[x:0..8192000], [x:8192000..16384000], [x:16384000..24576000], [x:24576000..32768000], [x:32768000..40960000], [x:40960000..49152000], [x:49152000..57344000], [x:57344000..65536000], [x:65536000..73728000], [x:73728000..81920000]]}, projection=[a, b, c, d, e], file_type=parquet",
+ ];
+ test_config.run(expected, physical_plan.clone(), &[Run::Distribution])?;
+
+ // what the sort parallelization (in enforce sorting), does after the enforce distribution changes
+ let expected = &[
+ "SortPreservingMergeExec: [c@2 ASC]",
+ " SortExec: expr=[c@2 ASC], preserve_partitioning=[true]",
+ " DataSourceExec: file_groups={10 groups: [[x:0..8192000], [x:8192000..16384000], [x:16384000..24576000], [x:24576000..32768000], [x:32768000..40960000], [x:40960000..49152000], [x:49152000..57344000], [x:57344000..65536000], [x:65536000..73728000], [x:73728000..81920000]]}, projection=[a, b, c, d, e], file_type=parquet",
+ ];
+ test_config.run(expected, physical_plan, &[Run::Distribution, Run::Sorting])?;
+ Ok(())
+}
+
+/// Ensures that `DataSourceExec` has been repartitioned into `target_partitions` memtable groups
+#[tokio::test]
+async fn test_distribute_sort_memtable() -> Result<()> {
+ let test_config: TestConfig =
+ TestConfig::default().with_prefer_repartition_file_scans(1000);
+ assert!(
+ test_config.config.optimizer.repartition_file_scans,
+ "should enable scans to be repartitioned"
+ );
+
+ let mem_table = create_memtable()?;
+ let session_config = SessionConfig::new()
+ .with_repartition_file_min_size(1000)
+ .with_target_partitions(3);
+ let ctx = SessionContext::new_with_config(session_config);
+ ctx.register_table("users", Arc::new(mem_table))?;
+
+ let dataframe = ctx.sql("SELECT * FROM users order by id;").await?;
+ let physical_plan = dataframe.create_physical_plan().await?;
+
+ // this is the final, optimized plan
+ let expected = &[
+ "SortPreservingMergeExec: [id@0 ASC NULLS LAST]",
+ " SortExec: expr=[id@0 ASC NULLS LAST], preserve_partitioning=[true]",
+ " DataSourceExec: partitions=3, partition_sizes=[34, 33, 33]",
+ ];
+ plans_matches_expected!(expected, physical_plan);
+
+ Ok(())
+}
+
+/// Create a [`MemTable`] with 100 batches of 8192 rows each, in 1 partition
+fn create_memtable() -> Result<MemTable> {
+ let mut batches = Vec::with_capacity(100);
+ for _ in 0..100 {
+ batches.push(create_record_batch()?);
+ }
+ let partitions = vec![batches];
+ MemTable::try_new(get_schema(), partitions)
+}
+
+fn create_record_batch() -> Result<RecordBatch> {
+ let id_array = UInt8Array::from(vec![1; 8192]);
+ let account_array = UInt64Array::from(vec![9000; 8192]);
+
+ Ok(RecordBatch::try_new(
+ get_schema(),
+ vec![Arc::new(id_array), Arc::new(account_array)],
+ )
+ .unwrap())
+}
+
+fn get_schema() -> SchemaRef {
+ SchemaRef::new(Schema::new(vec![
+ Field::new("id", DataType::UInt8, false),
+ Field::new("bank_account", DataType::UInt64, true),
+ ]))
+}
#[test]
fn test_replace_order_preserving_variants_with_fetch() -> Result<()> {
// Create a base plan
diff --git a/datafusion/core/tests/physical_optimizer/test_utils.rs b/datafusion/core/tests/physical_optimizer/test_utils.rs
index 4587f99989..0e36e83014 100644
--- a/datafusion/core/tests/physical_optimizer/test_utils.rs
+++ b/datafusion/core/tests/physical_optimizer/test_utils.rs
@@ -30,9 +30,10 @@ use datafusion::datasource::memory::MemorySourceConfig;
use datafusion::datasource::physical_plan::ParquetSource;
use datafusion::datasource::source::DataSourceExec;
use datafusion_common::config::ConfigOptions;
+use datafusion_common::stats::Precision;
use datafusion_common::tree_node::{Transformed, TransformedResult, TreeNode};
use datafusion_common::utils::expr::COUNT_STAR_EXPANSION;
-use datafusion_common::{JoinType, Result};
+use datafusion_common::{ColumnStatistics, JoinType, Result, Statistics};
use datafusion_datasource::file_scan_config::FileScanConfigBuilder;
use datafusion_execution::object_store::ObjectStoreUrl;
use datafusion_execution::{SendableRecordBatchStream, TaskContext};
@@ -96,6 +97,48 @@ pub(crate) fn parquet_exec_with_sort(
DataSourceExec::from_data_source(config)
}
+fn int64_stats() -> ColumnStatistics {
+ ColumnStatistics {
+ null_count: Precision::Absent,
+ sum_value: Precision::Absent,
+ max_value: Precision::Exact(1_000_000.into()),
+ min_value: Precision::Exact(0.into()),
+ distinct_count: Precision::Absent,
+ }
+}
+
+fn column_stats() -> Vec<ColumnStatistics> {
+ vec![
+ int64_stats(), // a
+ int64_stats(), // b
+ int64_stats(), // c
+ ColumnStatistics::default(),
+ ColumnStatistics::default(),
+ ]
+}
+
+/// Create parquet datasource exec using schema from [`schema`].
+pub(crate) fn parquet_exec_with_stats(file_size: u64) -> Arc<DataSourceExec> {
+ let mut statistics = Statistics::new_unknown(&schema());
+ statistics.num_rows = Precision::Inexact(10000);
+ statistics.column_statistics = column_stats();
+
+ let config = FileScanConfigBuilder::new(
+ ObjectStoreUrl::parse("test:///").unwrap(),
+ schema(),
+ Arc::new(ParquetSource::new(Default::default())),
+ )
+ .with_file(PartitionedFile::new("x".to_string(), file_size))
+ .with_statistics(statistics)
+ .build();
+
+ assert_eq!(
+ config.file_source.statistics().unwrap().num_rows,
+ Precision::Inexact(10000)
+ );
+ DataSourceExec::from_data_source(config)
+}
+
pub fn schema() -> SchemaRef {
Arc::new(Schema::new(vec![
Field::new("a", DataType::Int64, true),
diff --git a/datafusion/datasource/src/memory.rs b/datafusion/datasource/src/memory.rs
index 1a62a2a4a4..1d1f11c7b0 100644
--- a/datafusion/datasource/src/memory.rs
+++ b/datafusion/datasource/src/memory.rs
@@ -18,6 +18,8 @@
//! Execution plan for reading in-memory batches of data
use std::any::Any;
+use std::cmp::Ordering;
+use std::collections::BinaryHeap;
use std::fmt;
use std::fmt::Debug;
use std::sync::Arc;
@@ -46,6 +48,7 @@ use datafusion_physical_expr::expressions::Column;
use datafusion_physical_expr::utils::collect_columns;
use datafusion_physical_expr::{EquivalenceProperties, LexOrdering};
use futures::StreamExt;
+use itertools::Itertools;
use tokio::sync::RwLock;
/// Execution plan for reading in-memory batches of data
@@ -353,7 +356,9 @@ impl MemoryExec {
/// Data source configuration for reading in-memory batches of data
#[derive(Clone, Debug)]
pub struct MemorySourceConfig {
- /// The partitions to query
+ /// The partitions to query.
+ ///
+ /// Each partition is a `Vec<RecordBatch>`.
partitions: Vec<Vec<RecordBatch>>,
/// Schema representing the data before projection
schema: SchemaRef,
@@ -445,6 +450,39 @@ impl DataSource for MemorySourceConfig {
}
}
+ /// If possible, redistribute batches across partitions according to their size.
+ ///
+ /// Returns `Ok(None)` if unable to repartition. Preserve output ordering if exists.
+ /// Refer to [`DataSource::repartitioned`] for further details.
+ fn repartitioned(
+ &self,
+ target_partitions: usize,
+ _repartition_file_min_size: usize,
+ output_ordering: Option<LexOrdering>,
+ ) -> Result<Option<Arc<dyn DataSource>>> {
+ if self.partitions.is_empty() || self.partitions.len() >= target_partitions
+ // if have no partitions, or already have more partitions than desired, do not repartition
+ {
+ return Ok(None);
+ }
+
+ let maybe_repartitioned = if let Some(output_ordering) = output_ordering {
+ self.repartition_preserving_order(target_partitions, output_ordering)?
+ } else {
+ self.repartition_evenly_by_size(target_partitions)?
+ };
+
+ if let Some(repartitioned) = maybe_repartitioned {
+ Ok(Some(Arc::new(Self::try_new(
+ &repartitioned,
+ self.original_schema(),
+ self.projection.clone(),
+ )?)))
+ } else {
+ Ok(None)
+ }
+ }
+
fn output_partitioning(&self) -> Partitioning {
Partitioning::UnknownPartitioning(self.partitions.len())
}
@@ -723,6 +761,226 @@ impl MemorySourceConfig {
pub fn original_schema(&self) -> SchemaRef {
Arc::clone(&self.schema)
}
+
+ /// Repartition while preserving order.
+ ///
+ /// Returns `Ok(None)` if cannot fulfill the requested repartitioning, such
+ /// as having too few batches to fulfill the `target_partitions` or if unable
+ /// to preserve output ordering.
+ fn repartition_preserving_order(
+ &self,
+ target_partitions: usize,
+ output_ordering: LexOrdering,
+ ) -> Result<Option<Vec<Vec<RecordBatch>>>> {
+ if !self.eq_properties().ordering_satisfy(&output_ordering) {
+ Ok(None)
+ } else {
+ let total_num_batches =
+ self.partitions.iter().map(|b| b.len()).sum::<usize>();
+ if total_num_batches < target_partitions {
+ // no way to create the desired repartitioning
+ return Ok(None);
+ }
+
+ let cnt_to_repartition = target_partitions - self.partitions.len();
+
+ // Label the current partitions and their order.
+ // Such that when we later split up the partitions into smaller sizes, we are maintaining the order.
+ let to_repartition = self
+ .partitions
+ .iter()
+ .enumerate()
+ .map(|(idx, batches)| RePartition {
+ idx: idx + (cnt_to_repartition * idx), // make space in ordering for split partitions
+ row_count: batches.iter().map(|batch| batch.num_rows()).sum(),
+ batches: batches.clone(),
+ })
+ .collect_vec();
+
+ // Put all of the partitions into a heap ordered by `RePartition::partial_cmp`, which sizes
+ // by count of rows.
+ let mut max_heap = BinaryHeap::with_capacity(target_partitions);
+ for rep in to_repartition {
+ max_heap.push(rep);
+ }
+
+ // Split the largest partitions into smaller partitions. Maintaining the output
+ // order of the partitions & newly created partitions.
+ let mut cannot_split_further = Vec::with_capacity(target_partitions);
+ for _ in 0..cnt_to_repartition {
+ // triggers loop for the cnt_to_repartition. So if need another 4 partitions, it attempts to split 4 times.
+ loop {
+ // Take the largest item off the heap, and attempt to split.
+ let Some(to_split) = max_heap.pop() else {
+ // Nothing left to attempt repartition. Break inner loop.
+ break;
+ };
+
+ // Split the partition. The new partitions will be ordered with idx and idx+1.
+ let mut new_partitions = to_split.split();
+ if new_partitions.len() > 1 {
+ for new_partition in new_partitions {
+ max_heap.push(new_partition);
+ }
+ // Successful repartition. Break inner loop, and return to outer `cnt_to_repartition` loop.
+ break;
+ } else {
+ cannot_split_further.push(new_partitions.remove(0));
+ }
+ }
+ }
+ let mut partitions = max_heap.drain().collect_vec();
+ partitions.extend(cannot_split_further);
+
+ // Finally, sort all partitions by the output ordering.
+ // This was the original ordering of the batches within the partition. We are maintaining this ordering.
+ partitions.sort_by_key(|p| p.idx);
+ let partitions = partitions.into_iter().map(|rep| rep.batches).collect_vec();
+
+ Ok(Some(partitions))
+ }
+ }
+
+ /// Repartition into evenly sized chunks (as much as possible without batch splitting),
+ /// disregarding any ordering.
+ ///
+ /// Current implementation uses a first-fit-decreasing bin packing, modified to enable
+ /// us to still return the desired count of `target_partitions`.
+ ///
+ /// Returns `Ok(None)` if cannot fulfill the requested repartitioning, such
+ /// as having too few batches to fulfill the `target_partitions`.
+ fn repartition_evenly_by_size(
+ &self,
+ target_partitions: usize,
+ ) -> Result<Option<Vec<Vec<RecordBatch>>>> {
+ // determine if we have enough total batches to fulfill request
+ let mut flatten_batches =
+ self.partitions.clone().into_iter().flatten().collect_vec();
+ if flatten_batches.len() < target_partitions {
+ return Ok(None);
+ }
+
+ // Take all flattened batches (all in 1 partititon/vec) and divide evenly into the desired number of `target_partitions`.
+ let total_num_rows = flatten_batches.iter().map(|b| b.num_rows()).sum::<usize>();
+ // sort by size, so we pack multiple smaller batches into the same partition
+ flatten_batches.sort_by_key(|b| std::cmp::Reverse(b.num_rows()));
+
+ // Divide.
+ let mut partitions =
+ vec![Vec::with_capacity(flatten_batches.len()); target_partitions];
+ let mut target_partition_size = total_num_rows.div_ceil(target_partitions);
+ let mut total_rows_seen = 0;
+ let mut curr_bin_row_count = 0;
+ let mut idx = 0;
+ for batch in flatten_batches {
+ let row_cnt = batch.num_rows();
+ idx = std::cmp::min(idx, target_partitions - 1);
+
+ partitions[idx].push(batch);
+ curr_bin_row_count += row_cnt;
+ total_rows_seen += row_cnt;
+
+ if curr_bin_row_count >= target_partition_size {
+ idx += 1;
+ curr_bin_row_count = 0;
+
+ // update target_partition_size, to handle very lopsided batch distributions
+ // while still returning the count of `target_partitions`
+ if total_rows_seen < total_num_rows {
+ target_partition_size = (total_num_rows - total_rows_seen)
+ .div_ceil(target_partitions - idx);
+ }
+ }
+ }
+
+ Ok(Some(partitions))
+ }
+}
+
+/// For use in repartitioning, track the total size and original partition index.
+///
+/// Do not implement clone, in order to avoid unnecessary copying during repartitioning.
+struct RePartition {
+ /// Original output ordering for the partition.
+ idx: usize,
+ /// Total size of the partition, for use in heap ordering
+ /// (a.k.a. splitting up the largest partitions).
+ row_count: usize,
+ /// A partition containing record batches.
+ batches: Vec<RecordBatch>,
+}
+
+impl RePartition {
+ /// Split [`RePartition`] into 2 pieces, consuming self.
+ ///
+ /// Returns only 1 partition if cannot be split further.
+ fn split(self) -> Vec<Self> {
+ if self.batches.len() == 1 {
+ return vec![self];
+ }
+
+ let new_0 = RePartition {
+ idx: self.idx, // output ordering
+ row_count: 0,
+ batches: vec![],
+ };
+ let new_1 = RePartition {
+ idx: self.idx + 1, // output ordering +1
+ row_count: 0,
+ batches: vec![],
+ };
+ let split_pt = self.row_count / 2;
+
+ let [new_0, new_1] = self.batches.into_iter().fold(
+ [new_0, new_1],
+ |[mut new0, mut new1], batch| {
+ if new0.row_count < split_pt {
+ new0.add_batch(batch);
+ } else {
+ new1.add_batch(batch);
+ }
+ [new0, new1]
+ },
+ );
+ vec![new_0, new_1]
+ }
+
+ fn add_batch(&mut self, batch: RecordBatch) {
+ self.row_count += batch.num_rows();
+ self.batches.push(batch);
+ }
+}
+
+impl PartialOrd for RePartition {
+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+ Some(self.row_count.cmp(&other.row_count))
+ }
+}
+
+impl Ord for RePartition {
+ fn cmp(&self, other: &Self) -> Ordering {
+ self.row_count.cmp(&other.row_count)
+ }
+}
+
+impl PartialEq for RePartition {
+ fn eq(&self, other: &Self) -> bool {
+ self.row_count.eq(&other.row_count)
+ }
+}
+
+impl Eq for RePartition {}
+
+impl fmt::Display for RePartition {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(
+ f,
+ "{}rows-in-{}batches@{}",
+ self.row_count,
+ self.batches.len(),
+ self.idx
+ )
+ }
}
/// Type alias for partition data
@@ -868,10 +1126,14 @@ mod memory_source_tests {
#[cfg(test)]
mod tests {
+ use crate::test_util::col;
use crate::tests::{aggr_test_schema, make_partition};
use super::*;
+ use arrow::array::{ArrayRef, Int32Array, Int64Array, StringArray};
+ use arrow::compute::SortOptions;
+ use datafusion_physical_expr::PhysicalSortExpr;
use datafusion_physical_plan::expressions::lit;
use arrow::datatypes::{DataType, Field};
@@ -992,4 +1254,467 @@ mod tests {
Ok(())
}
+
+ fn batch(row_size: usize) -> RecordBatch {
+ let a: ArrayRef = Arc::new(Int32Array::from(vec![1; row_size]));
+ let b: ArrayRef = Arc::new(StringArray::from_iter(vec![Some("foo"); row_size]));
+ let c: ArrayRef = Arc::new(Int64Array::from_iter(vec![1; row_size]));
+ RecordBatch::try_from_iter(vec![("a", a), ("b", b), ("c", c)]).unwrap()
+ }
+
+ fn schema() -> SchemaRef {
+ batch(1).schema()
+ }
+
+ fn memorysrcconfig_no_partitions(
+ sort_information: Vec<LexOrdering>,
+ ) -> Result<MemorySourceConfig> {
+ let partitions = vec![];
+ MemorySourceConfig::try_new(&partitions, schema(), None)?
+ .try_with_sort_information(sort_information)
+ }
+
+ fn memorysrcconfig_1_partition_1_batch(
+ sort_information: Vec<LexOrdering>,
+ ) -> Result<MemorySourceConfig> {
+ let partitions = vec![vec![batch(100)]];
+ MemorySourceConfig::try_new(&partitions, schema(), None)?
+ .try_with_sort_information(sort_information)
+ }
+
+ fn memorysrcconfig_3_partitions_1_batch_each(
+ sort_information: Vec<LexOrdering>,
+ ) -> Result<MemorySourceConfig> {
+ let partitions = vec![vec![batch(100)], vec![batch(100)], vec![batch(100)]];
+ MemorySourceConfig::try_new(&partitions, schema(), None)?
+ .try_with_sort_information(sort_information)
+ }
+
+ fn memorysrcconfig_3_partitions_with_2_batches_each(
+ sort_information: Vec<LexOrdering>,
+ ) -> Result<MemorySourceConfig> {
+ let partitions = vec![
+ vec![batch(100), batch(100)],
+ vec![batch(100), batch(100)],
+ vec![batch(100), batch(100)],
+ ];
+ MemorySourceConfig::try_new(&partitions, schema(), None)?
+ .try_with_sort_information(sort_information)
+ }
+
+ /// Batches of different sizes, with batches ordered by size (100_000, 10_000, 100, 1)
+ /// in the Memtable partition (a.k.a. vector of batches).
+ fn memorysrcconfig_1_partition_with_different_sized_batches(
+ sort_information: Vec<LexOrdering>,
+ ) -> Result<MemorySourceConfig> {
+ let partitions = vec![vec![batch(100_000), batch(10_000), batch(100), batch(1)]];
+ MemorySourceConfig::try_new(&partitions, schema(), None)?
+ .try_with_sort_information(sort_information)
+ }
+
+ /// Same as [`memorysrcconfig_1_partition_with_different_sized_batches`],
+ /// but the batches are ordered differently (not by size)
+ /// in the Memtable partition (a.k.a. vector of batches).
+ fn memorysrcconfig_1_partition_with_ordering_not_matching_size(
+ sort_information: Vec<LexOrdering>,
+ ) -> Result<MemorySourceConfig> {
+ let partitions = vec![vec![batch(100_000), batch(1), batch(100), batch(10_000)]];
+ MemorySourceConfig::try_new(&partitions, schema(), None)?
+ .try_with_sort_information(sort_information)
+ }
+
+ fn memorysrcconfig_2_partition_with_different_sized_batches(
+ sort_information: Vec<LexOrdering>,
+ ) -> Result<MemorySourceConfig> {
+ let partitions = vec![
+ vec![batch(100_000), batch(10_000), batch(1_000)],
+ vec![batch(2_000), batch(20)],
+ ];
+ MemorySourceConfig::try_new(&partitions, schema(), None)?
+ .try_with_sort_information(sort_information)
+ }
+
+ fn memorysrcconfig_2_partition_with_extreme_sized_batches(
+ sort_information: Vec<LexOrdering>,
+ ) -> Result<MemorySourceConfig> {
+ let partitions = vec![
+ vec![
+ batch(100_000),
+ batch(1),
+ batch(1),
+ batch(1),
+ batch(1),
+ batch(0),
+ ],
+ vec![batch(1), batch(1), batch(1), batch(1), batch(0), batch(100)],
+ ];
+ MemorySourceConfig::try_new(&partitions, schema(), None)?
+ .try_with_sort_information(sort_information)
+ }
+
+ /// Assert that we get the expected count of partitions after repartitioning.
+ ///
+ /// If None, then we expected the [`DataSource::repartitioned`] to return None.
+ fn assert_partitioning(
+ partitioned_datasrc: Option<Arc<dyn DataSource>>,
+ partition_cnt: Option<usize>,
+ ) {
+ let should_exist = if let Some(partition_cnt) = partition_cnt {
+ format!(
+ "new datasource should exist and have {:?} partitions",
+ partition_cnt
+ )
+ } else {
+ "new datasource should not exist".into()
+ };
+
+ let actual = partitioned_datasrc
+ .map(|datasrc| datasrc.output_partitioning().partition_count());
+ assert_eq!(
+ actual,
+ partition_cnt,
+ "partitioned datasrc does not match expected, we expected {}, instead found {:?}",
+ should_exist,
+ actual
+ );
+ }
+
+ fn run_all_test_scenarios(
+ output_ordering: Option<LexOrdering>,
+ sort_information_on_config: Vec<LexOrdering>,
+ ) -> Result<()> {
+ let not_used = usize::MAX;
+
+ // src has no partitions
+ let mem_src_config =
+ memorysrcconfig_no_partitions(sort_information_on_config.clone())?;
+ let partitioned_datasrc =
+ mem_src_config.repartitioned(1, not_used, output_ordering.clone())?;
+ assert_partitioning(partitioned_datasrc, None);
+
+ // src has partitions == target partitions (=1)
+ let target_partitions = 1;
+ let mem_src_config =
+ memorysrcconfig_1_partition_1_batch(sort_information_on_config.clone())?;
+ let partitioned_datasrc = mem_src_config.repartitioned(
+ target_partitions,
+ not_used,
+ output_ordering.clone(),
+ )?;
+ assert_partitioning(partitioned_datasrc, None);
+
+ // src has partitions == target partitions (=3)
+ let target_partitions = 3;
+ let mem_src_config = memorysrcconfig_3_partitions_1_batch_each(
+ sort_information_on_config.clone(),
+ )?;
+ let partitioned_datasrc = mem_src_config.repartitioned(
+ target_partitions,
+ not_used,
+ output_ordering.clone(),
+ )?;
+ assert_partitioning(partitioned_datasrc, None);
+
+ // src has partitions > target partitions, but we don't merge them
+ let target_partitions = 2;
+ let mem_src_config = memorysrcconfig_3_partitions_1_batch_each(
+ sort_information_on_config.clone(),
+ )?;
+ let partitioned_datasrc = mem_src_config.repartitioned(
+ target_partitions,
+ not_used,
+ output_ordering.clone(),
+ )?;
+ assert_partitioning(partitioned_datasrc, None);
+
+ // src has partitions < target partitions, but not enough batches (per partition) to split into more partitions
+ let target_partitions = 4;
+ let mem_src_config = memorysrcconfig_3_partitions_1_batch_each(
+ sort_information_on_config.clone(),
+ )?;
+ let partitioned_datasrc = mem_src_config.repartitioned(
+ target_partitions,
+ not_used,
+ output_ordering.clone(),
+ )?;
+ assert_partitioning(partitioned_datasrc, None);
+
+ // src has partitions < target partitions, and can split to sufficient amount
+ // has 6 batches across 3 partitions. Will need to split 2 of it's partitions.
+ let target_partitions = 5;
+ let mem_src_config = memorysrcconfig_3_partitions_with_2_batches_each(
+ sort_information_on_config.clone(),
+ )?;
+ let partitioned_datasrc = mem_src_config.repartitioned(
+ target_partitions,
+ not_used,
+ output_ordering.clone(),
+ )?;
+ assert_partitioning(partitioned_datasrc, Some(5));
+
+ // src has partitions < target partitions, and can split to sufficient amount
+ // has 6 batches across 3 partitions. Will need to split all of it's partitions.
+ let target_partitions = 6;
+ let mem_src_config = memorysrcconfig_3_partitions_with_2_batches_each(
+ sort_information_on_config.clone(),
+ )?;
+ let partitioned_datasrc = mem_src_config.repartitioned(
+ target_partitions,
+ not_used,
+ output_ordering.clone(),
+ )?;
+ assert_partitioning(partitioned_datasrc, Some(6));
+
+ // src has partitions < target partitions, but not enough total batches to fulfill the split (desired target_partitions)
+ let target_partitions = 3 * 2 + 1;
+ let mem_src_config = memorysrcconfig_3_partitions_with_2_batches_each(
+ sort_information_on_config.clone(),
+ )?;
+ let partitioned_datasrc = mem_src_config.repartitioned(
+ target_partitions,
+ not_used,
+ output_ordering.clone(),
+ )?;
+ assert_partitioning(partitioned_datasrc, None);
+
+ // src has 1 partition with many batches of lopsided sizes
+ // make sure it handles the split properly
+ let target_partitions = 2;
+ let mem_src_config = memorysrcconfig_1_partition_with_different_sized_batches(
+ sort_information_on_config,
+ )?;
+ let partitioned_datasrc = mem_src_config.clone().repartitioned(
+ target_partitions,
+ not_used,
+ output_ordering,
+ )?;
+ assert_partitioning(partitioned_datasrc.clone(), Some(2));
+ // Starting = batch(100_000), batch(10_000), batch(100), batch(1).
+ // It should have split as p1=batch(100_000), p2=[batch(10_000), batch(100), batch(1)]
+ let partitioned_datasrc = partitioned_datasrc.unwrap();
+ let Some(mem_src_config) = partitioned_datasrc
+ .as_any()
+ .downcast_ref::<MemorySourceConfig>()
+ else {
+ unreachable!()
+ };
+ let repartitioned_raw_batches = mem_src_config.partitions.clone();
+ assert_eq!(repartitioned_raw_batches.len(), 2);
+ let [ref p1, ref p2] = repartitioned_raw_batches[..] else {
+ unreachable!()
+ };
+ // p1=batch(100_000)
+ assert_eq!(p1.len(), 1);
+ assert_eq!(p1[0].num_rows(), 100_000);
+ // p2=[batch(10_000), batch(100), batch(1)]
+ assert_eq!(p2.len(), 3);
+ assert_eq!(p2[0].num_rows(), 10_000);
+ assert_eq!(p2[1].num_rows(), 100);
+ assert_eq!(p2[2].num_rows(), 1);
+
+ Ok(())
+ }
+
+ #[test]
+ fn test_repartition_no_sort_information_no_output_ordering() -> Result<()> {
+ let no_sort = vec![];
+ let no_output_ordering = None;
+
+ // Test: common set of functionality
+ run_all_test_scenarios(no_output_ordering.clone(), no_sort.clone())?;
+
+ // Test: how no-sort-order divides differently.
+ // * does not preserve separate partitions (with own internal ordering) on even split,
+ // * nor does it preserve ordering (re-orders batch(2_000) vs batch(1_000)).
+ let target_partitions = 3;
+ let mem_src_config =
+ memorysrcconfig_2_partition_with_different_sized_batches(no_sort)?;
+ let partitioned_datasrc = mem_src_config.clone().repartitioned(
+ target_partitions,
+ usize::MAX,
+ no_output_ordering,
+ )?;
+ assert_partitioning(partitioned_datasrc.clone(), Some(3));
+ // Starting = batch(100_000), batch(10_000), batch(1_000), batch(2_000), batch(20)
+ // It should have split as p1=batch(100_000), p2=batch(10_000), p3=rest(mixed across original partitions)
+ let repartitioned_raw_batches = mem_src_config
+ .repartition_evenly_by_size(target_partitions)?
+ .unwrap();
+ assert_eq!(repartitioned_raw_batches.len(), 3);
+ let [ref p1, ref p2, ref p3] = repartitioned_raw_batches[..] else {
+ unreachable!()
+ };
+ // p1=batch(100_000)
+ assert_eq!(p1.len(), 1);
+ assert_eq!(p1[0].num_rows(), 100_000);
+ // p2=batch(10_000)
+ assert_eq!(p2.len(), 1);
+ assert_eq!(p2[0].num_rows(), 10_000);
+ // p3= batch(2_000), batch(1_000), batch(20)
+ assert_eq!(p3.len(), 3);
+ assert_eq!(p3[0].num_rows(), 2_000);
+ assert_eq!(p3[1].num_rows(), 1_000);
+ assert_eq!(p3[2].num_rows(), 20);
+
+ Ok(())
+ }
+
+ #[test]
+ fn test_repartition_no_sort_information_no_output_ordering_lopsized_batches(
+ ) -> Result<()> {
+ let no_sort = vec![];
+ let no_output_ordering = None;
+
+ // Test: case has two input partitions:
+ // b(100_000), b(1), b(1), b(1), b(1), b(0)
+ // b(1), b(1), b(1), b(1), b(0), b(100)
+ //
+ // We want an output with target_partitions=5, which means the ideal division is:
+ // b(100_000)
+ // b(100)
+ // b(1), b(1), b(1)
+ // b(1), b(1), b(1)
+ // b(1), b(1), b(0)
+ let target_partitions = 5;
+ let mem_src_config =
+ memorysrcconfig_2_partition_with_extreme_sized_batches(no_sort)?;
+ let partitioned_datasrc = mem_src_config.clone().repartitioned(
+ target_partitions,
+ usize::MAX,
+ no_output_ordering,
+ )?;
+ assert_partitioning(partitioned_datasrc.clone(), Some(5));
+ // Starting partition 1 = batch(100_000), batch(1), batch(1), batch(1), batch(1), batch(0)
+ // Starting partition 1 = batch(1), batch(1), batch(1), batch(1), batch(0), batch(100)
+ // It should have split as p1=batch(100_000), p2=batch(100), p3=[batch(1),batch(1)], p4=[batch(1),batch(1)], p5=[batch(1),batch(1),batch(0),batch(0)]
+ let repartitioned_raw_batches = mem_src_config
+ .repartition_evenly_by_size(target_partitions)?
+ .unwrap();
+ assert_eq!(repartitioned_raw_batches.len(), 5);
+ let [ref p1, ref p2, ref p3, ref p4, ref p5] = repartitioned_raw_batches[..]
+ else {
+ unreachable!()
+ };
+ // p1=batch(100_000)
+ assert_eq!(p1.len(), 1);
+ assert_eq!(p1[0].num_rows(), 100_000);
+ // p2=batch(100)
+ assert_eq!(p2.len(), 1);
+ assert_eq!(p2[0].num_rows(), 100);
+ // p3=[batch(1),batch(1),batch(1)]
+ assert_eq!(p3.len(), 3);
+ assert_eq!(p3[0].num_rows(), 1);
+ assert_eq!(p3[1].num_rows(), 1);
+ assert_eq!(p3[2].num_rows(), 1);
+ // p4=[batch(1),batch(1),batch(1)]
+ assert_eq!(p4.len(), 3);
+ assert_eq!(p4[0].num_rows(), 1);
+ assert_eq!(p4[1].num_rows(), 1);
+ assert_eq!(p4[2].num_rows(), 1);
+ // p5=[batch(1),batch(1),batch(0),batch(0)]
+ assert_eq!(p5.len(), 4);
+ assert_eq!(p5[0].num_rows(), 1);
+ assert_eq!(p5[1].num_rows(), 1);
+ assert_eq!(p5[2].num_rows(), 0);
+ assert_eq!(p5[3].num_rows(), 0);
+
+ Ok(())
+ }
+
+ #[test]
+ fn test_repartition_with_sort_information() -> Result<()> {
+ let schema = schema();
+ let sort_key = LexOrdering::new(vec![PhysicalSortExpr {
+ expr: col("c", &schema).unwrap(),
+ options: SortOptions::default(),
+ }]);
+ let has_sort = vec![sort_key.clone()];
+ let output_ordering = Some(sort_key);
+
+ // Test: common set of functionality
+ run_all_test_scenarios(output_ordering.clone(), has_sort.clone())?;
+
+ // Test: DOES preserve separate partitions (with own internal ordering)
+ let target_partitions = 3;
+ let mem_src_config =
+ memorysrcconfig_2_partition_with_different_sized_batches(has_sort)?;
+ let partitioned_datasrc = mem_src_config.clone().repartitioned(
+ target_partitions,
+ usize::MAX,
+ output_ordering.clone(),
+ )?;
+ assert_partitioning(partitioned_datasrc.clone(), Some(3));
+ // Starting = batch(100_000), batch(10_000), batch(1_000), batch(2_000), batch(20)
+ // It should have split as p1=batch(100_000), p2=[batch(10_000),batch(1_000)], p3=<other_partition>
+ let Some(output_ord) = output_ordering else {
+ unreachable!()
+ };
+ let repartitioned_raw_batches = mem_src_config
+ .repartition_preserving_order(target_partitions, output_ord)?
+ .unwrap();
+ assert_eq!(repartitioned_raw_batches.len(), 3);
+ let [ref p1, ref p2, ref p3] = repartitioned_raw_batches[..] else {
+ unreachable!()
+ };
+ // p1=batch(100_000)
+ assert_eq!(p1.len(), 1);
+ assert_eq!(p1[0].num_rows(), 100_000);
+ // p2=[batch(10_000),batch(1_000)]
+ assert_eq!(p2.len(), 2);
+ assert_eq!(p2[0].num_rows(), 10_000);
+ assert_eq!(p2[1].num_rows(), 1_000);
+ // p3=batch(2_000), batch(20)
+ assert_eq!(p3.len(), 2);
+ assert_eq!(p3[0].num_rows(), 2_000);
+ assert_eq!(p3[1].num_rows(), 20);
+
+ Ok(())
+ }
+
+ #[test]
+ fn test_repartition_with_batch_ordering_not_matching_sizing() -> Result<()> {
+ let schema = schema();
+ let sort_key = LexOrdering::new(vec![PhysicalSortExpr {
+ expr: col("c", &schema).unwrap(),
+ options: SortOptions::default(),
+ }]);
+ let has_sort = vec![sort_key.clone()];
+ let output_ordering = Some(sort_key);
+
+ // src has 1 partition with many batches of lopsided sizes
+ // note that the input vector of batches are not ordered by decreasing size
+ let target_partitions = 2;
+ let mem_src_config =
+ memorysrcconfig_1_partition_with_ordering_not_matching_size(has_sort)?;
+ let partitioned_datasrc = mem_src_config.clone().repartitioned(
+ target_partitions,
+ usize::MAX,
+ output_ordering,
+ )?;
+ assert_partitioning(partitioned_datasrc.clone(), Some(2));
+ // Starting = batch(100_000), batch(1), batch(100), batch(10_000).
+ // It should have split as p1=batch(100_000), p2=[batch(1), batch(100), batch(10_000)]
+ let partitioned_datasrc = partitioned_datasrc.unwrap();
+ let Some(mem_src_config) = partitioned_datasrc
+ .as_any()
+ .downcast_ref::<MemorySourceConfig>()
+ else {
+ unreachable!()
+ };
+ let repartitioned_raw_batches = mem_src_config.partitions.clone();
+ assert_eq!(repartitioned_raw_batches.len(), 2);
+ let [ref p1, ref p2] = repartitioned_raw_batches[..] else {
+ unreachable!()
+ };
+ // p1=batch(100_000)
+ assert_eq!(p1.len(), 1);
+ assert_eq!(p1[0].num_rows(), 100_000);
+ // p2=[batch(1), batch(100), batch(10_000)] -- **this is preserving the partition order**
+ assert_eq!(p2.len(), 3);
+ assert_eq!(p2[0].num_rows(), 1);
+ assert_eq!(p2[1].num_rows(), 100);
+ assert_eq!(p2[2].num_rows(), 10_000);
+
+ Ok(())
+ }
}
diff --git a/datafusion/datasource/src/source.rs b/datafusion/datasource/src/source.rs
index cf42347e3a..1afe3b3edb 100644
--- a/datafusion/datasource/src/source.rs
+++ b/datafusion/datasource/src/source.rs
@@ -70,7 +70,16 @@ pub trait DataSource: Send + Sync + Debug {
/// Format this source for display in explain plans
fn fmt_as(&self, t: DisplayFormatType, f: &mut Formatter) -> fmt::Result;
- /// Return a copy of this DataSource with a new partitioning scheme
+ /// Return a copy of this DataSource with a new partitioning scheme.
+ ///
+ /// Returns `Ok(None)` (the default) if the partitioning cannot be changed.
+ /// Refer to [`ExecutionPlan::repartitioned`] for details on when None should be returned.
+ ///
+ /// Repartitioning should not change the output ordering, if this ordering exists.
+ /// Refer to [`MemorySourceConfig::repartition_preserving_order`](crate::memory::MemorySourceConfig)
+ /// and the FileSource's
+ /// [`FileGroupPartitioner::repartition_file_groups`](crate::file_groups::FileGroupPartitioner::repartition_file_groups)
+ /// for examples.
fn repartitioned(
&self,
_target_partitions: usize,
@@ -162,6 +171,10 @@ impl ExecutionPlan for DataSourceExec {
Ok(self)
}
+ /// Implementation of [`ExecutionPlan::repartitioned`] which relies upon the inner [`DataSource::repartitioned`].
+ ///
+ /// If the data source does not support changing its partitioning, returns `Ok(None)` (the default). Refer
+ /// to [`ExecutionPlan::repartitioned`] for more details.
fn repartitioned(
&self,
target_partitions: usize,
diff --git a/datafusion/datasource/src/test_util.rs b/datafusion/datasource/src/test_util.rs
index 9a9b98d504..e75c7c3a3d 100644
--- a/datafusion/datasource/src/test_util.rs
+++ b/datafusion/datasource/src/test_util.rs
@@ -21,8 +21,9 @@ use crate::{
use std::sync::Arc;
-use arrow::datatypes::SchemaRef;
+use arrow::datatypes::{Schema, SchemaRef};
use datafusion_common::{Result, Statistics};
+use datafusion_physical_expr::{expressions::Column, PhysicalExpr};
use datafusion_physical_plan::metrics::ExecutionPlanMetricsSet;
use object_store::ObjectStore;
@@ -81,3 +82,8 @@ impl FileSource for MockSource {
"mock"
}
}
+
+/// Create a column expression
+pub(crate) fn col(name: &str, schema: &Schema) -> Result<Arc<dyn PhysicalExpr>> {
+ Ok(Arc::new(Column::new_with_schema(name, schema)?))
+}
diff --git a/datafusion/physical-optimizer/src/enforce_distribution.rs b/datafusion/physical-optimizer/src/enforce_distribution.rs
index 85669e90e0..700b00c19d 100644
--- a/datafusion/physical-optimizer/src/enforce_distribution.rs
+++ b/datafusion/physical-optimizer/src/enforce_distribution.rs
@@ -1153,6 +1153,10 @@ fn get_repartition_requirement_status(
/// operators to satisfy distribution requirements. Since this function
/// takes care of such requirements, we should avoid manually adding data
/// exchange operators in other places.
+///
+/// This function is intended to be used in a bottom up traversal, as it
+/// can first repartition (or newly partition) at the datasources -- these
+/// source partitions may be later repartitioned with additional data exchange operators.
pub fn ensure_distribution(
dist_context: DistributionContext,
config: &ConfigOptions,
@@ -1242,6 +1246,10 @@ pub fn ensure_distribution(
// When `repartition_file_scans` is set, attempt to increase
// parallelism at the source.
+ //
+ // If repartitioning is not possible (a.k.a. None is returned from `ExecutionPlan::repartitioned`)
+ // then no repartitioning will have occurred. As the default implementation returns None, it is only
+ // specific physical plan nodes, such as certain datasources, which are repartitioned.
if repartition_file_scans && roundrobin_beneficial_stats {
if let Some(new_child) =
child.plan.repartitioned(target_partitions, config)?
diff --git a/datafusion/sqllogictest/test_files/information_schema.slt b/datafusion/sqllogictest/test_files/information_schema.slt
index f0218540ac..3a98a4d185 100644
--- a/datafusion/sqllogictest/test_files/information_schema.slt
+++ b/datafusion/sqllogictest/test_files/information_schema.slt
@@ -407,7 +407,7 @@ datafusion.optimizer.prefer_existing_union false When set to true, the optimizer
datafusion.optimizer.prefer_hash_join true When set to true, the physical plan optimizer will prefer HashJoin over SortMergeJoin. HashJoin can work more efficiently than SortMergeJoin but consumes more memory
datafusion.optimizer.repartition_aggregations true Should DataFusion repartition data using the aggregate keys to execute aggregates in parallel using the provided `target_partitions` level
datafusion.optimizer.repartition_file_min_size 10485760 Minimum total files size in bytes to perform file scan repartitioning.
-datafusion.optimizer.repartition_file_scans true When set to `true`, file groups will be repartitioned to achieve maximum parallelism. Currently Parquet and CSV formats are supported. If set to `true`, all files will be repartitioned evenly (i.e., a single large file might be partitioned into smaller chunks) for parallel scanning. If set to `false`, different files will be read in parallel, but repartitioning won't happen within a single file.
+datafusion.optimizer.repartition_file_scans true When set to `true`, datasource partitions will be repartitioned to achieve maximum parallelism. This applies to both in-memory partitions and FileSource's file groups (1 group is 1 partition). For FileSources, only Parquet and CSV formats are currently supported. If set to `true` for a FileSource, all files will be repartitioned evenly (i.e., a single large file might be partitioned into smaller chunks) for parallel scanning. If set to `false` for a FileSource, different files will be read in parallel, but repartitioning won't happen within a single file. If set to `true` for an in-memory source, all memtable's partitions will have their batches repartitioned evenly to the desired number of `target_partitions`. Repartitioning can change the total number of partitions and batches per partition, but does not slice the initial record tables provided to the MemTable on creation.
datafusion.optimizer.repartition_joins true Should DataFusion repartition data using the join keys to execute joins in parallel using the provided `target_partitions` level
datafusion.optimizer.repartition_sorts true Should DataFusion execute sorts in a per-partition fashion and merge afterwards instead of coalescing first and sorting globally. With this flag is enabled, plans in the form below ```text "SortExec: [a@0 ASC]", " CoalescePartitionsExec", " RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1", ``` would turn into the plan below which performs better in multithreaded environments ```text "SortPreservingMergeExec: [a@0 ASC]", " SortExec: [a@0 ASC]", " RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1", ```
datafusion.optimizer.repartition_windows true Should DataFusion repartition data using the partitions keys to execute window functions in parallel using the provided `target_partitions` level
diff --git a/docs/source/user-guide/configs.md b/docs/source/user-guide/configs.md
index 0e75903219..fe9c57857b 100644
--- a/docs/source/user-guide/configs.md
+++ b/docs/source/user-guide/configs.md
@@ -35,110 +35,110 @@ Values are parsed according to the [same rules used in casts from Utf8](https://
If the value in the environment variable cannot be cast to the type of the configuration option, the default value will be used instead and a warning emitted.
Environment variables are read during `SessionConfig` initialisation so they must be set beforehand and will not affect running sessions.
-| key | default | description |
-| ----------------------------------------------------------------------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| datafusion.catalog.create_default_catalog_and_schema | true | Whether the default catalog and schema should be created automatically. |
-| datafusion.catalog.default_catalog | datafusion | The default catalog name - this impacts what SQL queries use if not specified |
-| datafusion.catalog.default_schema | public | The default schema name - this impacts what SQL queries use if not specified |
-| datafusion.catalog.information_schema | false | Should DataFusion provide access to `information_schema` virtual tables for displaying schema information |
-| datafusion.catalog.location | NULL | Location scanned to load tables for `default` schema |
-| datafusion.catalog.format | NULL | Type of `TableProvider` to use when loading `default` schema |
-| datafusion.catalog.has_header | true | Default value for `format.has_header` for `CREATE EXTERNAL TABLE` if not specified explicitly in the statement. |
-| datafusion.catalog.newlines_in_values | false | Specifies whether newlines in (quoted) CSV values are supported. This is the default value for `format.newlines_in_values` for `CREATE EXTERNAL TABLE` if not specified explicitly in the statement. Parsing newlines in quoted values may be affected by execution behaviour such as parallel file scanning. Setting this to `true` ensures that newlines in values are parsed successfully, which may reduce performance. |
-| datafusion.execution.batch_size | 8192 | Default batch size while creating new batches, it's especially useful for buffer-in-memory batches since creating tiny batches would result in too much metadata memory consumption |
-| datafusion.execution.coalesce_batches | true | When set to true, record batches will be examined between each operator and small batches will be coalesced into larger batches. This is helpful when there are highly selective filters or joins that could produce tiny output batches. The target batch size is determined by the configuration setting |
-| datafusion.execution.collect_statistics | false | Should DataFusion collect statistics after listing files |
-| datafusion.execution.target_partitions | 0 | Number of partitions for query execution. Increasing partitions can increase concurrency. Defaults to the number of CPU cores on the system |
-| datafusion.execution.time_zone | +00:00 | The default time zone Some functions, e.g. `EXTRACT(HOUR from SOME_TIME)`, shift the underlying datetime according to this time zone, and then extract the hour |
-| datafusion.execution.parquet.enable_page_index | true | (reading) If true, reads the Parquet data page level metadata (the Page Index), if present, to reduce the I/O and number of rows decoded. |
-| datafusion.execution.parquet.pruning | true | (reading) If true, the parquet reader attempts to skip entire row groups based on the predicate in the query and the metadata (min/max values) stored in the parquet file |
-| datafusion.execution.parquet.skip_metadata | true | (reading) If true, the parquet reader skip the optional embedded metadata that may be in the file Schema. This setting can help avoid schema conflicts when querying multiple parquet files with schemas containing compatible types but different metadata |
-| datafusion.execution.parquet.metadata_size_hint | NULL | (reading) If specified, the parquet reader will try and fetch the last `size_hint` bytes of the parquet file optimistically. If not specified, two reads are required: One read to fetch the 8-byte parquet footer and another to fetch the metadata length encoded in the footer |
-| datafusion.execution.parquet.pushdown_filters | false | (reading) If true, filter expressions are be applied during the parquet decoding operation to reduce the number of rows decoded. This optimization is sometimes called "late materialization". |
-| datafusion.execution.parquet.reorder_filters | false | (reading) If true, filter expressions evaluated during the parquet decoding operation will be reordered heuristically to minimize the cost of evaluation. If false, the filters are applied in the same order as written in the query |
-| datafusion.execution.parquet.schema_force_view_types | true | (reading) If true, parquet reader will read columns of `Utf8/Utf8Large` with `Utf8View`, and `Binary/BinaryLarge` with `BinaryView`. |
-| datafusion.execution.parquet.binary_as_string | false | (reading) If true, parquet reader will read columns of `Binary/LargeBinary` with `Utf8`, and `BinaryView` with `Utf8View`. Parquet files generated by some legacy writers do not correctly set the UTF8 flag for strings, causing string columns to be loaded as BLOB instead. |
-| datafusion.execution.parquet.coerce_int96 | NULL | (reading) If true, parquet reader will read columns of physical type int96 as originating from a different resolution than nanosecond. This is useful for reading data from systems like Spark which stores microsecond resolution timestamps in an int96 allowing it to write values with a larger date range than 64-bit timestamps with nanosecond resolution. |
-| datafusion.execution.parquet.bloom_filter_on_read | true | (reading) Use any available bloom filters when reading parquet files |
-| datafusion.execution.parquet.data_pagesize_limit | 1048576 | (writing) Sets best effort maximum size of data page in bytes |
-| datafusion.execution.parquet.write_batch_size | 1024 | (writing) Sets write_batch_size in bytes |
-| datafusion.execution.parquet.writer_version | 1.0 | (writing) Sets parquet writer version valid values are "1.0" and "2.0" |
-| datafusion.execution.parquet.skip_arrow_metadata | false | (writing) Skip encoding the embedded arrow metadata in the KV_meta This is analogous to the `ArrowWriterOptions::with_skip_arrow_metadata`. Refer to <https://docs.rs/parquet/53.3.0/parquet/arrow/arrow_writer/struct.ArrowWriterOptions.html#method.with_skip_arrow_metadata> |
-| datafusion.execution.parquet.compression | zstd(3) | (writing) Sets default parquet compression codec. Valid values are: uncompressed, snappy, gzip(level), lzo, brotli(level), lz4, zstd(level), and lz4_raw. These values are not case sensitive. If NULL, uses default parquet writer setting Note that this default setting is not the same as the default parquet writer setting. |
-| datafusion.execution.parquet.dictionary_enabled | true | (writing) Sets if dictionary encoding is enabled. If NULL, uses default parquet writer setting |
-| datafusion.execution.parquet.dictionary_page_size_limit | 1048576 | (writing) Sets best effort maximum dictionary page size, in bytes |
-| datafusion.execution.parquet.statistics_enabled | page | (writing) Sets if statistics are enabled for any column Valid values are: "none", "chunk", and "page" These values are not case sensitive. If NULL, uses default parquet writer setting |
-| datafusion.execution.parquet.max_statistics_size | 4096 | (writing) Sets max statistics size for any column. If NULL, uses default parquet writer setting max_statistics_size is deprecated, currently it is not being used |
-| datafusion.execution.parquet.max_row_group_size | 1048576 | (writing) Target maximum number of rows in each row group (defaults to 1M rows). Writing larger row groups requires more memory to write, but can get better compression and be faster to read. |
-| datafusion.execution.parquet.created_by | datafusion version 47.0.0 | (writing) Sets "created by" property |
-| datafusion.execution.parquet.column_index_truncate_length | 64 | (writing) Sets column index truncate length |
-| datafusion.execution.parquet.statistics_truncate_length | NULL | (writing) Sets statictics truncate length. If NULL, uses default parquet writer setting |
-| datafusion.execution.parquet.data_page_row_count_limit | 20000 | (writing) Sets best effort maximum number of rows in data page |
-| datafusion.execution.parquet.encoding | NULL | (writing) Sets default encoding for any column. Valid values are: plain, plain_dictionary, rle, bit_packed, delta_binary_packed, delta_length_byte_array, delta_byte_array, rle_dictionary, and byte_stream_split. These values are not case sensitive. If NULL, uses default parquet writer setting |
-| datafusion.execution.parquet.bloom_filter_on_write | false | (writing) Write bloom filters for all columns when creating parquet files |
-| datafusion.execution.parquet.bloom_filter_fpp | NULL | (writing) Sets bloom filter false positive probability. If NULL, uses default parquet writer setting |
-| datafusion.execution.parquet.bloom_filter_ndv | NULL | (writing) Sets bloom filter number of distinct values. If NULL, uses default parquet writer setting |
-| datafusion.execution.parquet.allow_single_file_parallelism | true | (writing) Controls whether DataFusion will attempt to speed up writing parquet files by serializing them in parallel. Each column in each row group in each output file are serialized in parallel leveraging a maximum possible core count of n_files*n_row_groups*n_columns. |
-| datafusion.execution.parquet.maximum_parallel_row_group_writers | 1 | (writing) By default parallel parquet writer is tuned for minimum memory usage in a streaming execution plan. You may see a performance benefit when writing large parquet files by increasing maximum_parallel_row_group_writers and maximum_buffered_record_batches_per_stream if your system has idle cores and can tolerate additional memory usage. Boosting these values is likely worthwhile when writing out already in-memory data, such as from a cached data frame. |
-| datafusion.execution.parquet.maximum_buffered_record_batches_per_stream | 2 | (writing) By default parallel parquet writer is tuned for minimum memory usage in a streaming execution plan. You may see a performance benefit when writing large parquet files by increasing maximum_parallel_row_group_writers and maximum_buffered_record_batches_per_stream if your system has idle cores and can tolerate additional memory usage. Boosting these values is likely worthwhile when writing out already in-memory data, such as from a cached data frame. |
-| datafusion.execution.planning_concurrency | 0 | Fan-out during initial physical planning. This is mostly use to plan `UNION` children in parallel. Defaults to the number of CPU cores on the system |
-| datafusion.execution.skip_physical_aggregate_schema_check | false | When set to true, skips verifying that the schema produced by planning the input of `LogicalPlan::Aggregate` exactly matches the schema of the input plan. When set to false, if the schema does not match exactly (including nullability and metadata), a planning error will be raised. This is used to workaround bugs in the planner that are now caught by the new schema verification step. |
-| datafusion.execution.sort_spill_reservation_bytes | 10485760 | Specifies the reserved memory for each spillable sort operation to facilitate an in-memory merge. When a sort operation spills to disk, the in-memory data must be sorted and merged before being written to a file. This setting reserves a specific amount of memory for that in-memory sort/merge process. Note: This setting is irrelevant if the sort operation cannot spill (i.e., if there's no `DiskManager` configured). |
-| datafusion.execution.sort_in_place_threshold_bytes | 1048576 | When sorting, below what size should data be concatenated and sorted in a single RecordBatch rather than sorted in batches and merged. |
-| datafusion.execution.meta_fetch_concurrency | 32 | Number of files to read in parallel when inferring schema and statistics |
-| datafusion.execution.minimum_parallel_output_files | 4 | Guarantees a minimum level of output files running in parallel. RecordBatches will be distributed in round robin fashion to each parallel writer. Each writer is closed and a new file opened once soft_max_rows_per_output_file is reached. |
-| datafusion.execution.soft_max_rows_per_output_file | 50000000 | Target number of rows in output files when writing multiple. This is a soft max, so it can be exceeded slightly. There also will be one file smaller than the limit if the total number of rows written is not roughly divisible by the soft max |
-| datafusion.execution.max_buffered_batches_per_output_file | 2 | This is the maximum number of RecordBatches buffered for each output file being worked. Higher values can potentially give faster write performance at the cost of higher peak memory consumption |
-| datafusion.execution.listing_table_ignore_subdirectory | true | Should sub directories be ignored when scanning directories for data files. Defaults to true (ignores subdirectories), consistent with Hive. Note that this setting does not affect reading partitioned tables (e.g. `/table/year=2021/month=01/data.parquet`). |
-| datafusion.execution.enable_recursive_ctes | true | Should DataFusion support recursive CTEs |
-| datafusion.execution.split_file_groups_by_statistics | false | Attempt to eliminate sorts by packing & sorting files with non-overlapping statistics into the same file groups. Currently experimental |
-| datafusion.execution.keep_partition_by_columns | false | Should DataFusion keep the columns used for partition_by in the output RecordBatches |
-| datafusion.execution.skip_partial_aggregation_probe_ratio_threshold | 0.8 | Aggregation ratio (number of distinct groups / number of input rows) threshold for skipping partial aggregation. If the value is greater then partial aggregation will skip aggregation for further input |
-| datafusion.execution.skip_partial_aggregation_probe_rows_threshold | 100000 | Number of input rows partial aggregation partition should process, before aggregation ratio check and trying to switch to skipping aggregation mode |
-| datafusion.execution.use_row_number_estimates_to_optimize_partitioning | false | Should DataFusion use row number estimates at the input to decide whether increasing parallelism is beneficial or not. By default, only exact row numbers (not estimates) are used for this decision. Setting this flag to `true` will likely produce better plans. if the source of statistics is accurate. We plan to make this the default in the future. |
-| datafusion.execution.enforce_batch_size_in_joins | false | Should DataFusion enforce batch size in joins or not. By default, DataFusion will not enforce batch size in joins. Enforcing batch size in joins can reduce memory usage when joining large tables with a highly-selective join filter, but is also slightly slower. |
-| datafusion.execution.objectstore_writer_buffer_size | 10485760 | Size (bytes) of data buffer DataFusion uses when writing output files. This affects the size of the data chunks that are uploaded to remote object stores (e.g. AWS S3). If very large (>= 100 GiB) output files are being written, it may be necessary to increase this size to avoid errors from the remote end point. |
-| datafusion.optimizer.enable_distinct_aggregation_soft_limit | true | When set to true, the optimizer will push a limit operation into grouped aggregations which have no aggregate expressions, as a soft limit, emitting groups once the limit is reached, before all rows in the group are read. |
-| datafusion.optimizer.enable_round_robin_repartition | true | When set to true, the physical plan optimizer will try to add round robin repartitioning to increase parallelism to leverage more CPU cores |
-| datafusion.optimizer.enable_topk_aggregation | true | When set to true, the optimizer will attempt to perform limit operations during aggregations, if possible |
-| datafusion.optimizer.filter_null_join_keys | false | When set to true, the optimizer will insert filters before a join between a nullable and non-nullable column to filter out nulls on the nullable side. This filter can add additional overhead when the file format does not fully support predicate push down. |
-| datafusion.optimizer.repartition_aggregations | true | Should DataFusion repartition data using the aggregate keys to execute aggregates in parallel using the provided `target_partitions` level |
-| datafusion.optimizer.repartition_file_min_size | 10485760 | Minimum total files size in bytes to perform file scan repartitioning. |
-| datafusion.optimizer.repartition_joins | true | Should DataFusion repartition data using the join keys to execute joins in parallel using the provided `target_partitions` level |
-| datafusion.optimizer.allow_symmetric_joins_without_pruning | true | Should DataFusion allow symmetric hash joins for unbounded data sources even when its inputs do not have any ordering or filtering If the flag is not enabled, the SymmetricHashJoin operator will be unable to prune its internal buffers, resulting in certain join types - such as Full, Left, LeftAnti, LeftSemi, Right, RightAnti, and RightSemi - being produced only at the end of the execution. This is not typical in stream processing. Additionally, without proper design for long runner execution, all types of joins may encounter out-of-memory errors. |
-| datafusion.optimizer.repartition_file_scans | true | When set to `true`, file groups will be repartitioned to achieve maximum parallelism. Currently Parquet and CSV formats are supported. If set to `true`, all files will be repartitioned evenly (i.e., a single large file might be partitioned into smaller chunks) for parallel scanning. If set to `false`, different files will be read in parallel, but repartitioning won't happen within a single file. |
-| datafusion.optimizer.repartition_windows | true | Should DataFusion repartition data using the partitions keys to execute window functions in parallel using the provided `target_partitions` level |
-| datafusion.optimizer.repartition_sorts | true | Should DataFusion execute sorts in a per-partition fashion and merge afterwards instead of coalescing first and sorting globally. With this flag is enabled, plans in the form below `text "SortExec: [a@0 ASC]", " CoalescePartitionsExec", " RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1", ` would turn into the plan below which performs better in multithreaded environments `text "SortPreservingMergeExec: [a@0 ASC]", " SortExec: [a@0 ASC]", " RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1", ` |
-| datafusion.optimizer.prefer_existing_sort | false | When true, DataFusion will opportunistically remove sorts when the data is already sorted, (i.e. setting `preserve_order` to true on `RepartitionExec` and using `SortPreservingMergeExec`) When false, DataFusion will maximize plan parallelism using `RepartitionExec` even if this requires subsequently resorting data using a `SortExec`. |
-| datafusion.optimizer.skip_failed_rules | false | When set to true, the logical plan optimizer will produce warning messages if any optimization rules produce errors and then proceed to the next rule. When set to false, any rules that produce errors will cause the query to fail |
-| datafusion.optimizer.max_passes | 3 | Number of times that the optimizer will attempt to optimize the plan |
-| datafusion.optimizer.top_down_join_key_reordering | true | When set to true, the physical plan optimizer will run a top down process to reorder the join keys |
-| datafusion.optimizer.prefer_hash_join | true | When set to true, the physical plan optimizer will prefer HashJoin over SortMergeJoin. HashJoin can work more efficiently than SortMergeJoin but consumes more memory |
-| datafusion.optimizer.hash_join_single_partition_threshold | 1048576 | The maximum estimated size in bytes for one input side of a HashJoin will be collected into a single partition |
-| datafusion.optimizer.hash_join_single_partition_threshold_rows | 131072 | The maximum estimated size in rows for one input side of a HashJoin will be collected into a single partition |
-| datafusion.optimizer.default_filter_selectivity | 20 | The default filter selectivity used by Filter Statistics when an exact selectivity cannot be determined. Valid values are between 0 (no selectivity) and 100 (all rows are selected). |
-| datafusion.optimizer.prefer_existing_union | false | When set to true, the optimizer will not attempt to convert Union to Interleave |
-| datafusion.optimizer.expand_views_at_output | false | When set to true, if the returned type is a view type then the output will be coerced to a non-view. Coerces `Utf8View` to `LargeUtf8`, and `BinaryView` to `LargeBinary`. |
-| datafusion.explain.logical_plan_only | false | When set to true, the explain statement will only print logical plans |
-| datafusion.explain.physical_plan_only | false | When set to true, the explain statement will only print physical plans |
-| datafusion.explain.show_statistics | false | When set to true, the explain statement will print operator statistics for physical plans |
-| datafusion.explain.show_sizes | true | When set to true, the explain statement will print the partition sizes |
-| datafusion.explain.show_schema | false | When set to true, the explain statement will print schema information |
-| datafusion.explain.format | indent | Display format of explain. Default is "indent". When set to "tree", it will print the plan in a tree-rendered format. |
-| datafusion.sql_parser.parse_float_as_decimal | false | When set to true, SQL parser will parse float as decimal type |
-| datafusion.sql_parser.enable_ident_normalization | true | When set to true, SQL parser will normalize ident (convert ident to lowercase when not quoted) |
-| datafusion.sql_parser.enable_options_value_normalization | false | When set to true, SQL parser will normalize options value (convert value to lowercase). Note that this option is ignored and will be removed in the future. All case-insensitive values are normalized automatically. |
-| datafusion.sql_parser.dialect | generic | Configure the SQL dialect used by DataFusion's parser; supported values include: Generic, MySQL, PostgreSQL, Hive, SQLite, Snowflake, Redshift, MsSQL, ClickHouse, BigQuery, Ansi, DuckDB and Databricks. |
-| datafusion.sql_parser.support_varchar_with_length | true | If true, permit lengths for `VARCHAR` such as `VARCHAR(20)`, but ignore the length. If false, error if a `VARCHAR` with a length is specified. The Arrow type system does not have a notion of maximum string length and thus DataFusion can not enforce such limits. |
-| datafusion.sql_parser.map_varchar_to_utf8view | false | If true, `VARCHAR` is mapped to `Utf8View` during SQL planning. If false, `VARCHAR` is mapped to `Utf8` during SQL planning. Default is false. |
-| datafusion.sql_parser.collect_spans | false | When set to true, the source locations relative to the original SQL query (i.e. [`Span`](https://docs.rs/sqlparser/latest/sqlparser/tokenizer/struct.Span.html)) will be collected and recorded in the logical plan nodes. |
-| datafusion.sql_parser.recursion_limit | 50 | Specifies the recursion depth limit when parsing complex SQL Queries |
-| datafusion.format.safe | true | If set to `true` any formatting errors will be written to the output instead of being converted into a [`std::fmt::Error`] |
-| datafusion.format.null | | Format string for nulls |
-| datafusion.format.date_format | %Y-%m-%d | Date format for date arrays |
-| datafusion.format.datetime_format | %Y-%m-%dT%H:%M:%S%.f | Format for DateTime arrays |
-| datafusion.format.timestamp_format | %Y-%m-%dT%H:%M:%S%.f | Timestamp format for timestamp arrays |
-| datafusion.format.timestamp_tz_format | NULL | Timestamp format for timestamp with timezone arrays. When `None`, ISO 8601 format is used. |
-| datafusion.format.time_format | %H:%M:%S%.f | Time format for time arrays |
-| datafusion.format.duration_format | pretty | Duration format. Can be either `"pretty"` or `"ISO8601"` |
-| datafusion.format.types_info | false | Show types in visual representation batches |
+| key | default | description |
+| ----------------------------------------------------------------------- | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| datafusion.catalog.create_default_catalog_and_schema | true | Whether the default catalog and schema should be created automatically. |
+| datafusion.catalog.default_catalog | datafusion | The default catalog name - this impacts what SQL queries use if not specified |
+| datafusion.catalog.default_schema | public | The default schema name - this impacts what SQL queries use if not specified |
+| datafusion.catalog.information_schema | false | Should DataFusion provide access to `information_schema` virtual tables for displaying schema information |
+| datafusion.catalog.location | NULL | Location scanned to load tables for `default` schema |
+| datafusion.catalog.format | NULL | Type of `TableProvider` to use when loading `default` schema |
+| datafusion.catalog.has_header | true | Default value for `format.has_header` for `CREATE EXTERNAL TABLE` if not specified explicitly in the statement. |
+| datafusion.catalog.newlines_in_values | false | Specifies whether newlines in (quoted) CSV values are supported. This is the default value for `format.newlines_in_values` for `CREATE EXTERNAL TABLE` if not specified explicitly in the statement. Parsing newlines in quoted values may be affected by execution behaviour such as parallel file scanning. Setting this to `true` ensures that newlines in values are parsed successfully, which may reduce performance. |
+| datafusion.execution.batch_size | 8192 | Default batch size while creating new batches, it's especially useful for buffer-in-memory batches since creating tiny batches would result in too much metadata memory consumption |
+| datafusion.execution.coalesce_batches | true | When set to true, record batches will be examined between each operator and small batches will be coalesced into larger batches. This is helpful when there are highly selective filters or joins that could produce tiny output batches. The target batch size is determined by the configuration setting |
+| datafusion.execution.collect_statistics | false | Should DataFusion collect statistics after listing files |
+| datafusion.execution.target_partitions | 0 | Number of partitions for query execution. Increasing partitions can increase concurrency. Defaults to the number of CPU cores on the system |
+| datafusion.execution.time_zone | +00:00 | The default time zone Some functions, e.g. `EXTRACT(HOUR from SOME_TIME)`, shift the underlying datetime according to this time zone, and then extract the hour |
+| datafusion.execution.parquet.enable_page_index | true | (reading) If true, reads the Parquet data page level metadata (the Page Index), if present, to reduce the I/O and number of rows decoded. |
+| datafusion.execution.parquet.pruning | true | (reading) If true, the parquet reader attempts to skip entire row groups based on the predicate in the query and the metadata (min/max values) stored in the parquet file |
+| datafusion.execution.parquet.skip_metadata | true | (reading) If true, the parquet reader skip the optional embedded metadata that may be in the file Schema. This setting can help avoid schema conflicts when querying multiple parquet files with schemas containing compatible types but different metadata |
+| datafusion.execution.parquet.metadata_size_hint | NULL | (reading) If specified, the parquet reader will try and fetch the last `size_hint` bytes of the parquet file optimistically. If not specified, two reads are required: One read to fetch the 8-byte parquet footer and another to fetch the metadata length encoded in the footer |
+| datafusion.execution.parquet.pushdown_filters | false | (reading) If true, filter expressions are be applied during the parquet decoding operation to reduce the number of rows decoded. This optimization is sometimes called "late materialization". |
+| datafusion.execution.parquet.reorder_filters | false | (reading) If true, filter expressions evaluated during the parquet decoding operation will be reordered heuristically to minimize the cost of evaluation. If false, the filters are applied in the same order as written in the query |
+| datafusion.execution.parquet.schema_force_view_types | true | (reading) If true, parquet reader will read columns of `Utf8/Utf8Large` with `Utf8View`, and `Binary/BinaryLarge` with `BinaryView`. |
+| datafusion.execution.parquet.binary_as_string | false | (reading) If true, parquet reader will read columns of `Binary/LargeBinary` with `Utf8`, and `BinaryView` with `Utf8View`. Parquet files generated by some legacy writers do not correctly set the UTF8 flag for strings, causing string columns to be loaded as BLOB instead. |
+| datafusion.execution.parquet.coerce_int96 | NULL | (reading) If true, parquet reader will read columns of physical type int96 as originating from a different resolution than nanosecond. This is useful for reading data from systems like Spark which stores microsecond resolution timestamps in an int96 allowing it to write values with a larger date range than 64-bit timestamps with nanosecond resolution. |
+| datafusion.execution.parquet.bloom_filter_on_read | true | (reading) Use any available bloom filters when reading parquet files |
+| datafusion.execution.parquet.data_pagesize_limit | 1048576 | (writing) Sets best effort maximum size of data page in bytes |
+| datafusion.execution.parquet.write_batch_size | 1024 | (writing) Sets write_batch_size in bytes |
+| datafusion.execution.parquet.writer_version | 1.0 | (writing) Sets parquet writer version valid values are "1.0" and "2.0" |
+| datafusion.execution.parquet.skip_arrow_metadata | false | (writing) Skip encoding the embedded arrow metadata in the KV_meta This is analogous to the `ArrowWriterOptions::with_skip_arrow_metadata`. Refer to <https://docs.rs/parquet/53.3.0/parquet/arrow/arrow_writer/struct.ArrowWriterOptions.html#method.with_skip_arrow_metadata> |
+| datafusion.execution.parquet.compression | zstd(3) | (writing) Sets default parquet compression codec. Valid values are: uncompressed, snappy, gzip(level), lzo, brotli(level), lz4, zstd(level), and lz4_raw. These values are not case sensitive. If NULL, uses default parquet writer setting Note that this default setting is not the same as the default parquet writer setting. |
+| datafusion.execution.parquet.dictionary_enabled | true | (writing) Sets if dictionary encoding is enabled. If NULL, uses default parquet writer setting |
+| datafusion.execution.parquet.dictionary_page_size_limit | 1048576 | (writing) Sets best effort maximum dictionary page size, in bytes |
+| datafusion.execution.parquet.statistics_enabled | page | (writing) Sets if statistics are enabled for any column Valid values are: "none", "chunk", and "page" These values are not case sensitive. If NULL, uses default parquet writer setting |
+| datafusion.execution.parquet.max_statistics_size | 4096 | (writing) Sets max statistics size for any column. If NULL, uses default parquet writer setting max_statistics_size is deprecated, currently it is not being used |
+| datafusion.execution.parquet.max_row_group_size | 1048576 | (writing) Target maximum number of rows in each row group (defaults to 1M rows). Writing larger row groups requires more memory to write, but can get better compression and be faster to read. |
+| datafusion.execution.parquet.created_by | datafusion version 47.0.0 | (writing) Sets "created by" property |
+| datafusion.execution.parquet.column_index_truncate_length | 64 | (writing) Sets column index truncate length |
+| datafusion.execution.parquet.statistics_truncate_length | NULL | (writing) Sets statictics truncate length. If NULL, uses default parquet writer setting |
+| datafusion.execution.parquet.data_page_row_count_limit | 20000 | (writing) Sets best effort maximum number of rows in data page |
+| datafusion.execution.parquet.encoding | NULL | (writing) Sets default encoding for any column. Valid values are: plain, plain_dictionary, rle, bit_packed, delta_binary_packed, delta_length_byte_array, delta_byte_array, rle_dictionary, and byte_stream_split. These values are not case sensitive. If NULL, uses default parquet writer setting |
+| datafusion.execution.parquet.bloom_filter_on_write | false | (writing) Write bloom filters for all columns when creating parquet files |
+| datafusion.execution.parquet.bloom_filter_fpp | NULL | (writing) Sets bloom filter false positive probability. If NULL, uses default parquet writer setting |
+| datafusion.execution.parquet.bloom_filter_ndv | NULL | (writing) Sets bloom filter number of distinct values. If NULL, uses default parquet writer setting |
+| datafusion.execution.parquet.allow_single_file_parallelism | true | (writing) Controls whether DataFusion will attempt to speed up writing parquet files by serializing them in parallel. Each column in each row group in each output file are serialized in parallel leveraging a maximum possible core count of n_files*n_row_groups*n_columns. |
+| datafusion.execution.parquet.maximum_parallel_row_group_writers | 1 | (writing) By default parallel parquet writer is tuned for minimum memory usage in a streaming execution plan. You may see a performance benefit when writing large parquet files by increasing maximum_parallel_row_group_writers and maximum_buffered_record_batches_per_stream if your system has idle cores and can tolerate additional memory usage. Boosting these values is likely worthwhile when writing out already in-memory data, such as from a cached data frame. |
+| datafusion.execution.parquet.maximum_buffered_record_batches_per_stream | 2 | (writing) By default parallel parquet writer is tuned for minimum memory usage in a streaming execution plan. You may see a performance benefit when writing large parquet files by increasing maximum_parallel_row_group_writers and maximum_buffered_record_batches_per_stream if your system has idle cores and can tolerate additional memory usage. Boosting these values is likely worthwhile when writing out already in-memory data, such as from a cached data frame. |
+| datafusion.execution.planning_concurrency | 0 | Fan-out during initial physical planning. This is mostly use to plan `UNION` children in parallel. Defaults to the number of CPU cores on the system |
+| datafusion.execution.skip_physical_aggregate_schema_check | false | When set to true, skips verifying that the schema produced by planning the input of `LogicalPlan::Aggregate` exactly matches the schema of the input plan. When set to false, if the schema does not match exactly (including nullability and metadata), a planning error will be raised. This is used to workaround bugs in the planner that are now caught by the new schema verification step. |
+| datafusion.execution.sort_spill_reservation_bytes | 10485760 | Specifies the reserved memory for each spillable sort operation to facilitate an in-memory merge. When a sort operation spills to disk, the in-memory data must be sorted and merged before being written to a file. This setting reserves a specific amount of memory for that in-memory sort/merge process. Note: This setting is irrelevant if the sort operation cannot spill (i.e., if there's no `DiskManager` configured). |
+| datafusion.execution.sort_in_place_threshold_bytes | 1048576 | When sorting, below what size should data be concatenated and sorted in a single RecordBatch rather than sorted in batches and merged. |
+| datafusion.execution.meta_fetch_concurrency | 32 | Number of files to read in parallel when inferring schema and statistics |
+| datafusion.execution.minimum_parallel_output_files | 4 | Guarantees a minimum level of output files running in parallel. RecordBatches will be distributed in round robin fashion to each parallel writer. Each writer is closed and a new file opened once soft_max_rows_per_output_file is reached. |
+| datafusion.execution.soft_max_rows_per_output_file | 50000000 | Target number of rows in output files when writing multiple. This is a soft max, so it can be exceeded slightly. There also will be one file smaller than the limit if the total number of rows written is not roughly divisible by the soft max |
+| datafusion.execution.max_buffered_batches_per_output_file | 2 | This is the maximum number of RecordBatches buffered for each output file being worked. Higher values can potentially give faster write performance at the cost of higher peak memory consumption |
+| datafusion.execution.listing_table_ignore_subdirectory | true | Should sub directories be ignored when scanning directories for data files. Defaults to true (ignores subdirectories), consistent with Hive. Note that this setting does not affect reading partitioned tables (e.g. `/table/year=2021/month=01/data.parquet`). |
+| datafusion.execution.enable_recursive_ctes | true | Should DataFusion support recursive CTEs |
+| datafusion.execution.split_file_groups_by_statistics | false | Attempt to eliminate sorts by packing & sorting files with non-overlapping statistics into the same file groups. Currently experimental |
+| datafusion.execution.keep_partition_by_columns | false | Should DataFusion keep the columns used for partition_by in the output RecordBatches |
+| datafusion.execution.skip_partial_aggregation_probe_ratio_threshold | 0.8 | Aggregation ratio (number of distinct groups / number of input rows) threshold for skipping partial aggregation. If the value is greater then partial aggregation will skip aggregation for further input |
+| datafusion.execution.skip_partial_aggregation_probe_rows_threshold | 100000 | Number of input rows partial aggregation partition should process, before aggregation ratio check and trying to switch to skipping aggregation mode |
+| datafusion.execution.use_row_number_estimates_to_optimize_partitioning | false | Should DataFusion use row number estimates at the input to decide whether increasing parallelism is beneficial or not. By default, only exact row numbers (not estimates) are used for this decision. Setting this flag to `true` will likely produce better plans. if the source of statistics is accurate. We plan to make this the default in the future. |
+| datafusion.execution.enforce_batch_size_in_joins | false | Should DataFusion enforce batch size in joins or not. By default, DataFusion will not enforce batch size in joins. Enforcing batch size in joins can reduce memory usage when joining large tables with a highly-selective join filter, but is also slightly slower. |
+| datafusion.execution.objectstore_writer_buffer_size | 10485760 | Size (bytes) of data buffer DataFusion uses when writing output files. This affects the size of the data chunks that are uploaded to remote object stores (e.g. AWS S3). If very large (>= 100 GiB) output files are being written, it may be necessary to increase this size to avoid errors from the remote end point. |
+| datafusion.optimizer.enable_distinct_aggregation_soft_limit | true | When set to true, the optimizer will push a limit operation into grouped aggregations which have no aggregate expressions, as a soft limit, emitting groups once the limit is reached, before all rows in the group are read. |
+| datafusion.optimizer.enable_round_robin_repartition | true | When set to true, the physical plan optimizer will try to add round robin repartitioning to increase parallelism to leverage more CPU cores |
+| datafusion.optimizer.enable_topk_aggregation | true | When set to true, the optimizer will attempt to perform limit operations during aggregations, if possible |
+| datafusion.optimizer.filter_null_join_keys | false | When set to true, the optimizer will insert filters before a join between a nullable and non-nullable column to filter out nulls on the nullable side. This filter can add additional overhead when the file format does not fully support predicate push down. |
+| datafusion.optimizer.repartition_aggregations | true | Should DataFusion repartition data using the aggregate keys to execute aggregates in parallel using the provided `target_partitions` level |
+| datafusion.optimizer.repartition_file_min_size | 10485760 | Minimum total files size in bytes to perform file scan repartitioning. |
+| datafusion.optimizer.repartition_joins | true | Should DataFusion repartition data using the join keys to execute joins in parallel using the provided `target_partitions` level |
+| datafusion.optimizer.allow_symmetric_joins_without_pruning | true | Should DataFusion allow symmetric hash joins for unbounded data sources even when its inputs do not have any ordering or filtering If the flag is not enabled, the SymmetricHashJoin operator will be unable to prune its internal buffers, resulting in certain join types - such as Full, Left, LeftAnti, LeftSemi, Right, RightAnti, and RightSemi - being produced only at the end of the execution. This is not typical in stream processing. Additionally, without proper design for long runner execution, all types of joins may encounter out-of-memory errors. |
+| datafusion.optimizer.repartition_file_scans | true | When set to `true`, datasource partitions will be repartitioned to achieve maximum parallelism. This applies to both in-memory partitions and FileSource's file groups (1 group is 1 partition). For FileSources, only Parquet and CSV formats are currently supported. If set to `true` for a FileSource, all files will be repartitioned evenly (i.e., a single large file might be partitioned into smaller chunks) for parallel scanning. If set to `false` for a FileSource, different files will be read in parallel, but repartitioning won't happen within a single file. If set to `true` for an in-memory source, all memtable's partitions will have their batches repartitioned evenly to the desired number of `target_partitions`. Repartitioning can change the total number of partitions and batches per partition, but does not slice the initial record tables provided to the MemTable on creation. |
+| datafusion.optimizer.repartition_windows | true | Should DataFusion repartition data using the partitions keys to execute window functions in parallel using the provided `target_partitions` level |
+| datafusion.optimizer.repartition_sorts | true | Should DataFusion execute sorts in a per-partition fashion and merge afterwards instead of coalescing first and sorting globally. With this flag is enabled, plans in the form below `text "SortExec: [a@0 ASC]", " CoalescePartitionsExec", " RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1", ` would turn into the plan below which performs better in multithreaded environments `text "SortPreservingMergeExec: [a@0 ASC]", " SortExec: [a@0 ASC]", " RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1", ` |
+| datafusion.optimizer.prefer_existing_sort | false | When true, DataFusion will opportunistically remove sorts when the data is already sorted, (i.e. setting `preserve_order` to true on `RepartitionExec` and using `SortPreservingMergeExec`) When false, DataFusion will maximize plan parallelism using `RepartitionExec` even if this requires subsequently resorting data using a `SortExec`. |
+| datafusion.optimizer.skip_failed_rules | false | When set to true, the logical plan optimizer will produce warning messages if any optimization rules produce errors and then proceed to the next rule. When set to false, any rules that produce errors will cause the query to fail |
+| datafusion.optimizer.max_passes | 3 | Number of times that the optimizer will attempt to optimize the plan |
+| datafusion.optimizer.top_down_join_key_reordering | true | When set to true, the physical plan optimizer will run a top down process to reorder the join keys |
+| datafusion.optimizer.prefer_hash_join | true | When set to true, the physical plan optimizer will prefer HashJoin over SortMergeJoin. HashJoin can work more efficiently than SortMergeJoin but consumes more memory |
+| datafusion.optimizer.hash_join_single_partition_threshold | 1048576 | The maximum estimated size in bytes for one input side of a HashJoin will be collected into a single partition |
+| datafusion.optimizer.hash_join_single_partition_threshold_rows | 131072 | The maximum estimated size in rows for one input side of a HashJoin will be collected into a single partition |
+| datafusion.optimizer.default_filter_selectivity | 20 | The default filter selectivity used by Filter Statistics when an exact selectivity cannot be determined. Valid values are between 0 (no selectivity) and 100 (all rows are selected). |
+| datafusion.optimizer.prefer_existing_union | false | When set to true, the optimizer will not attempt to convert Union to Interleave |
+| datafusion.optimizer.expand_views_at_output | false | When set to true, if the returned type is a view type then the output will be coerced to a non-view. Coerces `Utf8View` to `LargeUtf8`, and `BinaryView` to `LargeBinary`. |
+| datafusion.explain.logical_plan_only | false | When set to true, the explain statement will only print logical plans |
+| datafusion.explain.physical_plan_only | false | When set to true, the explain statement will only print physical plans |
+| datafusion.explain.show_statistics | false | When set to true, the explain statement will print operator statistics for physical plans |
+| datafusion.explain.show_sizes | true | When set to true, the explain statement will print the partition sizes |
+| datafusion.explain.show_schema | false | When set to true, the explain statement will print schema information |
+| datafusion.explain.format | indent | Display format of explain. Default is "indent". When set to "tree", it will print the plan in a tree-rendered format. |
+| datafusion.sql_parser.parse_float_as_decimal | false | When set to true, SQL parser will parse float as decimal type |
+| datafusion.sql_parser.enable_ident_normalization | true | When set to true, SQL parser will normalize ident (convert ident to lowercase when not quoted) |
+| datafusion.sql_parser.enable_options_value_normalization | false | When set to true, SQL parser will normalize options value (convert value to lowercase). Note that this option is ignored and will be removed in the future. All case-insensitive values are normalized automatically. |
+| datafusion.sql_parser.dialect | generic | Configure the SQL dialect used by DataFusion's parser; supported values include: Generic, MySQL, PostgreSQL, Hive, SQLite, Snowflake, Redshift, MsSQL, ClickHouse, BigQuery, Ansi, DuckDB and Databricks. |
+| datafusion.sql_parser.support_varchar_with_length | true | If true, permit lengths for `VARCHAR` such as `VARCHAR(20)`, but ignore the length. If false, error if a `VARCHAR` with a length is specified. The Arrow type system does not have a notion of maximum string length and thus DataFusion can not enforce such limits. |
+| datafusion.sql_parser.map_varchar_to_utf8view | false | If true, `VARCHAR` is mapped to `Utf8View` during SQL planning. If false, `VARCHAR` is mapped to `Utf8` during SQL planning. Default is false. |
+| datafusion.sql_parser.collect_spans | false | When set to true, the source locations relative to the original SQL query (i.e. [`Span`](https://docs.rs/sqlparser/latest/sqlparser/tokenizer/struct.Span.html)) will be collected and recorded in the logical plan nodes. |
+| datafusion.sql_parser.recursion_limit | 50 | Specifies the recursion depth limit when parsing complex SQL Queries |
+| datafusion.format.safe | true | If set to `true` any formatting errors will be written to the output instead of being converted into a [`std::fmt::Error`] |
+| datafusion.format.null | | Format string for nulls |
+| datafusion.format.date_format | %Y-%m-%d | Date format for date arrays |
+| datafusion.format.datetime_format | %Y-%m-%dT%H:%M:%S%.f | Format for DateTime arrays |
+| datafusion.format.timestamp_format | %Y-%m-%dT%H:%M:%S%.f | Timestamp format for timestamp arrays |
+| datafusion.format.timestamp_tz_format | NULL | Timestamp format for timestamp with timezone arrays. When `None`, ISO 8601 format is used. |
+| datafusion.format.time_format | %H:%M:%S%.f | Time format for time arrays |
+| datafusion.format.duration_format | pretty | Duration format. Can be either `"pretty"` or `"ISO8601"` |
+| datafusion.format.types_info | false | Show types in visual representation batches |