Apache DataFusion SQL Query Engine
ARROW-11018: [Rust][DataFusion] Add support for column-level statistics, null count.
Heres, Daniel7f311bb7d9bf
diff --git a/rust/datafusion/src/datasource/datasource.rs b/rust/datafusion/src/datasource/datasource.rsindex e6590e8692..5e9cb0044d 100644--- a/rust/datafusion/src/datasource/datasource.rs+++ b/rust/datafusion/src/datasource/datasource.rs@@ -33,6 +33,14 @@ pub struct Statistics {pub num_rows: Option<usize>,/// total byte of the table rowspub total_byte_size: Option<usize>,+ /// Statistics on a column level+ pub column_statistics: Option<Vec<ColumnStatistics>>,+}+/// This table statistics are estimates about column+#[derive(Clone, Debug, PartialEq)]+pub struct ColumnStatistics {+ /// Number of null values on column+ pub null_count: Option<usize>,}/// Indicates whether and how a filter expression can be handled by adiff --git a/rust/datafusion/src/datasource/empty.rs b/rust/datafusion/src/datasource/empty.rsindex 52529c409e..c33572b24e 100644--- a/rust/datafusion/src/datasource/empty.rs+++ b/rust/datafusion/src/datasource/empty.rs@@ -73,6 +73,7 @@ impl TableProvider for EmptyTable {Statistics {num_rows: Some(0),total_byte_size: Some(0),+ column_statistics: None,}}}diff --git a/rust/datafusion/src/datasource/memory.rs b/rust/datafusion/src/datasource/memory.rsindex fe230abcb3..a3d7b0f1ac 100644--- a/rust/datafusion/src/datasource/memory.rs+++ b/rust/datafusion/src/datasource/memory.rs@@ -19,6 +19,7 @@//! queried by DataFusion. This allows data to be pre-loaded into memory and then//! repeatedly queried without incurring additional file I/O overhead.+use log::debug;use std::any::Any;use std::sync::Arc;@@ -33,6 +34,8 @@ use crate::physical_plan::common;use crate::physical_plan::memory::MemoryExec;use crate::physical_plan::ExecutionPlan;+use super::datasource::ColumnStatistics;+/// In-memory tablepub struct MemTable {schema: SchemaRef,@@ -40,6 +43,41 @@ pub struct MemTable {statistics: Statistics,}+// Calculates statistics based on partitions+fn calculate_statistics(+ schema: &SchemaRef,+ partitions: &Vec<Vec<RecordBatch>>,+) -> Statistics {+ let num_rows: usize = partitions+ .iter()+ .flat_map(|batches| batches.iter().map(RecordBatch::num_rows))+ .sum();++ let mut null_count: Vec<usize> = vec![0; schema.fields().len()];+ for partition in partitions.iter() {+ for batch in partition {+ for (i, array) in batch.columns().iter().enumerate() {+ null_count[i] += array.null_count();+ }+ }+ }++ let column_statistics = Some(+ null_count+ .iter()+ .map(|null_count| ColumnStatistics {+ null_count: Some(*null_count),+ })+ .collect(),+ );++ Statistics {+ num_rows: Some(num_rows),+ total_byte_size: None,+ column_statistics,+ }+}+impl MemTable {/// Create a new in-memory table from the provided schema and record batchespub fn try_new(schema: SchemaRef, partitions: Vec<Vec<RecordBatch>>) -> Result<Self> {@@ -48,17 +86,13 @@ impl MemTable {.flatten().all(|batches| batches.schema() == schema){- let num_rows: usize = partitions- .iter()- .flat_map(|batches| batches.iter().map(RecordBatch::num_rows))- .sum();+ let statistics = calculate_statistics(&schema, &partitions);+ debug!("MemTable statistics: {:?}", statistics);+Ok(Self {schema,batches: partitions,- statistics: Statistics {- num_rows: Some(num_rows),- total_byte_size: None,- },+ statistics,})} else {Err(DataFusionError::Plan(@@ -163,6 +197,7 @@ mod tests {Field::new("a", DataType::Int32, false),Field::new("b", DataType::Int32, false),Field::new("c", DataType::Int32, false),+ Field::new("d", DataType::Int32, true),]));let batch = RecordBatch::try_new(@@ -171,12 +206,30 @@ mod tests {Arc::new(Int32Array::from(vec![1, 2, 3])),Arc::new(Int32Array::from(vec![4, 5, 6])),Arc::new(Int32Array::from(vec![7, 8, 9])),+ Arc::new(Int32Array::from(vec![None, None, Some(9)])),],)?;let provider = MemTable::try_new(schema, vec![vec![batch]])?;assert_eq!(provider.statistics().num_rows, Some(3));+ assert_eq!(+ provider.statistics().column_statistics,+ Some(vec![+ ColumnStatistics {+ null_count: Some(0)+ },+ ColumnStatistics {+ null_count: Some(0)+ },+ ColumnStatistics {+ null_count: Some(0)+ },+ ColumnStatistics {+ null_count: Some(2)+ },+ ])+ );// scan with projectionlet exec = provider.scan(&Some(vec![2, 1]), 1024, &[])?;diff --git a/rust/datafusion/src/optimizer/hash_build_probe_order.rs b/rust/datafusion/src/optimizer/hash_build_probe_order.rsindex 179149b489..fddb63d246 100644--- a/rust/datafusion/src/optimizer/hash_build_probe_order.rs+++ b/rust/datafusion/src/optimizer/hash_build_probe_order.rs@@ -188,6 +188,7 @@ mod tests {Statistics {num_rows: Some(self.num_rows),total_byte_size: None,+ column_statistics: None,}}}diff --git a/rust/datafusion/src/physical_plan/parquet.rs b/rust/datafusion/src/physical_plan/parquet.rsindex d11fba2e15..c393941e8e 100644--- a/rust/datafusion/src/physical_plan/parquet.rs+++ b/rust/datafusion/src/physical_plan/parquet.rs@@ -129,6 +129,7 @@ impl ParquetExec {let statistics = Statistics {num_rows: Some(num_rows as usize),total_byte_size: Some(total_byte_size as usize),+ column_statistics: None,};partitions.push(ParquetPartition {filename: filename.to_owned().to_string(),@@ -184,6 +185,7 @@ impl ParquetExec {let statistics = Statistics {num_rows,total_byte_size,+ column_statistics: None,};Self {partitions,