Skip to content

Apache DataFusion SQL Query Engine

ARROW-10994: [Rust] [DataFusion] Add support for compression when writing Parquet files

Andy Grove3c67b9c5d989
diff --git a/rust/benchmarks/src/bin/tpch.rs b/rust/benchmarks/src/bin/tpch.rs
index 9cbbd6b166..37eb0bcb61 100644
--- a/rust/benchmarks/src/bin/tpch.rs
+++ b/rust/benchmarks/src/bin/tpch.rs
@@ -17,7 +17,7 @@
//! Benchmark derived from TPC-H. This is not an official TPC-H benchmark.
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;
@@ -31,6 +31,8 @@ use datafusion::physical_plan::collect;
use datafusion::physical_plan::csv::CsvExec;
use datafusion::prelude::*;
+use parquet::basic::Compression;
+use parquet::file::properties::WriterProperties;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
@@ -81,6 +83,10 @@ struct ConvertOpt {
/// Output file format: `csv` or `parquet`
#[structopt(short = "f", long = "format")]
file_format: String,
+
+ /// Compression to use when writing Parquet files
+ #[structopt(short = "c", long = "compression", default_value = "snappy")]
+ compression: String,
}
#[derive(Debug, StructOpt)]
@@ -997,22 +1003,50 @@ async fn execute_query(
}
async fn convert_tbl(opt: ConvertOpt) -> Result<()> {
+ let output_root_path = Path::new(&opt.output_path);
+
for table in TABLES {
+ let start = Instant::now();
let schema = get_schema(table);
- let path = format!("{}/{}.tbl", opt.input_path.to_str().unwrap(), table);
+ let input_path = format!("{}/{}.tbl", opt.input_path.to_str().unwrap(), table);
let options = CsvReadOptions::new()
.schema(&schema)
.delimiter(b'|')
.file_extension(".tbl");
let ctx = ExecutionContext::new();
- let csv = Arc::new(CsvExec::try_new(&path, options, None, 4096)?);
- let output_path = opt.output_path.to_str().unwrap().to_owned();
-
+ let csv = Arc::new(CsvExec::try_new(&input_path, options, None, 4096)?);
+ let output_path = output_root_path.join(table);
+ let output_path = output_path.to_str().unwrap().to_owned();
+
+ println!(
+ "Converting '{}' to {} files in directory '{}'",
+ &input_path, &opt.file_format, &output_path
+ );
match opt.file_format.as_str() {
"csv" => ctx.write_csv(csv, output_path).await?,
- "parquet" => ctx.write_parquet(csv, output_path).await?,
+ "parquet" => {
+ let compression = match opt.compression.as_str() {
+ "none" => Compression::UNCOMPRESSED,
+ "snappy" => Compression::SNAPPY,
+ "brotli" => Compression::BROTLI,
+ "gzip" => Compression::GZIP,
+ "lz4" => Compression::LZ4,
+ "lz0" => Compression::LZO,
+ "zstd" => Compression::ZSTD,
+ other => {
+ return Err(DataFusionError::NotImplemented(format!(
+ "Invalid compression format: {}",
+ other
+ )))
+ }
+ };
+ let props = WriterProperties::builder()
+ .set_compression(compression)
+ .build();
+ ctx.write_parquet(csv, output_path, Some(props)).await?
+ }
other => {
return Err(DataFusionError::NotImplemented(format!(
"Invalid output format: {}",
@@ -1020,6 +1054,7 @@ async fn convert_tbl(opt: ConvertOpt) -> Result<()> {
)))
}
}
+ println!("Conversion completed in {} ms", start.elapsed().as_millis());
}
Ok(())
diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rs
index fcfd8832c7..33d84e1c31 100644
--- a/rust/datafusion/src/execution/context.rs
+++ b/rust/datafusion/src/execution/context.rs
@@ -54,6 +54,7 @@ use crate::sql::{
use crate::variable::{VarProvider, VarType};
use crate::{dataframe::DataFrame, physical_plan::udaf::AggregateUDF};
use parquet::arrow::ArrowWriter;
+use parquet::file::properties::WriterProperties;
/// ExecutionContext is the main interface for executing queries with DataFusion. The context
/// provides the following functionality:
@@ -346,25 +347,30 @@ impl ExecutionContext {
path: String,
) -> Result<()> {
// create directory to contain the CSV files (one per partition)
- let path = path.to_owned();
- fs::create_dir(&path)?;
-
- for i in 0..plan.output_partitioning().partition_count() {
- let path = path.clone();
- let plan = plan.clone();
- let filename = format!("part-{}.csv", i);
- let path = Path::new(&path).join(&filename);
- let file = fs::File::create(path)?;
- let mut writer = csv::Writer::new(file);
- let stream = plan.execute(i).await?;
-
- stream
- .map(|batch| writer.write(&batch?))
- .try_collect()
- .await
- .map_err(DataFusionError::from)?;
+ let fs_path = Path::new(&path);
+ match fs::create_dir(fs_path) {
+ Ok(()) => {
+ for i in 0..plan.output_partitioning().partition_count() {
+ let plan = plan.clone();
+ let filename = format!("part-{}.csv", i);
+ let path = fs_path.join(&filename);
+ let file = fs::File::create(path)?;
+ let mut writer = csv::Writer::new(file);
+ let stream = plan.execute(i).await?;
+
+ stream
+ .map(|batch| writer.write(&batch?))
+ .try_collect()
+ .await
+ .map_err(DataFusionError::from)?;
+ }
+ Ok(())
+ }
+ Err(e) => Err(DataFusionError::Execution(format!(
+ "Could not create directory {}: {:?}",
+ path, e
+ ))),
}
- Ok(())
}
/// Execute a query and write the results to a partitioned Parquet file
@@ -372,30 +378,39 @@ impl ExecutionContext {
&self,
plan: Arc<dyn ExecutionPlan>,
path: String,
+ writer_properties: Option<WriterProperties>,
) -> Result<()> {
- // create directory to contain the CSV files (one per partition)
- let path = path.to_owned();
- fs::create_dir(&path)?;
-
- for i in 0..plan.output_partitioning().partition_count() {
- let path = path.clone();
- let plan = plan.clone();
- let filename = format!("part-{}.parquet", i);
- let path = Path::new(&path).join(&filename);
- let file = fs::File::create(path)?;
- let mut writer =
- ArrowWriter::try_new(file.try_clone().unwrap(), plan.schema(), None)?;
- let stream = plan.execute(i).await?;
-
- stream
- .map(|batch| writer.write(&batch?))
- .try_collect()
- .await
- .map_err(DataFusionError::from)?;
-
- writer.close()?;
+ // create directory to contain the Parquet files (one per partition)
+ let fs_path = Path::new(&path);
+ match fs::create_dir(fs_path) {
+ Ok(()) => {
+ for i in 0..plan.output_partitioning().partition_count() {
+ let plan = plan.clone();
+ let filename = format!("part-{}.parquet", i);
+ let path = fs_path.join(&filename);
+ let file = fs::File::create(path)?;
+ let mut writer = ArrowWriter::try_new(
+ file.try_clone().unwrap(),
+ plan.schema(),
+ writer_properties.clone(),
+ )?;
+ let stream = plan.execute(i).await?;
+
+ stream
+ .map(|batch| writer.write(&batch?))
+ .try_collect()
+ .await
+ .map_err(DataFusionError::from)?;
+
+ writer.close()?;
+ }
+ Ok(())
+ }
+ Err(e) => Err(DataFusionError::Execution(format!(
+ "Could not create directory {}: {:?}",
+ path, e
+ ))),
}
- Ok(())
}
}
@@ -1224,7 +1239,7 @@ mod tests {
// execute a simple query and write the results to CSV
let out_dir = tmp_dir.as_ref().to_str().unwrap().to_string() + "/out";
- write_parquet(&mut ctx, "SELECT c1, c2 FROM test", &out_dir).await?;
+ write_parquet(&mut ctx, "SELECT c1, c2 FROM test", &out_dir, None).await?;
// create a new context and verify that the results were saved to a partitioned csv file
let mut ctx = ExecutionContext::new();
@@ -1569,11 +1584,13 @@ mod tests {
ctx: &mut ExecutionContext,
sql: &str,
out_dir: &str,
+ writer_properties: Option<WriterProperties>,
) -> Result<()> {
let logical_plan = ctx.create_logical_plan(sql)?;
let logical_plan = ctx.optimize(&logical_plan)?;
let physical_plan = ctx.create_physical_plan(&logical_plan)?;
- ctx.write_parquet(physical_plan, out_dir.to_string()).await
+ ctx.write_parquet(physical_plan, out_dir.to_string(), writer_properties)
+ .await
}
/// Generate CSV partitions within the supplied directory