Apache DataFusion SQL Query Engine
add correlation function (#1561)
Lin Mab7436103dd70
diff --git a/README.md b/README.mdindex 19ccdef31f..4cf35f5ec3 100644--- a/README.md+++ b/README.md@@ -268,7 +268,7 @@ This library currently supports many SQL constructs, including- `CAST` to change types, including e.g. `Timestamp(Nanosecond, None)`- Many mathematical unary and binary expressions such as `+`, `/`, `sqrt`, `tan`, `>=`.- `WHERE` to filter-- `GROUP BY` together with one of the following aggregations: `MIN`, `MAX`, `COUNT`, `SUM`, `AVG`, `VAR`, `COVAR`, `STDDEV` (sample and population)+- `GROUP BY` together with one of the following aggregations: `MIN`, `MAX`, `COUNT`, `SUM`, `AVG`, `CORR`, `VAR`, `COVAR`, `STDDEV` (sample and population)- `ORDER BY` together with an expression and optional `ASC` or `DESC` and also optional `NULLS FIRST` or `NULLS LAST`## Supported Functionsdiff --git a/ballista/rust/core/proto/ballista.proto b/ballista/rust/core/proto/ballista.protoindex cc6e00aa93..cdd27cfec9 100644--- a/ballista/rust/core/proto/ballista.proto+++ b/ballista/rust/core/proto/ballista.proto@@ -175,6 +175,7 @@ enum AggregateFunction {COVARIANCE_POP=10;STDDEV=11;STDDEV_POP=12;+ CORRELATION=13;}message AggregateExprNode {diff --git a/ballista/rust/core/src/serde/logical_plan/to_proto.rs b/ballista/rust/core/src/serde/logical_plan/to_proto.rsindex 36e9ba69ed..b783b545ef 100644--- a/ballista/rust/core/src/serde/logical_plan/to_proto.rs+++ b/ballista/rust/core/src/serde/logical_plan/to_proto.rs@@ -1049,6 +1049,9 @@ impl TryInto<protobuf::LogicalExprNode> for &Expr {AggregateFunction::StddevPop => {protobuf::AggregateFunction::StddevPop}+ AggregateFunction::Correlation => {+ protobuf::AggregateFunction::Correlation+ }};let arg = &args[0];@@ -1285,6 +1288,7 @@ impl From<&AggregateFunction> for protobuf::AggregateFunction {AggregateFunction::CovariancePop => Self::CovariancePop,AggregateFunction::Stddev => Self::Stddev,AggregateFunction::StddevPop => Self::StddevPop,+ AggregateFunction::Correlation => Self::Correlation,}}}diff --git a/ballista/rust/core/src/serde/mod.rs b/ballista/rust/core/src/serde/mod.rsindex 62246a0232..5f9950d9ad 100644--- a/ballista/rust/core/src/serde/mod.rs+++ b/ballista/rust/core/src/serde/mod.rs@@ -128,6 +128,7 @@ impl From<protobuf::AggregateFunction> for AggregateFunction {}protobuf::AggregateFunction::Stddev => AggregateFunction::Stddev,protobuf::AggregateFunction::StddevPop => AggregateFunction::StddevPop,+ protobuf::AggregateFunction::Correlation => AggregateFunction::Correlation,}}}diff --git a/datafusion/src/physical_plan/aggregates.rs b/datafusion/src/physical_plan/aggregates.rsindex 949dbb1e05..15bda30bbf 100644--- a/datafusion/src/physical_plan/aggregates.rs+++ b/datafusion/src/physical_plan/aggregates.rs@@ -36,8 +36,8 @@ use crate::physical_plan::distinct_expressions;use crate::physical_plan::expressions;use arrow::datatypes::{DataType, Field, Schema, TimeUnit};use expressions::{- avg_return_type, covariance_return_type, stddev_return_type, sum_return_type,- variance_return_type,+ avg_return_type, correlation_return_type, covariance_return_type, stddev_return_type,+ sum_return_type, variance_return_type,};use std::{fmt, str::FromStr, sync::Arc};@@ -79,6 +79,8 @@ pub enum AggregateFunction {Covariance,/// Covariance (Population)CovariancePop,+ /// Correlation+ Correlation,}impl fmt::Display for AggregateFunction {@@ -108,6 +110,7 @@ impl FromStr for AggregateFunction {"covar" => AggregateFunction::Covariance,"covar_samp" => AggregateFunction::Covariance,"covar_pop" => AggregateFunction::CovariancePop,+ "corr" => AggregateFunction::Correlation,_ => {return Err(DataFusionError::Plan(format!("There is no built-in function named {}",@@ -146,6 +149,7 @@ pub fn return_type(AggregateFunction::CovariancePop => {covariance_return_type(&coerced_data_types[0])}+ AggregateFunction::Correlation => correlation_return_type(&coerced_data_types[0]),AggregateFunction::Stddev => stddev_return_type(&coerced_data_types[0]),AggregateFunction::StddevPop => stddev_return_type(&coerced_data_types[0]),AggregateFunction::Avg => avg_return_type(&coerced_data_types[0]),@@ -315,6 +319,19 @@ pub fn create_aggregate_expr("STDDEV_POP(DISTINCT) aggregations are not available".to_string(),));}+ (AggregateFunction::Correlation, false) => {+ Arc::new(expressions::Correlation::new(+ coerced_phy_exprs[0].clone(),+ coerced_phy_exprs[1].clone(),+ name,+ return_type,+ ))+ }+ (AggregateFunction::Correlation, true) => {+ return Err(DataFusionError::NotImplemented(+ "CORR(DISTINCT) aggregations are not available".to_string(),+ ));+ }})}@@ -370,6 +387,9 @@ pub fn signature(fun: &AggregateFunction) -> Signature {AggregateFunction::Covariance | AggregateFunction::CovariancePop => {Signature::uniform(2, NUMERICS.to_vec(), Volatility::Immutable)}+ AggregateFunction::Correlation => {+ Signature::uniform(2, NUMERICS.to_vec(), Volatility::Immutable)+ }}}@@ -380,7 +400,8 @@ mod tests {use crate::error::Result;use crate::physical_plan::distinct_expressions::DistinctCount;use crate::physical_plan::expressions::{- ApproxDistinct, ArrayAgg, Avg, Count, Max, Min, Stddev, Sum, Variance,+ ApproxDistinct, ArrayAgg, Avg, Correlation, Count, Covariance, Max, Min, Stddev,+ Sum, Variance,};#[test]@@ -760,6 +781,147 @@ mod tests {Ok(())}+ #[test]+ fn test_covar_expr() -> Result<()> {+ let funcs = vec![AggregateFunction::Covariance];+ let data_types = vec![+ DataType::UInt32,+ DataType::UInt64,+ DataType::Int32,+ DataType::Int64,+ DataType::Float32,+ DataType::Float64,+ ];+ for fun in funcs {+ for data_type in &data_types {+ let input_schema = Schema::new(vec![+ Field::new("c1", data_type.clone(), true),+ Field::new("c2", data_type.clone(), true),+ ]);+ let input_phy_exprs: Vec<Arc<dyn PhysicalExpr>> = vec![+ Arc::new(+ expressions::Column::new_with_schema("c1", &input_schema)+ .unwrap(),+ ),+ Arc::new(+ expressions::Column::new_with_schema("c2", &input_schema)+ .unwrap(),+ ),+ ];+ let result_agg_phy_exprs = create_aggregate_expr(+ &fun,+ false,+ &input_phy_exprs[0..2],+ &input_schema,+ "c1",+ )?;+ if fun == AggregateFunction::Covariance {+ assert!(result_agg_phy_exprs.as_any().is::<Covariance>());+ assert_eq!("c1", result_agg_phy_exprs.name());+ assert_eq!(+ Field::new("c1", DataType::Float64, true),+ result_agg_phy_exprs.field().unwrap()+ )+ }+ }+ }+ Ok(())+ }++ #[test]+ fn test_covar_pop_expr() -> Result<()> {+ let funcs = vec![AggregateFunction::CovariancePop];+ let data_types = vec![+ DataType::UInt32,+ DataType::UInt64,+ DataType::Int32,+ DataType::Int64,+ DataType::Float32,+ DataType::Float64,+ ];+ for fun in funcs {+ for data_type in &data_types {+ let input_schema = Schema::new(vec![+ Field::new("c1", data_type.clone(), true),+ Field::new("c2", data_type.clone(), true),+ ]);+ let input_phy_exprs: Vec<Arc<dyn PhysicalExpr>> = vec![+ Arc::new(+ expressions::Column::new_with_schema("c1", &input_schema)+ .unwrap(),+ ),+ Arc::new(+ expressions::Column::new_with_schema("c2", &input_schema)+ .unwrap(),+ ),+ ];+ let result_agg_phy_exprs = create_aggregate_expr(+ &fun,+ false,+ &input_phy_exprs[0..2],+ &input_schema,+ "c1",+ )?;+ if fun == AggregateFunction::Covariance {+ assert!(result_agg_phy_exprs.as_any().is::<Covariance>());+ assert_eq!("c1", result_agg_phy_exprs.name());+ assert_eq!(+ Field::new("c1", DataType::Float64, true),+ result_agg_phy_exprs.field().unwrap()+ )+ }+ }+ }+ Ok(())+ }++ #[test]+ fn test_corr_expr() -> Result<()> {+ let funcs = vec![AggregateFunction::Correlation];+ let data_types = vec![+ DataType::UInt32,+ DataType::UInt64,+ DataType::Int32,+ DataType::Int64,+ DataType::Float32,+ DataType::Float64,+ ];+ for fun in funcs {+ for data_type in &data_types {+ let input_schema = Schema::new(vec![+ Field::new("c1", data_type.clone(), true),+ Field::new("c2", data_type.clone(), true),+ ]);+ let input_phy_exprs: Vec<Arc<dyn PhysicalExpr>> = vec![+ Arc::new(+ expressions::Column::new_with_schema("c1", &input_schema)+ .unwrap(),+ ),+ Arc::new(+ expressions::Column::new_with_schema("c2", &input_schema)+ .unwrap(),+ ),+ ];+ let result_agg_phy_exprs = create_aggregate_expr(+ &fun,+ false,+ &input_phy_exprs[0..2],+ &input_schema,+ "c1",+ )?;+ if fun == AggregateFunction::Covariance {+ assert!(result_agg_phy_exprs.as_any().is::<Correlation>());+ assert_eq!("c1", result_agg_phy_exprs.name());+ assert_eq!(+ Field::new("c1", DataType::Float64, true),+ result_agg_phy_exprs.field().unwrap()+ )+ }+ }+ }+ Ok(())+ }+#[test]fn test_min_max() -> Result<()> {let observed = return_type(&AggregateFunction::Min, &[DataType::Utf8])?;diff --git a/datafusion/src/physical_plan/coercion_rule/aggregate_rule.rs b/datafusion/src/physical_plan/coercion_rule/aggregate_rule.rsindex 2b02ba0eba..c151fb70a0 100644--- a/datafusion/src/physical_plan/coercion_rule/aggregate_rule.rs+++ b/datafusion/src/physical_plan/coercion_rule/aggregate_rule.rs@@ -21,8 +21,9 @@ use crate::arrow::datatypes::Schema;use crate::error::{DataFusionError, Result};use crate::physical_plan::aggregates::AggregateFunction;use crate::physical_plan::expressions::{- is_avg_support_arg_type, is_covariance_support_arg_type, is_stddev_support_arg_type,- is_sum_support_arg_type, is_variance_support_arg_type, try_cast,+ is_avg_support_arg_type, is_correlation_support_arg_type,+ is_covariance_support_arg_type, is_stddev_support_arg_type, is_sum_support_arg_type,+ is_variance_support_arg_type, try_cast,};use crate::physical_plan::functions::{Signature, TypeSignature};use crate::physical_plan::PhysicalExpr;@@ -141,6 +142,15 @@ pub(crate) fn coerce_types(}Ok(input_types.to_vec())}+ AggregateFunction::Correlation => {+ if !is_correlation_support_arg_type(&input_types[0]) {+ return Err(DataFusionError::Plan(format!(+ "The function {:?} does not support inputs of type {:?}.",+ agg_fun, input_types[0]+ )));+ }+ Ok(input_types.to_vec())+ }}}diff --git a/datafusion/src/physical_plan/expressions/correlation.rs b/datafusion/src/physical_plan/expressions/correlation.rsnew file mode 100644index 0000000000..7ac534e3f2--- /dev/null+++ b/datafusion/src/physical_plan/expressions/correlation.rs@@ -0,0 +1,550 @@+// Licensed to the Apache Software Foundation (ASF) under one+// or more contributor license agreements. See the NOTICE file+// distributed with this work for additional information+// regarding copyright ownership. The ASF licenses this file+// to you under the Apache License, Version 2.0 (the+// "License"); you may not use this file except in compliance+// with the License. You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing,+// software distributed under the License is distributed on an+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+// KIND, either express or implied. See the License for the+// specific language governing permissions and limitations+// under the License.++//! Defines physical expressions that can evaluated at runtime during query execution++use std::any::Any;+use std::sync::Arc;++use crate::error::{DataFusionError, Result};+use crate::physical_plan::{+ expressions::{covariance::CovarianceAccumulator, stddev::StddevAccumulator},+ Accumulator, AggregateExpr, PhysicalExpr,+};+use crate::scalar::ScalarValue;+use arrow::{array::ArrayRef, datatypes::DataType, datatypes::Field};++use super::{format_state_name, StatsType};++/// CORR aggregate expression+#[derive(Debug)]+pub struct Correlation {+ name: String,+ expr1: Arc<dyn PhysicalExpr>,+ expr2: Arc<dyn PhysicalExpr>,+}++/// function return type of correlation+pub(crate) fn correlation_return_type(arg_type: &DataType) -> Result<DataType> {+ match arg_type {+ DataType::Int8+ | DataType::Int16+ | DataType::Int32+ | DataType::Int64+ | DataType::UInt8+ | DataType::UInt16+ | DataType::UInt32+ | DataType::UInt64+ | DataType::Float32+ | DataType::Float64 => Ok(DataType::Float64),+ other => Err(DataFusionError::Plan(format!(+ "CORR does not support {:?}",+ other+ ))),+ }+}++pub(crate) fn is_correlation_support_arg_type(arg_type: &DataType) -> bool {+ matches!(+ arg_type,+ DataType::UInt8+ | DataType::UInt16+ | DataType::UInt32+ | DataType::UInt64+ | DataType::Int8+ | DataType::Int16+ | DataType::Int32+ | DataType::Int64+ | DataType::Float32+ | DataType::Float64+ )+}++impl Correlation {+ /// Create a new COVAR_POP aggregate function+ pub fn new(+ expr1: Arc<dyn PhysicalExpr>,+ expr2: Arc<dyn PhysicalExpr>,+ name: impl Into<String>,+ data_type: DataType,+ ) -> Self {+ // the result of correlation just support FLOAT64 data type.+ assert!(matches!(data_type, DataType::Float64));+ Self {+ name: name.into(),+ expr1,+ expr2,+ }+ }+}++impl AggregateExpr for Correlation {+ /// Return a reference to Any that can be used for downcasting+ fn as_any(&self) -> &dyn Any {+ self+ }++ fn field(&self) -> Result<Field> {+ Ok(Field::new(&self.name, DataType::Float64, true))+ }++ fn create_accumulator(&self) -> Result<Box<dyn Accumulator>> {+ Ok(Box::new(CorrelationAccumulator::try_new()?))+ }++ fn state_fields(&self) -> Result<Vec<Field>> {+ Ok(vec![+ Field::new(+ &format_state_name(&self.name, "count"),+ DataType::UInt64,+ true,+ ),+ Field::new(+ &format_state_name(&self.name, "mean1"),+ DataType::Float64,+ true,+ ),+ Field::new(+ &format_state_name(&self.name, "m2_1"),+ DataType::Float64,+ true,+ ),+ Field::new(+ &format_state_name(&self.name, "mean2"),+ DataType::Float64,+ true,+ ),+ Field::new(+ &format_state_name(&self.name, "m2_2"),+ DataType::Float64,+ true,+ ),+ Field::new(+ &format_state_name(&self.name, "algo_const"),+ DataType::Float64,+ true,+ ),+ ])+ }++ fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {+ vec![self.expr1.clone(), self.expr2.clone()]+ }++ fn name(&self) -> &str {+ &self.name+ }+}++/// An accumulator to compute correlation+#[derive(Debug)]+pub struct CorrelationAccumulator {+ covar: CovarianceAccumulator,+ stddev1: StddevAccumulator,+ stddev2: StddevAccumulator,+}++impl CorrelationAccumulator {+ /// Creates a new `CorrelationAccumulator`+ pub fn try_new() -> Result<Self> {+ Ok(Self {+ covar: CovarianceAccumulator::try_new(StatsType::Population)?,+ stddev1: StddevAccumulator::try_new(StatsType::Population)?,+ stddev2: StddevAccumulator::try_new(StatsType::Population)?,+ })+ }+}++impl Accumulator for CorrelationAccumulator {+ fn state(&self) -> Result<Vec<ScalarValue>> {+ Ok(vec![+ ScalarValue::from(self.covar.get_count()),+ ScalarValue::from(self.covar.get_mean1()),+ ScalarValue::from(self.stddev1.get_m2()),+ ScalarValue::from(self.covar.get_mean2()),+ ScalarValue::from(self.stddev2.get_m2()),+ ScalarValue::from(self.covar.get_algo_const()),+ ])+ }++ fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {+ self.covar.update_batch(values)?;+ self.stddev1.update_batch(&[values[0].clone()])?;+ self.stddev2.update_batch(&[values[1].clone()])?;+ Ok(())+ }++ fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {+ let states_c = [+ states[0].clone(),+ states[1].clone(),+ states[3].clone(),+ states[5].clone(),+ ];+ let states_s1 = [states[0].clone(), states[1].clone(), states[2].clone()];+ let states_s2 = [states[0].clone(), states[3].clone(), states[4].clone()];++ self.covar.merge_batch(&states_c)?;+ self.stddev1.merge_batch(&states_s1)?;+ self.stddev2.merge_batch(&states_s2)?;+ Ok(())+ }++ fn update(&mut self, _values: &[ScalarValue]) -> Result<()> {+ unimplemented!("update_batch is implemented instead");+ }++ fn merge(&mut self, _states: &[ScalarValue]) -> Result<()> {+ unimplemented!("merge_batch is implemented instead");+ }++ fn evaluate(&self) -> Result<ScalarValue> {+ let covar = self.covar.evaluate()?;+ let stddev1 = self.stddev1.evaluate()?;+ let stddev2 = self.stddev2.evaluate()?;++ if let ScalarValue::Float64(Some(c)) = covar {+ if let ScalarValue::Float64(Some(s1)) = stddev1 {+ if let ScalarValue::Float64(Some(s2)) = stddev2 {+ if s1 == 0_f64 || s2 == 0_f64 {+ return Ok(ScalarValue::Float64(Some(0_f64)));+ } else {+ return Ok(ScalarValue::Float64(Some(c / s1 / s2)));+ }+ }+ }+ }++ Ok(ScalarValue::Float64(None))+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::physical_plan::expressions::col;+ use crate::{error::Result, generic_test_op2};+ use arrow::record_batch::RecordBatch;+ use arrow::{array::*, datatypes::*};++ #[test]+ fn correlation_f64_1() -> Result<()> {+ let a: ArrayRef = Arc::new(Float64Array::from(vec![1_f64, 2_f64, 3_f64]));+ let b: ArrayRef = Arc::new(Float64Array::from(vec![4_f64, 5_f64, 7_f64]));++ generic_test_op2!(+ a,+ b,+ DataType::Float64,+ DataType::Float64,+ Correlation,+ ScalarValue::from(0.9819805060619659),+ DataType::Float64+ )+ }++ #[test]+ fn correlation_f64_2() -> Result<()> {+ let a: ArrayRef = Arc::new(Float64Array::from(vec![1_f64, 2_f64, 3_f64]));+ let b: ArrayRef = Arc::new(Float64Array::from(vec![4_f64, -5_f64, 6_f64]));++ generic_test_op2!(+ a,+ b,+ DataType::Float64,+ DataType::Float64,+ Correlation,+ ScalarValue::from(0.17066403719657236),+ DataType::Float64+ )+ }++ #[test]+ fn correlation_f64_4() -> Result<()> {+ let a: ArrayRef = Arc::new(Float64Array::from(vec![1.1_f64, 2_f64, 3_f64]));+ let b: ArrayRef = Arc::new(Float64Array::from(vec![4.1_f64, 5_f64, 6_f64]));++ generic_test_op2!(+ a,+ b,+ DataType::Float64,+ DataType::Float64,+ Correlation,+ ScalarValue::from(1_f64),+ DataType::Float64+ )+ }++ #[test]+ fn correlation_f64_6() -> Result<()> {+ let a = Arc::new(Float64Array::from(vec![+ 1_f64, 2_f64, 3_f64, 1.1_f64, 2.2_f64, 3.3_f64,+ ]));+ let b = Arc::new(Float64Array::from(vec![+ 4_f64, 5_f64, 6_f64, 4.4_f64, 5.5_f64, 6.6_f64,+ ]));++ generic_test_op2!(+ a,+ b,+ DataType::Float64,+ DataType::Float64,+ Correlation,+ ScalarValue::from(0.9860135594710389),+ DataType::Float64+ )+ }++ #[test]+ fn correlation_i32() -> Result<()> {+ let a: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3]));+ let b: ArrayRef = Arc::new(Int32Array::from(vec![4, 5, 6]));++ generic_test_op2!(+ a,+ b,+ DataType::Int32,+ DataType::Int32,+ Correlation,+ ScalarValue::from(1_f64),+ DataType::Float64+ )+ }++ #[test]+ fn correlation_u32() -> Result<()> {+ let a: ArrayRef = Arc::new(UInt32Array::from(vec![1_u32, 2_u32, 3_u32]));+ let b: ArrayRef = Arc::new(UInt32Array::from(vec![4_u32, 5_u32, 6_u32]));+ generic_test_op2!(+ a,+ b,+ DataType::UInt32,+ DataType::UInt32,+ Correlation,+ ScalarValue::from(1_f64),+ DataType::Float64+ )+ }++ #[test]+ fn correlation_f32() -> Result<()> {+ let a: ArrayRef = Arc::new(Float32Array::from(vec![1_f32, 2_f32, 3_f32]));+ let b: ArrayRef = Arc::new(Float32Array::from(vec![4_f32, 5_f32, 6_f32]));+ generic_test_op2!(+ a,+ b,+ DataType::Float32,+ DataType::Float32,+ Correlation,+ ScalarValue::from(1_f64),+ DataType::Float64+ )+ }++ #[test]+ fn test_correlation_return_data_type() -> Result<()> {+ let data_type = DataType::Float64;+ let result_type = correlation_return_type(&data_type)?;+ assert_eq!(DataType::Float64, result_type);++ let data_type = DataType::Decimal(36, 10);+ assert!(correlation_return_type(&data_type).is_err());+ Ok(())+ }++ #[test]+ fn correlation_i32_with_nulls_1() -> Result<()> {+ let a: ArrayRef =+ Arc::new(Int32Array::from(vec![Some(1), None, Some(3), Some(3)]));+ let b: ArrayRef =+ Arc::new(Int32Array::from(vec![Some(4), None, Some(6), Some(3)]));++ generic_test_op2!(+ a,+ b,+ DataType::Int32,+ DataType::Int32,+ Correlation,+ ScalarValue::from(0.1889822365046137),+ DataType::Float64+ )+ }++ #[test]+ fn correlation_i32_with_nulls_2() -> Result<()> {+ let a: ArrayRef = Arc::new(Int32Array::from(vec![Some(1), None, Some(3)]));+ let b: ArrayRef = Arc::new(Int32Array::from(vec![Some(4), Some(5), Some(6)]));++ let schema = Schema::new(vec![+ Field::new("a", DataType::Int32, false),+ Field::new("b", DataType::Int32, false),+ ]);+ let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![a, b])?;++ let agg = Arc::new(Correlation::new(+ col("a", &schema)?,+ col("b", &schema)?,+ "bla".to_string(),+ DataType::Float64,+ ));+ let actual = aggregate(&batch, agg);+ assert!(actual.is_err());++ Ok(())+ }++ #[test]+ fn correlation_i32_all_nulls() -> Result<()> {+ let a: ArrayRef = Arc::new(Int32Array::from(vec![None, None]));+ let b: ArrayRef = Arc::new(Int32Array::from(vec![None, None]));++ let schema = Schema::new(vec![+ Field::new("a", DataType::Int32, false),+ Field::new("b", DataType::Int32, false),+ ]);+ let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![a, b])?;++ let agg = Arc::new(Correlation::new(+ col("a", &schema)?,+ col("b", &schema)?,+ "bla".to_string(),+ DataType::Float64,+ ));+ let actual = aggregate(&batch, agg);+ assert!(actual.is_err());++ Ok(())+ }++ #[test]+ fn correlation_f64_merge_1() -> Result<()> {+ let a = Arc::new(Float64Array::from(vec![1_f64, 2_f64, 3_f64]));+ let b = Arc::new(Float64Array::from(vec![4_f64, 5_f64, 6_f64]));+ let c = Arc::new(Float64Array::from(vec![1.1_f64, 2.2_f64, 3.3_f64]));+ let d = Arc::new(Float64Array::from(vec![4.4_f64, 5.5_f64, 9.9_f64]));++ let schema = Schema::new(vec![+ Field::new("a", DataType::Float64, false),+ Field::new("b", DataType::Float64, false),+ ]);++ let batch1 = RecordBatch::try_new(Arc::new(schema.clone()), vec![a, b])?;+ let batch2 = RecordBatch::try_new(Arc::new(schema.clone()), vec![c, d])?;++ let agg1 = Arc::new(Correlation::new(+ col("a", &schema)?,+ col("b", &schema)?,+ "bla".to_string(),+ DataType::Float64,+ ));++ let agg2 = Arc::new(Correlation::new(+ col("a", &schema)?,+ col("b", &schema)?,+ "bla".to_string(),+ DataType::Float64,+ ));++ let actual = merge(&batch1, &batch2, agg1, agg2)?;+ assert!(actual == ScalarValue::from(0.8443707186481967));++ Ok(())+ }++ #[test]+ fn correlation_f64_merge_2() -> Result<()> {+ let a = Arc::new(Float64Array::from(vec![1_f64, 2_f64, 3_f64]));+ let b = Arc::new(Float64Array::from(vec![4_f64, 5_f64, 6_f64]));+ let c = Arc::new(Float64Array::from(vec![None]));+ let d = Arc::new(Float64Array::from(vec![None]));++ let schema = Schema::new(vec![+ Field::new("a", DataType::Float64, false),+ Field::new("b", DataType::Float64, false),+ ]);++ let batch1 = RecordBatch::try_new(Arc::new(schema.clone()), vec![a, b])?;+ let batch2 = RecordBatch::try_new(Arc::new(schema.clone()), vec![c, d])?;++ let agg1 = Arc::new(Correlation::new(+ col("a", &schema)?,+ col("b", &schema)?,+ "bla".to_string(),+ DataType::Float64,+ ));++ let agg2 = Arc::new(Correlation::new(+ col("a", &schema)?,+ col("b", &schema)?,+ "bla".to_string(),+ DataType::Float64,+ ));++ let actual = merge(&batch1, &batch2, agg1, agg2)?;+ assert!(actual == ScalarValue::from(1_f64));++ Ok(())+ }++ fn aggregate(+ batch: &RecordBatch,+ agg: Arc<dyn AggregateExpr>,+ ) -> Result<ScalarValue> {+ let mut accum = agg.create_accumulator()?;+ let expr = agg.expressions();+ let values = expr+ .iter()+ .map(|e| e.evaluate(batch))+ .map(|r| r.map(|v| v.into_array(batch.num_rows())))+ .collect::<Result<Vec<_>>>()?;+ accum.update_batch(&values)?;+ accum.evaluate()+ }++ fn merge(+ batch1: &RecordBatch,+ batch2: &RecordBatch,+ agg1: Arc<dyn AggregateExpr>,+ agg2: Arc<dyn AggregateExpr>,+ ) -> Result<ScalarValue> {+ let mut accum1 = agg1.create_accumulator()?;+ let mut accum2 = agg2.create_accumulator()?;+ let expr1 = agg1.expressions();+ let expr2 = agg2.expressions();++ let values1 = expr1+ .iter()+ .map(|e| e.evaluate(batch1))+ .map(|r| r.map(|v| v.into_array(batch1.num_rows())))+ .collect::<Result<Vec<_>>>()?;+ let values2 = expr2+ .iter()+ .map(|e| e.evaluate(batch2))+ .map(|r| r.map(|v| v.into_array(batch2.num_rows())))+ .collect::<Result<Vec<_>>>()?;+ accum1.update_batch(&values1)?;+ accum2.update_batch(&values2)?;+ let state2 = accum2+ .state()?+ .iter()+ .map(|v| vec![v.clone()])+ .map(|x| ScalarValue::iter_to_array(x).unwrap())+ .collect::<Vec<_>>();+ accum1.merge_batch(&state2)?;+ accum1.evaluate()+ }+}diff --git a/datafusion/src/physical_plan/expressions/covariance.rs b/datafusion/src/physical_plan/expressions/covariance.rsindex 454dc43517..6b9e296619 100644--- a/datafusion/src/physical_plan/expressions/covariance.rs+++ b/datafusion/src/physical_plan/expressions/covariance.rs@@ -63,7 +63,7 @@ pub(crate) fn covariance_return_type(arg_type: &DataType) -> Result<DataType> {| DataType::Float32| DataType::Float64 => Ok(DataType::Float64),other => Err(DataFusionError::Plan(format!(- "VARIANCE does not support {:?}",+ "COVAR does not support {:?}",other))),}@@ -253,22 +253,21 @@ impl CovarianceAccumulator {})}- // These functions are commented out for now, they will be used in the next PR- // pub fn get_count(&self) -> u64 {- // self.count- // }+ pub fn get_count(&self) -> u64 {+ self.count+ }- // pub fn get_mean1(&self) -> f64 {- // self.mean1- // }+ pub fn get_mean1(&self) -> f64 {+ self.mean1+ }- // pub fn get_mean2(&self) -> f64 {- // self.mean2- // }+ pub fn get_mean2(&self) -> f64 {+ self.mean2+ }- // pub fn get_algo_const(&self) -> f64 {- // self.algo_const- // }+ pub fn get_algo_const(&self) -> f64 {+ self.algo_const+ }}impl Accumulator for CovarianceAccumulator {diff --git a/datafusion/src/physical_plan/expressions/mod.rs b/datafusion/src/physical_plan/expressions/mod.rsindex 2200ee03d5..cf2b3331bf 100644--- a/datafusion/src/physical_plan/expressions/mod.rs+++ b/datafusion/src/physical_plan/expressions/mod.rs@@ -44,6 +44,7 @@ mod lead_lag;mod literal;#[macro_use]mod min_max;+mod correlation;mod covariance;mod negative;mod not;@@ -72,6 +73,9 @@ pub use cast::{cast, cast_column, cast_with_options, CastExpr, DEFAULT_DATAFUSION_CAST_OPTIONS,};pub use column::{col, Column};+pub(crate) use correlation::{+ correlation_return_type, is_correlation_support_arg_type, Correlation,+};pub use count::Count;pub(crate) use covariance::{covariance_return_type, is_covariance_support_arg_type, Covariance, CovariancePop,diff --git a/datafusion/src/physical_plan/expressions/stddev.rs b/datafusion/src/physical_plan/expressions/stddev.rsindex 191ac07ecf..a4c24fc042 100644--- a/datafusion/src/physical_plan/expressions/stddev.rs+++ b/datafusion/src/physical_plan/expressions/stddev.rs@@ -209,6 +209,10 @@ impl StddevAccumulator {variance: VarianceAccumulator::try_new(s_type)?,})}++ pub fn get_m2(&self) -> f64 {+ self.variance.get_m2()+ }}impl Accumulator for StddevAccumulator {diff --git a/datafusion/src/physical_plan/expressions/variance.rs b/datafusion/src/physical_plan/expressions/variance.rsindex 117350c69c..5e7d01aff6 100644--- a/datafusion/src/physical_plan/expressions/variance.rs+++ b/datafusion/src/physical_plan/expressions/variance.rs@@ -61,7 +61,7 @@ pub(crate) fn variance_return_type(arg_type: &DataType) -> Result<DataType> {| DataType::Float32| DataType::Float64 => Ok(DataType::Float64),other => Err(DataFusionError::Plan(format!(- "VARIANCE does not support {:?}",+ "VAR does not support {:?}",other))),}diff --git a/datafusion/tests/sql/aggregates.rs b/datafusion/tests/sql/aggregates.rsindex 7caedaacf5..785d3084ad 100644--- a/datafusion/tests/sql/aggregates.rs+++ b/datafusion/tests/sql/aggregates.rs@@ -74,6 +74,18 @@ async fn csv_query_covariance_2() -> Result<()> {Ok(())}+#[tokio::test]+async fn csv_query_correlation() -> Result<()> {+ let mut ctx = ExecutionContext::new();+ register_aggregate_csv(&mut ctx).await?;+ let sql = "SELECT corr(c2, c12) FROM aggregate_test_100";+ let mut actual = execute(&mut ctx, sql).await;+ actual.sort();+ let expected = vec![vec!["-0.19064544190576607"]];+ assert_float_eq(&expected, &actual);+ Ok(())+}+#[tokio::test]async fn csv_query_variance_1() -> Result<()> {let mut ctx = ExecutionContext::new();