Skip to content

Apache DataFusion SQL Query Engine

ARROW-10464: [Rust] [DataFusion] Add utility to convert TPC-H data from tbl to CSV and Parquet

Andy Grove60e0620fddfa
diff --git a/rust/benchmarks/Cargo.toml b/rust/benchmarks/Cargo.toml
index 1762969ad9..7d7b6c9734 100644
--- a/rust/benchmarks/Cargo.toml
+++ b/rust/benchmarks/Cargo.toml
@@ -27,6 +27,8 @@ license = "Apache-2.0"
[dependencies]
arrow = { path = "../arrow" }
+parquet = { path = "../parquet" }
datafusion = { path = "../datafusion" }
structopt = { version = "0.3", default-features = false }
tokio = { version = "0.2", features = ["macros", "rt-core", "rt-threaded"] }
+futures = "0.3"
diff --git a/rust/benchmarks/README.md b/rust/benchmarks/README.md
index 89bb4ecc5a..9bff3e2d8e 100644
--- a/rust/benchmarks/README.md
+++ b/rust/benchmarks/README.md
@@ -49,15 +49,18 @@ data. This value can be increased to generate larger data sets.
The benchmark can then be run (assuming the data created from `dbgen` is in `/mnt/tpch-dbgen`) with a command such as:
```bash
-cargo run --release --bin tpch -- --iterations 3 --path /mnt/tpch-dbgen --format tbl --query 1 --batch-size 4096
+cargo run --release --bin tpch -- benchmark --iterations 3 --path /mnt/tpch-dbgen --format tbl --query 1 --batch-size 4096
```
-The benchmark program also supports CSV and Parquet input file formats.
+The benchmark program also supports CSV and Parquet input file formats and a utility is provided to convert from `tbl`
+(generated by the `dbgen` utility) to CSV and Parquet.
-This crate does not currently provide a method for converting the generated tbl format to CSV or Parquet so it is
-necessary to use other tools to perform this conversion.
+```bash
+cargo run --release --bin tpch -- convert --input /mnt/tpch-dbgen --output /mnt/tpch-parquet --format parquet
+```
-One option is to use the following Docker image to perform the conversion from `tbl` files to CSV or Parquet.
+This utility does not yet provide support for changing the number of partitions when performing the conversion. Another
+option is to use the following Docker image to perform the conversion from `tbl` files to CSV or Parquet.
```bash
docker run -it ballistacompute/spark-benchmarks:0.4.0-SNAPSHOT
@@ -87,7 +90,6 @@ docker run -v /mnt:/mnt -it ballistacompute/spark-benchmarks:0.4.0-SNAPSHOT \
--partitions 64
```
-
## NYC Taxi Benchmark
These benchmarks are based on the [New York Taxi and Limousine Commission][3] data set.
@@ -108,4 +110,4 @@ Query 'fare_amt_by_passenger' iteration 2 took 7969 ms
[1]: http://www.tpc.org/tpch/
[2]: https://github.com/databricks/tpch-dbgen
-[3]: https://www1.nyc.gov/site/tlc/about/tlc-trip-record-data.page
\ No newline at end of file
+[3]: https://www1.nyc.gov/site/tlc/about/tlc-trip-record-data.page
diff --git a/rust/benchmarks/src/bin/tpch.rs b/rust/benchmarks/src/bin/tpch.rs
index b76ae13b38..1a71c933a3 100644
--- a/rust/benchmarks/src/bin/tpch.rs
+++ b/rust/benchmarks/src/bin/tpch.rs
@@ -19,21 +19,21 @@
use std::path::PathBuf;
use std::process;
+use std::sync::Arc;
use std::time::Instant;
use arrow::datatypes::{DataType, Field, Schema};
use arrow::util::pretty;
-use datafusion::error::Result;
-use datafusion::execution::context::{ExecutionConfig, ExecutionContext};
-
use datafusion::datasource::parquet::ParquetTable;
use datafusion::datasource::{CsvFile, MemTable, TableProvider};
-use datafusion::physical_plan::csv::CsvReadOptions;
+use datafusion::error::{DataFusionError, Result};
+use datafusion::execution::context::{ExecutionConfig, ExecutionContext};
+use datafusion::physical_plan::csv::{CsvExec, CsvReadOptions};
+
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
-#[structopt(name = "Benchmarks", about = "Apache Arrow Rust Benchmarks.")]
-struct TpchOpt {
+struct BenchmarkOpt {
/// Query number
#[structopt(short, long)]
query: usize,
@@ -67,11 +67,38 @@ struct TpchOpt {
mem_table: bool,
}
+#[derive(Debug, StructOpt)]
+struct ConvertOpt {
+ /// Path to csv files
+ #[structopt(parse(from_os_str), required = true, short = "i", long = "input")]
+ input_path: PathBuf,
+
+ /// Output path
+ #[structopt(parse(from_os_str), required = true, short = "o", long = "output")]
+ output_path: PathBuf,
+
+ /// Output file format: `csv` or `parquet`
+ #[structopt(short = "f", long = "format")]
+ file_format: String,
+}
+
+#[derive(Debug, StructOpt)]
+#[structopt(name = "TPC-H", about = "TPC-H Benchmarks.")]
+enum TpchOpt {
+ Benchmark(BenchmarkOpt),
+ Convert(ConvertOpt),
+}
+
#[tokio::main]
async fn main() -> Result<()> {
- let opt = TpchOpt::from_args();
- println!("Running benchmarks with the following options: {:?}", opt);
+ match TpchOpt::from_args() {
+ TpchOpt::Benchmark(opt) => benchmark(opt).await,
+ TpchOpt::Convert(opt) => convert_tbl(opt).await,
+ }
+}
+async fn benchmark(opt: BenchmarkOpt) -> Result<()> {
+ println!("Running benchmarks with the following options: {:?}", opt);
let config = ExecutionConfig::new()
.with_concurrency(opt.concurrency)
.with_batch_size(opt.batch_size);
@@ -180,6 +207,33 @@ async fn execute_sql(ctx: &mut ExecutionContext, sql: &str, debug: bool) -> Resu
Ok(())
}
+async fn convert_tbl(opt: ConvertOpt) -> Result<()> {
+ let schema = lineitem_schema();
+
+ let path = format!("{}/lineitem.tbl", opt.input_path.to_str().unwrap());
+ 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();
+
+ match opt.file_format.as_str() {
+ "csv" => ctx.write_csv(csv, output_path).await?,
+ "parquet" => ctx.write_parquet(csv, output_path).await?,
+ other => {
+ return Err(DataFusionError::NotImplemented(format!(
+ "Invalid output format: {}",
+ other
+ )))
+ }
+ }
+
+ Ok(())
+}
+
fn lineitem_schema() -> Schema {
Schema::new(vec![
Field::new("l_orderkey", DataType::UInt32, true),
diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rs
index 2a1e1479cc..03973aadf3 100644
--- a/rust/datafusion/src/execution/context.rs
+++ b/rust/datafusion/src/execution/context.rs
@@ -53,6 +53,7 @@ use crate::sql::{
};
use crate::variable::{VarProvider, VarType};
use crate::{dataframe::DataFrame, physical_plan::udaf::AggregateUDF};
+use parquet::arrow::ArrowWriter;
/// ExecutionContext is the main interface for executing queries with DataFusion. The context
/// provides the following functionality:
@@ -390,6 +391,37 @@ impl ExecutionContext {
Ok(())
}
+ /// Execute a query and write the results to a partitioned Parquet file
+ pub async fn write_parquet(
+ &self,
+ plan: Arc<dyn ExecutionPlan>,
+ 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-{}.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(|e| DataFusionError::from(e))?;
+
+ writer.close()?;
+ }
+ Ok(())
+ }
+
/// get the registry, that allows to construct logical expressions of UDFs
pub fn registry(&self) -> &dyn FunctionRegistry {
&self.state
@@ -1192,6 +1224,47 @@ mod tests {
Ok(())
}
+ #[tokio::test]
+ async fn write_parquet_results() -> Result<()> {
+ // create partitioned input file and context
+ let tmp_dir = TempDir::new()?;
+ let mut ctx = create_ctx(&tmp_dir, 4)?;
+
+ // 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?;
+
+ // create a new context and verify that the results were saved to a partitioned csv file
+ let mut ctx = ExecutionContext::new();
+
+ // register each partition as well as the top level dir
+ ctx.register_parquet("part0", &format!("{}/part-0.parquet", out_dir))?;
+ ctx.register_parquet("part1", &format!("{}/part-1.parquet", out_dir))?;
+ ctx.register_parquet("part2", &format!("{}/part-2.parquet", out_dir))?;
+ ctx.register_parquet("part3", &format!("{}/part-3.parquet", out_dir))?;
+ ctx.register_parquet("allparts", &out_dir)?;
+
+ let part0 = collect(&mut ctx, "SELECT c1, c2 FROM part0").await?;
+ let part1 = collect(&mut ctx, "SELECT c1, c2 FROM part1").await?;
+ let part2 = collect(&mut ctx, "SELECT c1, c2 FROM part2").await?;
+ let part3 = collect(&mut ctx, "SELECT c1, c2 FROM part3").await?;
+ let allparts = collect(&mut ctx, "SELECT c1, c2 FROM allparts").await?;
+
+ let part0_count: usize = part0.iter().map(|batch| batch.num_rows()).sum();
+ let part1_count: usize = part1.iter().map(|batch| batch.num_rows()).sum();
+ let part2_count: usize = part2.iter().map(|batch| batch.num_rows()).sum();
+ let part3_count: usize = part3.iter().map(|batch| batch.num_rows()).sum();
+ let allparts_count: usize = allparts.iter().map(|batch| batch.num_rows()).sum();
+
+ assert_eq!(part0_count, 10);
+ assert_eq!(part1_count, 10);
+ assert_eq!(part2_count, 10);
+ assert_eq!(part3_count, 10);
+ assert_eq!(allparts_count, 40);
+
+ Ok(())
+ }
+
#[tokio::test]
async fn query_csv_with_custom_partition_extension() -> Result<()> {
let tmp_dir = TempDir::new()?;
@@ -1493,6 +1566,18 @@ mod tests {
ctx.write_csv(physical_plan, out_dir.to_string()).await
}
+ /// Execute SQL and write results to partitioned parquet files
+ async fn write_parquet(
+ ctx: &mut ExecutionContext,
+ sql: &str,
+ out_dir: &str,
+ ) -> 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
+ }
+
/// Generate CSV partitions within the supplied directory
fn populate_csv_partitions(
tmp_dir: &TempDir,