Apache DataFusion SQL Query Engine
Parquet sorting benchmark (#5433)
Jay Miller1455b025cec3
diff --git a/benchmarks/README.md b/benchmarks/README.mdindex f2f581fd2a..0d13ed9764 100644--- a/benchmarks/README.md+++ b/benchmarks/README.md@@ -50,6 +50,7 @@ cargo run --release --bin tpch -- benchmark datafusion --iterations 3 --path ./d```If you omit `--query=<query_id>` argument, then all benchmarks will be run one by one (from query 1 to query 22).+```bashcargo run --release --bin tpch -- benchmark datafusion --iterations 1 --path ./data --format tbl --batch-size 4096```@@ -61,6 +62,7 @@ cargo run --release --features "simd mimalloc" --bin tpch -- benchmark datafusio```If you want to disable collection of statistics (and thus cost based optimizers), you can pass `--disable-statistics` flag.+```bashcargo run --release --bin tpch -- benchmark datafusion --iterations 3 --path /mnt/tpch-parquet --format parquet --query 17 --disable-statistics```@@ -143,13 +145,15 @@ h2o groupby query 1 took 1669 ms[1]: http://www.tpc.org/tpch/[2]: https://www1.nyc.gov/site/tlc/about/tlc-trip-record-data.page-## Parquet filter pushdown benchmarks+## Parquet benchmarks++This is a set of benchmarks for testing and verifying performance of parquet filtering and sorting.+The queries are executed on a synthetic dataset generated during the benchmark execution and designed to simulate web server access logs.-This is a set of benchmarks for testing and verifying performance of parquet filter pushdown. The queries are executed on-a synthetic dataset generated during the benchmark execution and designed to simulate web server access logs.+To run filter benchmarks, run:```base-cargo run --release --bin parquet_filter_pushdown -- --path ./data --scale-factor 1.0+cargo run --release --bin parquet -- filter --path ./data --scale-factor 1.0```This will generate the synthetic dataset at `./data/logs.parquet`. The size of the dataset can be controlled through the `size_factor`@@ -158,6 +162,7 @@ This will generate the synthetic dataset at `./data/logs.parquet`. The size of tFor each filter we will run the query using different `ParquetScanOption` settings.Example run:+```Running benchmarks with the following options: Opt { debug: false, iterations: 3, partitions: 2, path: "./data", batch_size: 8192, scale_factor: 1.0 }Generated test dataset with 10699521 rows@@ -176,3 +181,13 @@ Iteration 1 returned 1781686 rows in 1986 msIteration 2 returned 1781686 rows in 1947 ms...```++Similarly, to run sorting benchmarks, run:++```base+cargo run --release --bin parquet -- sort --path ./data --scale-factor 1.0+```++This proceeds in the same way as the filter benchmarks: each sort expression+combination will be run using the same set of `ParquetScanOption` as the+filter benchmarks.diff --git a/benchmarks/src/bin/parquet_filter_pushdown.rs b/benchmarks/src/bin/parquet.rssimilarity index 50%rename from benchmarks/src/bin/parquet_filter_pushdown.rsrename to benchmarks/src/bin/parquet.rsindex d49cb839da..30fdc5ea3d 100644--- a/benchmarks/src/bin/parquet_filter_pushdown.rs+++ b/benchmarks/src/bin/parquet.rs@@ -19,11 +19,14 @@ use arrow::util::pretty;use datafusion::common::Result;use datafusion::logical_expr::{lit, or, Expr};use datafusion::optimizer::utils::disjunction;+use datafusion::physical_expr::PhysicalSortExpr;use datafusion::physical_plan::collect;-use datafusion::prelude::{col, SessionContext};+use datafusion::physical_plan::sorts::sort::SortExec;+use datafusion::prelude::{col, SessionConfig, SessionContext};use parquet::file::properties::WriterProperties;use parquet_test_utils::{ParquetScanOptions, TestParquetFile};use std::path::PathBuf;+use std::sync::Arc;use std::time::Instant;use structopt::StructOpt;use test_utils::AccessLogGenerator;@@ -32,8 +35,16 @@ use test_utils::AccessLogGenerator;#[global_allocator]static ALLOC: snmalloc_rs::SnMalloc = snmalloc_rs::SnMalloc;-#[derive(Debug, StructOpt)]+#[derive(Debug, Clone, StructOpt)]#[structopt(name = "Benchmarks", about = "Apache Arrow Rust Benchmarks.")]+enum ParquetBenchCmd {+ /// Benchmark sorting parquet files+ Sort(Opt),+ /// Benchmark parquet filter pushdown+ Filter(Opt),+}++#[derive(Debug, StructOpt, Clone)]struct Opt {/// Activate debug mode to see query results#[structopt(short, long)]@@ -50,7 +61,6 @@ struct Opt {/// Path to folder where access log file will be generated#[structopt(parse(from_os_str), required = true, short = "p", long = "path")]path: PathBuf,-/// Data page size of the generated parquet file#[structopt(long = "page-size")]page_size: Option<usize>,@@ -63,34 +73,144 @@ struct Opt {#[structopt(short = "s", long = "scale-factor", default_value = "1.0")]scale_factor: f32,}+impl Opt {+ /// Initialize parquet test file given options.+ fn init_file(&self) -> Result<parquet_test_utils::TestParquetFile> {+ let path = self.path.join("logs.parquet");-#[tokio::main]-async fn main() -> Result<()> {- let opt: Opt = Opt::from_args();- println!("Running benchmarks with the following options: {opt:?}");+ let mut props_builder = WriterProperties::builder();- let path = opt.path.join("logs.parquet");+ if let Some(s) = self.page_size {+ props_builder = props_builder+ .set_data_pagesize_limit(s)+ .set_write_batch_size(s);+ }- let mut props_builder = WriterProperties::builder();+ if let Some(s) = self.row_group_size {+ props_builder = props_builder.set_max_row_group_size(s);+ }- if let Some(s) = opt.page_size {- props_builder = props_builder- .set_data_pagesize_limit(s)- .set_write_batch_size(s);+ gen_data(path, self.scale_factor, props_builder.build())}+}- if let Some(s) = opt.row_group_size {- props_builder = props_builder.set_max_row_group_size(s);+#[tokio::main]+async fn main() -> Result<()> {+ let cmd = ParquetBenchCmd::from_args();+ match cmd {+ ParquetBenchCmd::Filter(opt) => {+ println!("running filter benchmarks");+ let test_file = opt.init_file()?;+ run_filter_benchmarks(opt, &test_file).await?;+ }+ ParquetBenchCmd::Sort(opt) => {+ println!("running sort benchmarks");+ let test_file = opt.init_file()?;+ run_sort_benchmarks(opt, &test_file).await?;+ }}-- let test_file = gen_data(path, opt.scale_factor, props_builder.build())?;-- run_benchmarks(opt, &test_file).await?;-Ok(())}-async fn run_benchmarks(opt: Opt, test_file: &TestParquetFile) -> Result<()> {+async fn run_sort_benchmarks(opt: Opt, test_file: &TestParquetFile) -> Result<()> {+ use datafusion::physical_expr::expressions::col;+ let schema = test_file.schema();+ let sort_cases = vec![+ (+ "sort utf8",+ vec![PhysicalSortExpr {+ expr: col("request_method", &schema)?,+ options: Default::default(),+ }],+ ),+ (+ "sort int",+ vec![PhysicalSortExpr {+ expr: col("request_bytes", &schema)?,+ options: Default::default(),+ }],+ ),+ (+ "sort decimal",+ vec![+ // sort decimal+ PhysicalSortExpr {+ expr: col("decimal_price", &schema)?,+ options: Default::default(),+ },+ ],+ ),+ (+ "sort integer tuple",+ vec![+ PhysicalSortExpr {+ expr: col("request_bytes", &schema)?,+ options: Default::default(),+ },+ PhysicalSortExpr {+ expr: col("response_bytes", &schema)?,+ options: Default::default(),+ },+ ],+ ),+ (+ "sort utf8 tuple",+ vec![+ // sort utf8 tuple+ PhysicalSortExpr {+ expr: col("service", &schema)?,+ options: Default::default(),+ },+ PhysicalSortExpr {+ expr: col("host", &schema)?,+ options: Default::default(),+ },+ PhysicalSortExpr {+ expr: col("pod", &schema)?,+ options: Default::default(),+ },+ PhysicalSortExpr {+ expr: col("image", &schema)?,+ options: Default::default(),+ },+ ],+ ),+ (+ "sort mixed tuple",+ vec![+ PhysicalSortExpr {+ expr: col("service", &schema)?,+ options: Default::default(),+ },+ PhysicalSortExpr {+ expr: col("request_bytes", &schema)?,+ options: Default::default(),+ },+ PhysicalSortExpr {+ expr: col("decimal_price", &schema)?,+ options: Default::default(),+ },+ ],+ ),+ ];+ for (title, expr) in sort_cases {+ println!("Executing '{title}' (sorting by: {expr:?})");+ for i in 0..opt.iterations {+ let config = SessionConfig::new().with_target_partitions(opt.partitions);+ let ctx = SessionContext::with_config(config);+ let start = Instant::now();+ exec_sort(&ctx, &expr, test_file, opt.debug).await?;+ println!(+ "Iteration {} finished in {} ms",+ i,+ start.elapsed().as_millis()+ );+ }+ println!("\n");+ }+ Ok(())+}+async fn run_filter_benchmarks(opt: Opt, test_file: &TestParquetFile) -> Result<()> {let scan_options_matrix = vec![ParquetScanOptions {pushdown_filters: false,@@ -167,7 +287,7 @@ async fn exec_scan(filter: Expr,debug: bool,) -> Result<usize> {- let exec = test_file.create_scan(filter).await?;+ let exec = test_file.create_scan(Some(filter)).await?;let task_ctx = ctx.task_ctx();let result = collect(exec, task_ctx).await?;@@ -178,6 +298,22 @@ async fn exec_scan(Ok(result.iter().map(|b| b.num_rows()).sum())}+async fn exec_sort(+ ctx: &SessionContext,+ expr: &[PhysicalSortExpr],+ test_file: &TestParquetFile,+ debug: bool,+) -> Result<()> {+ let scan = test_file.create_scan(None).await?;+ let exec = Arc::new(SortExec::try_new(expr.to_owned(), scan, None)?);+ let task_ctx = ctx.task_ctx();+ let result = collect(exec, task_ctx).await?;+ if debug {+ pretty::print_batches(&result)?;+ }+ Ok(())+}+fn gen_data(path: PathBuf,scale_factor: f32,diff --git a/datafusion/core/tests/parquet/filter_pushdown.rs b/datafusion/core/tests/parquet/filter_pushdown.rsindex f7f2241729..49481c1f33 100644--- a/datafusion/core/tests/parquet/filter_pushdown.rs+++ b/datafusion/core/tests/parquet/filter_pushdown.rs@@ -517,7 +517,7 @@ impl<'a> TestCase<'a> {let ctx = SessionContext::with_config(scan_options.config());let exec = self.test_parquet_file- .create_scan(filter.clone())+ .create_scan(Some(filter.clone())).await.unwrap();let result = collect(exec.clone(), ctx.task_ctx()).await.unwrap();diff --git a/parquet-test-utils/src/lib.rs b/parquet-test-utils/src/lib.rsindex 59c3024d78..cd8eab8ec5 100644--- a/parquet-test-utils/src/lib.rs+++ b/parquet-test-utils/src/lib.rs@@ -117,15 +117,22 @@ impl TestParquetFile {}impl TestParquetFile {- /// return a `ParquetExec` and `FilterExec` with the specified options to scan this parquet file.+ /// Return a `ParquetExec` with the specified options.///- /// This returns the same plan that DataFusion will make with a pushed down predicate followed by a filter:+ /// If `maybe_filter` is non-None, the ParquetExec will be filtered using+ /// the given expression, and this method will return the same plan that DataFusion+ /// will make with a pushed down predicate followed by a filter:////// ```text/// (FilterExec)/// (ParquetExec)/// ```- pub async fn create_scan(&self, filter: Expr) -> Result<Arc<dyn ExecutionPlan>> {+ ///+ /// Otherwise if `maybe_filter` is None, return just a `ParquetExec`+ pub async fn create_scan(+ &self,+ maybe_filter: Option<Expr>,+ ) -> Result<Arc<dyn ExecutionPlan>> {let scan_config = FileScanConfig {object_store_url: self.object_store_url.clone(),file_schema: self.schema.clone(),@@ -148,25 +155,26 @@ impl TestParquetFile {// run coercion on the filters to coerce types etc.let props = ExecutionProps::new();let context = SimplifyContext::new(&props).with_schema(df_schema.clone());- let simplifier = ExprSimplifier::new(context);- let filter = simplifier.coerce(filter, df_schema.clone()).unwrap();-- let physical_filter_expr = create_physical_expr(- &filter,- &df_schema,- self.schema.as_ref(),- &ExecutionProps::default(),- )?;-- let parquet_exec = Arc::new(ParquetExec::new(- scan_config,- Some(physical_filter_expr.clone()),- None,- ));-- let exec = Arc::new(FilterExec::try_new(physical_filter_expr, parquet_exec)?);-- Ok(exec)+ if let Some(filter) = maybe_filter {+ let simplifier = ExprSimplifier::new(context);+ let filter = simplifier.coerce(filter, df_schema.clone()).unwrap();+ let physical_filter_expr = create_physical_expr(+ &filter,+ &df_schema,+ self.schema.as_ref(),+ &ExecutionProps::default(),+ )?;+ let parquet_exec = Arc::new(ParquetExec::new(+ scan_config,+ Some(physical_filter_expr.clone()),+ None,+ ));++ let exec = Arc::new(FilterExec::try_new(physical_filter_expr, parquet_exec)?);+ Ok(exec)+ } else {+ Ok(Arc::new(ParquetExec::new(scan_config, None, None)))+ }}/// Retrieve metrics from the parquet exec returned from `create_scan`