Skip to content

Commit 47c6236

Browse files
committed
Introduce way to customize prefix of multi file outputs
Add test to illustrate prefixed parquet files Update docs with new execution's parameter partitioned_file_prefix_name
1 parent cdaecf0 commit 47c6236

9 files changed

Lines changed: 284 additions & 21 deletions

File tree

datafusion/common/src/config.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -684,6 +684,14 @@ config_namespace! {
684684
///
685685
/// Disabled by default, set to a number greater than 0 for enabling it.
686686
pub hash_join_buffering_capacity: usize, default = 0
687+
688+
/// Prefix to use when generating file name in multi file output.
689+
///
690+
/// When prefix is non-empty string, this prefix will be used to generate file name as
691+
/// `{partitioned_file_prefix_name}{datafusion generated suffix}`.
692+
///
693+
/// Defaults to empty string.
694+
pub partitioned_file_prefix_name: String, default = String::new()
687695
}
688696
}
689697

datafusion/core/src/dataframe/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ use datafusion_functions_aggregate::expr_fn::{
7272
use async_trait::async_trait;
7373
use datafusion_catalog::Session;
7474

75+
#[derive(Clone)]
7576
/// Contains options that control how data is
7677
/// written out from a DataFrame
7778
pub struct DataFrameWriteOptions {

datafusion/core/tests/dataframe/mod.rs

Lines changed: 252 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6854,3 +6854,255 @@ async fn test_duplicate_state_fields_for_dfschema_construct() -> Result<()> {
68546854

68556855
Ok(())
68566856
}
6857+
6858+
struct FixtureDataGen {
6859+
_tmp_dir: TempDir,
6860+
out_dir: String,
6861+
ctx: SessionContext,
6862+
}
6863+
6864+
impl FixtureDataGen {
6865+
fn register_local_table(
6866+
out_dir: impl AsRef<Path>,
6867+
ctx: &SessionContext,
6868+
) -> Result<()> {
6869+
// Create an in memory table with schema C1 and C2, both strings
6870+
let schema = Arc::new(Schema::new(vec![
6871+
Field::new("c1", DataType::Utf8, false),
6872+
Field::new("c2", DataType::Utf8, false),
6873+
]));
6874+
6875+
let record_batch = RecordBatch::try_new(
6876+
schema.clone(),
6877+
vec![
6878+
Arc::new(StringArray::from(vec!["abc", "def"])),
6879+
Arc::new(StringArray::from(vec!["123", "456"])),
6880+
],
6881+
)?;
6882+
6883+
let mem_table = Arc::new(MemTable::try_new(schema, vec![vec![record_batch]])?);
6884+
6885+
// Register the table in the context
6886+
ctx.register_table("test", mem_table)?;
6887+
6888+
let local = Arc::new(LocalFileSystem::new_with_prefix(&out_dir)?);
6889+
let local_url = Url::parse("file://local").unwrap();
6890+
ctx.register_object_store(&local_url, local);
6891+
6892+
Ok(())
6893+
}
6894+
6895+
// initializes basic data and writes it using via executing physical plan
6896+
//
6897+
// Available columns: c1, c2
6898+
async fn prepare_execution_plan_writes(config: SessionConfig) -> Result<Self> {
6899+
let tmp_dir = TempDir::new()?;
6900+
6901+
let ctx = SessionContext::new_with_config(config);
6902+
6903+
Self::register_local_table(&tmp_dir, &ctx)?;
6904+
6905+
let out_dir = tmp_dir.as_ref().to_str().unwrap().to_string() + "/out/";
6906+
let out_dir_url = format!("file://{out_dir}");
6907+
6908+
let df = ctx.sql("SELECT c1, c2 FROM test").await?;
6909+
let plan = df.create_physical_plan().await?;
6910+
6911+
ctx.write_parquet(plan.clone(), &out_dir_url, None).await?;
6912+
ctx.write_csv(plan.clone(), &out_dir_url).await?;
6913+
ctx.write_json(plan.clone(), &out_dir_url).await?;
6914+
6915+
Ok(Self {
6916+
_tmp_dir: tmp_dir,
6917+
out_dir,
6918+
ctx,
6919+
})
6920+
}
6921+
6922+
// initializes basic data and writes it using `write_opts`
6923+
//
6924+
// Available columns: c1, c2
6925+
async fn prepare_direct_df_writes(
6926+
config: SessionConfig,
6927+
write_opts: DataFrameWriteOptions,
6928+
) -> Result<Self> {
6929+
let tmp_dir = TempDir::new()?;
6930+
6931+
let ctx = SessionContext::new_with_config(config);
6932+
6933+
Self::register_local_table(&tmp_dir, &ctx)?;
6934+
6935+
let out_dir = tmp_dir.as_ref().to_str().unwrap().to_string() + "/out/";
6936+
let out_dir_url = format!("file://{out_dir}");
6937+
6938+
let df = ctx.sql("SELECT c1, c2 FROM test").await?;
6939+
6940+
df.clone()
6941+
.write_parquet(&out_dir_url, write_opts.clone(), None)
6942+
.await?;
6943+
df.clone()
6944+
.write_csv(&out_dir_url, write_opts.clone(), None)
6945+
.await?;
6946+
df.write_json(&out_dir_url, write_opts.clone(), None)
6947+
.await?;
6948+
6949+
Ok(Self {
6950+
_tmp_dir: tmp_dir,
6951+
out_dir,
6952+
ctx,
6953+
})
6954+
}
6955+
}
6956+
6957+
#[tokio::test]
6958+
async fn write_partitioned_results_with_prefix() -> Result<()> {
6959+
let mut config = SessionConfig::new();
6960+
config.options_mut().execution.partitioned_file_prefix_name = "prefix-".to_owned();
6961+
6962+
let df_write_options =
6963+
DataFrameWriteOptions::new().with_partition_by(vec![String::from("c2")]);
6964+
let FixtureDataGen {
6965+
_tmp_dir,
6966+
out_dir,
6967+
ctx,
6968+
} = FixtureDataGen::prepare_direct_df_writes(config, df_write_options).await?;
6969+
6970+
let partitioned_file = format!("{out_dir}/c2=123/prefix-*");
6971+
let filter_df = ctx
6972+
.read_parquet(&partitioned_file, ParquetReadOptions::default())
6973+
.await?;
6974+
6975+
// Check that the c2 column is gone and that c1 is abc.
6976+
let results_parquet = filter_df.collect().await?;
6977+
let results_parquet_display = batches_to_string(&results_parquet);
6978+
assert_snapshot!(
6979+
results_parquet_display.as_str(),
6980+
@r###"
6981+
+-----+
6982+
| c1 |
6983+
+-----+
6984+
| abc |
6985+
+-----+
6986+
"###
6987+
);
6988+
6989+
let results_csv = ctx
6990+
.read_csv(&partitioned_file, Default::default())
6991+
.await?
6992+
.collect()
6993+
.await?;
6994+
assert_eq!(
6995+
results_parquet_display.as_str(),
6996+
batches_to_string(&results_csv)
6997+
);
6998+
6999+
let results_json = ctx
7000+
.read_json(&partitioned_file, Default::default())
7001+
.await?
7002+
.collect()
7003+
.await?;
7004+
assert_eq!(results_parquet_display, batches_to_string(&results_json));
7005+
7006+
Ok(())
7007+
}
7008+
7009+
#[tokio::test]
7010+
async fn write_physical_plan_results_with_prefix() -> Result<()> {
7011+
let mut config = SessionConfig::new();
7012+
config.options_mut().execution.partitioned_file_prefix_name = "prefix-".to_owned();
7013+
7014+
let FixtureDataGen {
7015+
_tmp_dir,
7016+
out_dir,
7017+
ctx,
7018+
} = FixtureDataGen::prepare_execution_plan_writes(config).await?;
7019+
7020+
let partitioned_file = format!("{out_dir}/prefix-*");
7021+
7022+
let df = ctx
7023+
.read_parquet(&partitioned_file, Default::default())
7024+
.await?;
7025+
let results_parquet = df.collect().await?;
7026+
let results_parquet_display = batches_to_string(&results_parquet);
7027+
assert_snapshot!(
7028+
results_parquet_display.as_str(),
7029+
@r###"
7030+
+-----+-----+
7031+
| c1 | c2 |
7032+
+-----+-----+
7033+
| abc | 123 |
7034+
| def | 456 |
7035+
+-----+-----+
7036+
"###
7037+
);
7038+
7039+
let results_csv = ctx
7040+
.read_csv(&partitioned_file, Default::default())
7041+
.await?
7042+
.collect()
7043+
.await?;
7044+
assert_eq!(
7045+
results_parquet_display.as_str(),
7046+
batches_to_string(&results_csv)
7047+
);
7048+
7049+
let results_json = ctx
7050+
.read_json(&partitioned_file, Default::default())
7051+
.await?
7052+
.collect()
7053+
.await?;
7054+
assert_eq!(results_parquet_display, batches_to_string(&results_json));
7055+
7056+
Ok(())
7057+
}
7058+
7059+
#[tokio::test]
7060+
async fn write_parts_parquet_results_with_prefix() -> Result<()> {
7061+
let mut config = SessionConfig::new();
7062+
config.options_mut().execution.partitioned_file_prefix_name = "prefix-".to_owned();
7063+
7064+
let df_write_options = DataFrameWriteOptions::new();
7065+
let FixtureDataGen {
7066+
_tmp_dir,
7067+
out_dir,
7068+
ctx,
7069+
} = FixtureDataGen::prepare_direct_df_writes(config, df_write_options).await?;
7070+
7071+
let partitioned_file = format!("{out_dir}/prefix-*");
7072+
7073+
let df = ctx
7074+
.read_parquet(&partitioned_file, Default::default())
7075+
.await?;
7076+
let results_parquet = df.collect().await?;
7077+
let results_parquet_display = batches_to_string(&results_parquet);
7078+
assert_snapshot!(
7079+
results_parquet_display.as_str(),
7080+
@r###"
7081+
+-----+-----+
7082+
| c1 | c2 |
7083+
+-----+-----+
7084+
| abc | 123 |
7085+
| def | 456 |
7086+
+-----+-----+
7087+
"###
7088+
);
7089+
7090+
let results_csv = ctx
7091+
.read_csv(&partitioned_file, Default::default())
7092+
.await?
7093+
.collect()
7094+
.await?;
7095+
assert_eq!(
7096+
results_parquet_display.as_str(),
7097+
batches_to_string(&results_csv)
7098+
);
7099+
7100+
let results_json = ctx
7101+
.read_json(&partitioned_file, Default::default())
7102+
.await?
7103+
.collect()
7104+
.await?;
7105+
assert_eq!(results_parquet_display, batches_to_string(&results_json));
7106+
7107+
Ok(())
7108+
}

datafusion/datasource-csv/src/source.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -463,16 +463,15 @@ pub async fn plan_to_csv(
463463
let parsed = ListingTableUrl::parse(path)?;
464464
let object_store_url = parsed.object_store();
465465
let store = task_ctx.runtime_env().object_store(&object_store_url)?;
466-
let writer_buffer_size = task_ctx
467-
.session_config()
468-
.options()
469-
.execution
470-
.objectstore_writer_buffer_size;
466+
let exec_options = &task_ctx.session_config().options().execution;
467+
let writer_buffer_size = exec_options.objectstore_writer_buffer_size;
468+
let file_name_prefix = exec_options.partitioned_file_prefix_name.as_str();
469+
471470
let mut join_set = JoinSet::new();
472471
for i in 0..plan.output_partitioning().partition_count() {
473472
let storeref = Arc::clone(&store);
474473
let plan: Arc<dyn ExecutionPlan> = Arc::clone(&plan);
475-
let filename = format!("{}/part-{i}.csv", parsed.prefix());
474+
let filename = format!("{}/{file_name_prefix}part-{i}.csv", parsed.prefix(),);
476475
let file = object_store::path::Path::parse(filename)?;
477476

478477
let mut stream = plan.execute(i, Arc::clone(&task_ctx))?;

datafusion/datasource-json/src/source.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -471,16 +471,15 @@ pub async fn plan_to_json(
471471
let parsed = ListingTableUrl::parse(path)?;
472472
let object_store_url = parsed.object_store();
473473
let store = task_ctx.runtime_env().object_store(&object_store_url)?;
474-
let writer_buffer_size = task_ctx
475-
.session_config()
476-
.options()
477-
.execution
478-
.objectstore_writer_buffer_size;
474+
let exec_options = &task_ctx.session_config().options().execution;
475+
let writer_buffer_size = exec_options.objectstore_writer_buffer_size;
476+
let file_name_prefix = exec_options.partitioned_file_prefix_name.as_str();
477+
479478
let mut join_set = JoinSet::new();
480479
for i in 0..plan.output_partitioning().partition_count() {
481480
let storeref = Arc::clone(&store);
482481
let plan: Arc<dyn ExecutionPlan> = Arc::clone(&plan);
483-
let filename = format!("{}/part-{i}.json", parsed.prefix());
482+
let filename = format!("{}/{file_name_prefix}part-{i}.json", parsed.prefix());
484483
let file = object_store::path::Path::parse(filename)?;
485484

486485
let mut stream = plan.execute(i, Arc::clone(&task_ctx))?;

datafusion/datasource-parquet/src/writer.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -39,21 +39,20 @@ pub async fn plan_to_parquet(
3939
let object_store_url = parsed.object_store();
4040
let store = task_ctx.runtime_env().object_store(&object_store_url)?;
4141
let mut join_set = JoinSet::new();
42+
let exec_options = &task_ctx.session_config().options().execution;
43+
let file_name_prefix = exec_options.partitioned_file_prefix_name.as_str();
44+
4245
for i in 0..plan.output_partitioning().partition_count() {
4346
let plan: Arc<dyn ExecutionPlan> = Arc::clone(&plan);
44-
let filename = format!("{}/part-{i}.parquet", parsed.prefix());
47+
let filename = format!("{}/{file_name_prefix}part-{i}.parquet", parsed.prefix());
4548
let file = Path::parse(filename)?;
4649
let propclone = writer_properties.clone();
4750

4851
let storeref = Arc::clone(&store);
4952
let buf_writer = BufWriter::with_capacity(
5053
storeref,
5154
file.clone(),
52-
task_ctx
53-
.session_config()
54-
.options()
55-
.execution
56-
.objectstore_writer_buffer_size,
55+
exec_options.objectstore_writer_buffer_size,
5756
);
5857
let mut stream = plan.execute(i, Arc::clone(&task_ctx))?;
5958
join_set.spawn(async move {

datafusion/datasource/src/write/demux.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,8 @@ async fn row_count_demuxer(
157157
let max_buffered_batches = exec_options.max_buffered_batches_per_output_file;
158158
let minimum_parallel_files = exec_options.minimum_parallel_output_files;
159159
let mut part_idx = 0;
160-
let write_id = rand::distr::Alphanumeric.sample_string(&mut rand::rng(), 16);
160+
let mut write_id = exec_options.partitioned_file_prefix_name.clone();
161+
rand::distr::Alphanumeric.append_string(&mut rand::rng(), &mut write_id, 16);
161162

162163
let mut open_file_streams = Vec::with_capacity(minimum_parallel_files);
163164

@@ -301,9 +302,10 @@ async fn hive_style_partitions_demuxer(
301302
file_extension: String,
302303
keep_partition_by_columns: bool,
303304
) -> Result<()> {
304-
let write_id = rand::distr::Alphanumeric.sample_string(&mut rand::rng(), 16);
305-
306305
let exec_options = &context.session_config().options().execution;
306+
let mut write_id = exec_options.partitioned_file_prefix_name.clone();
307+
rand::distr::Alphanumeric.append_string(&mut rand::rng(), &mut write_id, 16);
308+
307309
let max_buffered_recordbatches = exec_options.max_buffered_batches_per_output_file;
308310

309311
// To support non string partition col types, cast the type to &str first

datafusion/sqllogictest/test_files/information_schema.slt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,7 @@ datafusion.execution.parquet.statistics_enabled page
261261
datafusion.execution.parquet.statistics_truncate_length 64
262262
datafusion.execution.parquet.write_batch_size 1024
263263
datafusion.execution.parquet.writer_version 1.0
264+
datafusion.execution.partitioned_file_prefix_name (empty)
264265
datafusion.execution.perfect_hash_join_min_key_density 0.15
265266
datafusion.execution.perfect_hash_join_small_build_threshold 1024
266267
datafusion.execution.planning_concurrency 13
@@ -402,6 +403,7 @@ datafusion.execution.parquet.statistics_enabled page (writing) Sets if statistic
402403
datafusion.execution.parquet.statistics_truncate_length 64 (writing) Sets statistics truncate length. If NULL, uses default parquet writer setting
403404
datafusion.execution.parquet.write_batch_size 1024 (writing) Sets write_batch_size in rows
404405
datafusion.execution.parquet.writer_version 1.0 (writing) Sets parquet writer version valid values are "1.0" and "2.0"
406+
datafusion.execution.partitioned_file_prefix_name (empty) Prefix to use when generating file name in multi file output. When prefix is non-empty string, this prefix will be used to generate file name as `{partitioned_file_prefix_name}{datafusion generated suffix}`. Defaults to empty string.
405407
datafusion.execution.perfect_hash_join_min_key_density 0.15 The minimum required density of join keys on the build side to consider a perfect hash join (see `HashJoinExec` for more details). Density is calculated as: `(number of rows) / (max_key - min_key + 1)`. A perfect hash join may be used if the actual key density > this value. Currently only supports cases where build_side.num_rows() < u32::MAX. Support for build_side.num_rows() >= u32::MAX will be added in the future.
406408
datafusion.execution.perfect_hash_join_small_build_threshold 1024 A perfect hash join (see `HashJoinExec` for more details) will be considered if the range of keys (max - min) on the build side is < this threshold. This provides a fast path for joins with very small key ranges, bypassing the density check. Currently only supports cases where build_side.num_rows() < u32::MAX. Support for build_side.num_rows() >= u32::MAX will be added in the future.
407409
datafusion.execution.planning_concurrency 13 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

0 commit comments

Comments
 (0)