Skip to content

Apache DataFusion SQL Query Engine

#2004 approx percentile with weight (#2031)

Riche8ed603c6d91
diff --git a/datafusion-expr/src/aggregate_function.rs b/datafusion-expr/src/aggregate_function.rs
index 87b666ffb3..545155ca9d 100644
--- a/datafusion-expr/src/aggregate_function.rs
+++ b/datafusion-expr/src/aggregate_function.rs
@@ -53,6 +53,8 @@ pub enum AggregateFunction {
Correlation,
/// Approximate continuous percentile function
ApproxPercentileCont,
+ /// Approximate continuous percentile function with weight
+ ApproxPercentileContWithWeight,
/// ApproxMedian
ApproxMedian,
}
@@ -86,6 +88,9 @@ impl FromStr for AggregateFunction {
"covar_pop" => AggregateFunction::CovariancePop,
"corr" => AggregateFunction::Correlation,
"approx_percentile_cont" => AggregateFunction::ApproxPercentileCont,
+ "approx_percentile_cont_with_weight" => {
+ AggregateFunction::ApproxPercentileContWithWeight
+ }
"approx_median" => AggregateFunction::ApproxMedian,
_ => {
return Err(DataFusionError::Plan(format!(
diff --git a/datafusion-expr/src/expr_fn.rs b/datafusion-expr/src/expr_fn.rs
index a5c302c5f6..9d6fb7f93c 100644
--- a/datafusion-expr/src/expr_fn.rs
+++ b/datafusion-expr/src/expr_fn.rs
@@ -166,6 +166,19 @@ pub fn approx_percentile_cont(expr: Expr, percentile: Expr) -> Expr {
}
}
+/// Calculate an approximation of the specified `percentile` for `expr` and `weight_expr`.
+pub fn approx_percentile_cont_with_weight(
+ expr: Expr,
+ weight_expr: Expr,
+ percentile: Expr,
+) -> Expr {
+ Expr::AggregateFunction {
+ fun: aggregate_function::AggregateFunction::ApproxPercentileContWithWeight,
+ distinct: false,
+ args: vec![expr, weight_expr, percentile],
+ }
+}
+
// TODO(kszucs): this seems buggy, unary_scalar_expr! is used for many
// varying arity functions
/// Create an convenience function representing a unary scalar function
diff --git a/datafusion-physical-expr/src/coercion_rule/aggregate_rule.rs b/datafusion-physical-expr/src/coercion_rule/aggregate_rule.rs
index 279fe7d31b..9b3920ddfd 100644
--- a/datafusion-physical-expr/src/coercion_rule/aggregate_rule.rs
+++ b/datafusion-physical-expr/src/coercion_rule/aggregate_rule.rs
@@ -152,6 +152,27 @@ pub fn coerce_types(
}
Ok(input_types.to_vec())
}
+ AggregateFunction::ApproxPercentileContWithWeight => {
+ if !is_approx_percentile_cont_supported_arg_type(&input_types[0]) {
+ return Err(DataFusionError::Plan(format!(
+ "The function {:?} does not support inputs of type {:?}.",
+ agg_fun, input_types[0]
+ )));
+ }
+ if !is_approx_percentile_cont_supported_arg_type(&input_types[1]) {
+ return Err(DataFusionError::Plan(format!(
+ "The weight argument for {:?} does not support inputs of type {:?}.",
+ agg_fun, input_types[1]
+ )));
+ }
+ if !matches!(input_types[2], DataType::Float64) {
+ return Err(DataFusionError::Plan(format!(
+ "The percentile argument for {:?} must be Float64, not {:?}.",
+ agg_fun, input_types[2]
+ )));
+ }
+ Ok(input_types.to_vec())
+ }
AggregateFunction::ApproxMedian => {
if !is_approx_percentile_cont_supported_arg_type(&input_types[0]) {
return Err(DataFusionError::Plan(format!(
diff --git a/datafusion-physical-expr/src/expressions/approx_percentile_cont.rs b/datafusion-physical-expr/src/expressions/approx_percentile_cont.rs
index 77d82cf49a..395a43f5bf 100644
--- a/datafusion-physical-expr/src/expressions/approx_percentile_cont.rs
+++ b/datafusion-physical-expr/src/expressions/approx_percentile_cont.rs
@@ -16,7 +16,11 @@
// under the License.
use super::{format_state_name, Literal};
-use crate::{tdigest::TDigest, AggregateExpr, PhysicalExpr};
+use crate::tdigest::TryIntoOrderedF64;
+use crate::{
+ tdigest::{TDigest, DEFAULT_MAX_SIZE},
+ AggregateExpr, PhysicalExpr,
+};
use arrow::{
array::{
ArrayRef, Float32Array, Float64Array, Int16Array, Int32Array, Int64Array,
@@ -28,6 +32,7 @@ use datafusion_common::DataFusionError;
use datafusion_common::Result;
use datafusion_common::ScalarValue;
use datafusion_expr::Accumulator;
+use ordered_float::OrderedFloat;
use std::{any::Any, iter, sync::Arc};
/// Return `true` if `arg_type` is of a [`DataType`] that the
@@ -102,6 +107,30 @@ impl ApproxPercentileCont {
percentile,
})
}
+
+ pub(crate) fn create_plain_accumulator(&self) -> Result<ApproxPercentileAccumulator> {
+ let accumulator: ApproxPercentileAccumulator = match &self.input_data_type {
+ t @ (DataType::UInt8
+ | DataType::UInt16
+ | DataType::UInt32
+ | DataType::UInt64
+ | DataType::Int8
+ | DataType::Int16
+ | DataType::Int32
+ | DataType::Int64
+ | DataType::Float32
+ | DataType::Float64) => {
+ ApproxPercentileAccumulator::new(self.percentile, t.clone())
+ }
+ other => {
+ return Err(DataFusionError::NotImplemented(format!(
+ "Support for 'APPROX_PERCENTILE_CONT' for data type {} is not implemented",
+ other
+ )))
+ }
+ };
+ Ok(accumulator)
+ }
}
impl AggregateExpr for ApproxPercentileCont {
@@ -156,27 +185,8 @@ impl AggregateExpr for ApproxPercentileCont {
}
fn create_accumulator(&self) -> Result<Box<dyn Accumulator>> {
- let accumulator: Box<dyn Accumulator> = match &self.input_data_type {
- t @ (DataType::UInt8
- | DataType::UInt16
- | DataType::UInt32
- | DataType::UInt64
- | DataType::Int8
- | DataType::Int16
- | DataType::Int32
- | DataType::Int64
- | DataType::Float32
- | DataType::Float64) => {
- Box::new(ApproxPercentileAccumulator::new(self.percentile, t.clone()))
- }
- other => {
- return Err(DataFusionError::NotImplemented(format!(
- "Support for 'APPROX_PERCENTILE_CONT' for data type {} is not implemented",
- other
- )))
- }
- };
- Ok(accumulator)
+ let accumulator = self.create_plain_accumulator()?;
+ Ok(Box::new(accumulator))
}
fn name(&self) -> &str {
@@ -194,66 +204,99 @@ pub struct ApproxPercentileAccumulator {
impl ApproxPercentileAccumulator {
pub fn new(percentile: f64, return_type: DataType) -> Self {
Self {
- digest: TDigest::new(100),
+ digest: TDigest::new(DEFAULT_MAX_SIZE),
percentile,
return_type,
}
}
-}
-impl Accumulator for ApproxPercentileAccumulator {
- fn state(&self) -> Result<Vec<ScalarValue>> {
- Ok(self.digest.to_scalar_state())
+ pub(crate) fn merge_digests(&mut self, digests: &[TDigest]) {
+ self.digest = TDigest::merge_digests(digests);
}
- fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
- debug_assert_eq!(
- values.len(),
- 1,
- "invalid number of values in batch percentile update"
- );
- let values = &values[0];
-
- self.digest = match values.data_type() {
+ pub(crate) fn convert_to_ordered_float(
+ values: &ArrayRef,
+ ) -> Result<Vec<OrderedFloat<f64>>> {
+ match values.data_type() {
DataType::Float64 => {
let array = values.as_any().downcast_ref::<Float64Array>().unwrap();
- self.digest.merge_unsorted(array.values().iter().cloned())?
+ Ok(array
+ .values()
+ .iter()
+ .filter_map(|v| v.try_as_f64().transpose())
+ .collect::<Result<Vec<_>>>()?)
}
DataType::Float32 => {
let array = values.as_any().downcast_ref::<Float32Array>().unwrap();
- self.digest.merge_unsorted(array.values().iter().cloned())?
+ Ok(array
+ .values()
+ .iter()
+ .filter_map(|v| v.try_as_f64().transpose())
+ .collect::<Result<Vec<_>>>()?)
}
DataType::Int64 => {
let array = values.as_any().downcast_ref::<Int64Array>().unwrap();
- self.digest.merge_unsorted(array.values().iter().cloned())?
+ Ok(array
+ .values()
+ .iter()
+ .filter_map(|v| v.try_as_f64().transpose())
+ .collect::<Result<Vec<_>>>()?)
}
DataType::Int32 => {
let array = values.as_any().downcast_ref::<Int32Array>().unwrap();
- self.digest.merge_unsorted(array.values().iter().cloned())?
+ Ok(array
+ .values()
+ .iter()
+ .filter_map(|v| v.try_as_f64().transpose())
+ .collect::<Result<Vec<_>>>()?)
}
DataType::Int16 => {
let array = values.as_any().downcast_ref::<Int16Array>().unwrap();
- self.digest.merge_unsorted(array.values().iter().cloned())?
+ Ok(array
+ .values()
+ .iter()
+ .filter_map(|v| v.try_as_f64().transpose())
+ .collect::<Result<Vec<_>>>()?)
}
DataType::Int8 => {
let array = values.as_any().downcast_ref::<Int8Array>().unwrap();
- self.digest.merge_unsorted(array.values().iter().cloned())?
+ Ok(array
+ .values()
+ .iter()
+ .filter_map(|v| v.try_as_f64().transpose())
+ .collect::<Result<Vec<_>>>()?)
}
DataType::UInt64 => {
let array = values.as_any().downcast_ref::<UInt64Array>().unwrap();
- self.digest.merge_unsorted(array.values().iter().cloned())?
+ Ok(array
+ .values()
+ .iter()
+ .filter_map(|v| v.try_as_f64().transpose())
+ .collect::<Result<Vec<_>>>()?)
}
DataType::UInt32 => {
let array = values.as_any().downcast_ref::<UInt32Array>().unwrap();
- self.digest.merge_unsorted(array.values().iter().cloned())?
+ Ok(array
+ .values()
+ .iter()
+ .filter_map(|v| v.try_as_f64().transpose())
+ .collect::<Result<Vec<_>>>()?)
}
DataType::UInt16 => {
let array = values.as_any().downcast_ref::<UInt16Array>().unwrap();
- self.digest.merge_unsorted(array.values().iter().cloned())?
+ Ok(array
+ .values()
+ .iter()
+ .filter_map(|v| v.try_as_f64().transpose())
+ .collect::<Result<Vec<_>>>()?)
}
DataType::UInt8 => {
let array = values.as_any().downcast_ref::<UInt8Array>().unwrap();
- self.digest.merge_unsorted(array.values().iter().cloned())?
+ Ok(array
+ .values()
+ .iter()
+ .filter_map(|v| v.try_as_f64().transpose())
+ .collect::<Result<Vec<_>>>()?)
}
e => {
return Err(DataFusionError::Internal(format!(
@@ -261,8 +304,25 @@ impl Accumulator for ApproxPercentileAccumulator {
e
)));
}
- };
+ }
+ }
+}
+impl Accumulator for ApproxPercentileAccumulator {
+ fn state(&self) -> Result<Vec<ScalarValue>> {
+ Ok(self.digest.to_scalar_state())
+ }
+
+ fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
+ debug_assert_eq!(
+ values.len(),
+ 1,
+ "invalid number of values in batch percentile update"
+ );
+ let values = &values[0];
+ let unsorted_values =
+ ApproxPercentileAccumulator::convert_to_ordered_float(values)?;
+ self.digest = self.digest.merge_unsorted_f64(unsorted_values);
Ok(())
}
@@ -302,7 +362,7 @@ impl Accumulator for ApproxPercentileAccumulator {
.chain(iter::once(Ok(self.digest.clone())))
.collect::<Result<Vec<_>>>()?;
- self.digest = TDigest::merge_digests(&states);
+ self.merge_digests(&states);
Ok(())
}
diff --git a/datafusion-physical-expr/src/expressions/approx_percentile_cont_with_weight.rs b/datafusion-physical-expr/src/expressions/approx_percentile_cont_with_weight.rs
new file mode 100644
index 0000000000..33b2ee7a67
--- /dev/null
+++ b/datafusion-physical-expr/src/expressions/approx_percentile_cont_with_weight.rs
@@ -0,0 +1,154 @@
+// 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.
+
+use crate::expressions::approx_percentile_cont::ApproxPercentileAccumulator;
+use crate::expressions::ApproxPercentileCont;
+use crate::{
+ tdigest::{Centroid, TDigest, DEFAULT_MAX_SIZE},
+ AggregateExpr, PhysicalExpr,
+};
+use arrow::{
+ array::ArrayRef,
+ datatypes::{DataType, Field},
+};
+
+use datafusion_common::Result;
+use datafusion_common::ScalarValue;
+use datafusion_expr::Accumulator;
+
+use std::{any::Any, sync::Arc};
+
+/// APPROX_PERCENTILE_CONT_WITH_WEIGTH aggregate expression
+#[derive(Debug)]
+pub struct ApproxPercentileContWithWeight {
+ approx_percentile_cont: ApproxPercentileCont,
+ column_expr: Arc<dyn PhysicalExpr>,
+ weight_expr: Arc<dyn PhysicalExpr>,
+}
+
+impl ApproxPercentileContWithWeight {
+ /// Create a new [`ApproxPercentileContWithWeight`] aggregate function.
+ pub fn new(
+ expr: Vec<Arc<dyn PhysicalExpr>>,
+ name: impl Into<String>,
+ return_type: DataType,
+ ) -> Result<Self> {
+ // Arguments should be [ColumnExpr, WeightExpr, DesiredPercentileLiteral]
+ debug_assert_eq!(expr.len(), 3);
+
+ let sub_expr = vec![expr[0].clone(), expr[2].clone()];
+ let approx_percentile_cont =
+ ApproxPercentileCont::new(sub_expr, name, return_type)?;
+
+ Ok(Self {
+ approx_percentile_cont,
+ column_expr: expr[0].clone(),
+ weight_expr: expr[1].clone(),
+ })
+ }
+}
+
+impl AggregateExpr for ApproxPercentileContWithWeight {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn field(&self) -> Result<Field> {
+ self.approx_percentile_cont.field()
+ }
+
+ #[allow(rustdoc::private_intra_doc_links)]
+ /// See [`TDigest::to_scalar_state()`] for a description of the serialised
+ /// state.
+ fn state_fields(&self) -> Result<Vec<Field>> {
+ self.approx_percentile_cont.state_fields()
+ }
+
+ fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ vec![self.column_expr.clone(), self.weight_expr.clone()]
+ }
+
+ fn create_accumulator(&self) -> Result<Box<dyn Accumulator>> {
+ let approx_percentile_cont_accumulator =
+ self.approx_percentile_cont.create_plain_accumulator()?;
+ let accumulator = ApproxPercentileWithWeightAccumulator::new(
+ approx_percentile_cont_accumulator,
+ );
+ Ok(Box::new(accumulator))
+ }
+
+ fn name(&self) -> &str {
+ self.approx_percentile_cont.name()
+ }
+}
+
+#[derive(Debug)]
+pub struct ApproxPercentileWithWeightAccumulator {
+ approx_percentile_cont_accumulator: ApproxPercentileAccumulator,
+}
+
+impl ApproxPercentileWithWeightAccumulator {
+ pub fn new(approx_percentile_cont_accumulator: ApproxPercentileAccumulator) -> Self {
+ Self {
+ approx_percentile_cont_accumulator,
+ }
+ }
+}
+
+impl Accumulator for ApproxPercentileWithWeightAccumulator {
+ fn state(&self) -> Result<Vec<ScalarValue>> {
+ self.approx_percentile_cont_accumulator.state()
+ }
+
+ fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
+ debug_assert_eq!(
+ values.len(),
+ 2,
+ "invalid number of values in batch percentile update"
+ );
+ let means = &values[0];
+ let weights = &values[1];
+ debug_assert_eq!(
+ means.len(),
+ weights.len(),
+ "invalid number of values in means and weights"
+ );
+ let means_f64 = ApproxPercentileAccumulator::convert_to_ordered_float(means)?;
+ let weights_f64 = ApproxPercentileAccumulator::convert_to_ordered_float(weights)?;
+ let mut digests: Vec<TDigest> = vec![];
+ for (mean, weight) in means_f64.iter().zip(weights_f64.iter()) {
+ digests.push(TDigest::new_with_centroid(
+ DEFAULT_MAX_SIZE,
+ Centroid::new(*mean, *weight),
+ ))
+ }
+ self.approx_percentile_cont_accumulator
+ .merge_digests(&digests);
+ Ok(())
+ }
+
+ fn evaluate(&self) -> Result<ScalarValue> {
+ self.approx_percentile_cont_accumulator.evaluate()
+ }
+
+ fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
+ self.approx_percentile_cont_accumulator
+ .merge_batch(states)?;
+
+ Ok(())
+ }
+}
diff --git a/datafusion-physical-expr/src/expressions/mod.rs b/datafusion-physical-expr/src/expressions/mod.rs
index dd0b01129e..775c4ccd4b 100644
--- a/datafusion-physical-expr/src/expressions/mod.rs
+++ b/datafusion-physical-expr/src/expressions/mod.rs
@@ -19,6 +19,7 @@
mod approx_distinct;
mod approx_percentile_cont;
+mod approx_percentile_cont_with_weight;
mod array_agg;
mod average;
#[macro_use]
@@ -62,6 +63,7 @@ pub use approx_median::ApproxMedian;
pub use approx_percentile_cont::{
is_approx_percentile_cont_supported_arg_type, ApproxPercentileCont,
};
+pub use approx_percentile_cont_with_weight::ApproxPercentileContWithWeight;
pub use array_agg::ArrayAgg;
pub use average::is_avg_support_arg_type;
pub use average::{avg_return_type, Avg, AvgAccumulator};
diff --git a/datafusion-physical-expr/src/tdigest/mod.rs b/datafusion-physical-expr/src/tdigest/mod.rs
index 3f5cbfb76e..401fd5a239 100644
--- a/datafusion-physical-expr/src/tdigest/mod.rs
+++ b/datafusion-physical-expr/src/tdigest/mod.rs
@@ -34,6 +34,8 @@ use datafusion_common::ScalarValue;
use ordered_float::OrderedFloat;
use std::cmp::Ordering;
+pub const DEFAULT_MAX_SIZE: usize = 100;
+
// Cast a non-null [`ScalarValue::Float64`] to an [`OrderedFloat<f64>`], or
// panic.
macro_rules! cast_scalar_f64 {
@@ -96,7 +98,7 @@ impl TryIntoOrderedF64 for ScalarValue {
got => {
return Err(DataFusionError::NotImplemented(format!(
- "Support for 'APPROX_PERCENTILE_CONT' for data type {} is not implemented",
+ "Support for 'TryIntoOrderedF64' for data type {} is not implemented",
got
)))
}
@@ -189,6 +191,17 @@ impl TDigest {
}
}
+ pub(crate) fn new_with_centroid(max_size: usize, centroid: Centroid) -> Self {
+ TDigest {
+ centroids: vec![centroid.clone()],
+ max_size,
+ sum: centroid.mean * centroid.weight,
+ count: OrderedFloat::from(1.0),
+ max: centroid.mean,
+ min: centroid.mean,
+ }
+ }
+
#[inline]
pub(crate) fn count(&self) -> f64 {
self.count.into_inner()
@@ -249,18 +262,13 @@ impl TDigest {
}
}
- pub(crate) fn merge_unsorted<T: TryIntoOrderedF64>(
+ pub(crate) fn merge_unsorted_f64(
&self,
- unsorted_values: impl IntoIterator<Item = T>,
- ) -> Result<TDigest> {
- let mut values = unsorted_values
- .into_iter()
- .filter_map(|v| v.try_as_f64().transpose())
- .collect::<Result<Vec<_>>>()?;
-
+ unsorted_values: Vec<OrderedFloat<f64>>,
+ ) -> TDigest {
+ let mut values = unsorted_values;
values.sort();
-
- Ok(self.merge_sorted_f64(&values))
+ self.merge_sorted_f64(&values)
}
fn merge_sorted_f64(&self, sorted_values: &[OrderedFloat<f64>]) -> TDigest {
@@ -668,8 +676,6 @@ fn is_sorted(values: &[OrderedFloat<f64>]) -> bool {
#[cfg(test)]
mod tests {
- use std::iter;
-
use super::*;
// A macro to assert the specified `quantile` estimated by `t` is within the
@@ -708,29 +714,12 @@ mod tests {
#[test]
fn test_int64_uniform() {
- let values = (1i64..=1000).map(|v| ScalarValue::Int64(Some(v)));
-
- let t = TDigest::new(100);
- let t = t.merge_unsorted(values).unwrap();
-
- assert_error_bounds!(t, quantile = 0.1, want = 100.0);
- assert_error_bounds!(t, quantile = 0.5, want = 500.0);
- assert_error_bounds!(t, quantile = 0.9, want = 900.0);
- assert_state_roundtrip!(t);
- }
-
- #[test]
- fn test_int64_uniform_with_nulls() {
- let values = (1i64..=1000).map(|v| ScalarValue::Int64(Some(v)));
- // Prepend some NULLs
- let values = iter::repeat(ScalarValue::Int64(None))
- .take(10)
- .chain(values);
- // Append some more NULLs
- let values = values.chain(iter::repeat(ScalarValue::Int64(None)).take(10));
+ let values = (1i64..=1000)
+ .map(|v| OrderedFloat::from(v as f64))
+ .collect();
let t = TDigest::new(100);
- let t = t.merge_unsorted(values).unwrap();
+ let t = t.merge_unsorted_f64(values);
assert_error_bounds!(t, quantile = 0.1, want = 100.0);
assert_error_bounds!(t, quantile = 0.5, want = 500.0);
@@ -746,7 +735,7 @@ mod tests {
let mut t = TDigest::new(10);
for v in vals {
- t = t.merge_unsorted([ScalarValue::Float64(Some(v))]).unwrap();
+ t = t.merge_unsorted_f64(vec![OrderedFloat::from(v as f64)]);
}
assert_error_bounds!(t, quantile = 0.5, want = 1.0);
@@ -759,10 +748,10 @@ mod tests {
let t = TDigest::new(100);
let values: Vec<_> = (1..=1_000_000)
.map(f64::from)
- .map(|v| ScalarValue::Float64(Some(v)))
+ .map(|v| OrderedFloat::from(v as f64))
.collect();
- let t = t.merge_unsorted(values).unwrap();
+ let t = t.merge_unsorted_f64(values);
assert_error_bounds!(t, quantile = 1.0, want = 1_000_000.0);
assert_error_bounds!(t, quantile = 0.99, want = 990_000.0);
@@ -777,13 +766,13 @@ mod tests {
let t = TDigest::new(100);
let mut values: Vec<_> = (1..=600_000)
.map(f64::from)
- .map(|v| ScalarValue::Float64(Some(v)))
+ .map(|v| OrderedFloat::from(v as f64))
.collect();
for _ in 0..400_000 {
- values.push(ScalarValue::Float64(Some(1_000_000.0)));
+ values.push(OrderedFloat::from(1_000_000_f64));
}
- let t = t.merge_unsorted(values).unwrap();
+ let t = t.merge_unsorted_f64(values);
assert_error_bounds!(t, quantile = 0.99, want = 1_000_000.0);
assert_error_bounds!(t, quantile = 0.01, want = 10_000.0);
@@ -799,9 +788,9 @@ mod tests {
let t = TDigest::new(100);
let values: Vec<_> = (1..=1_000)
.map(f64::from)
- .map(|v| ScalarValue::Float64(Some(v)))
+ .map(|v| OrderedFloat::from(v as f64))
.collect();
- let t = t.merge_unsorted(values).unwrap();
+ let t = t.merge_unsorted_f64(values);
digests.push(t)
}
diff --git a/datafusion-proto/proto/datafusion.proto b/datafusion-proto/proto/datafusion.proto
index 4ee3298ff1..2e934b86ce 100644
--- a/datafusion-proto/proto/datafusion.proto
+++ b/datafusion-proto/proto/datafusion.proto
@@ -207,6 +207,7 @@ enum AggregateFunction {
CORRELATION=13;
APPROX_PERCENTILE_CONT = 14;
APPROX_MEDIAN=15;
+ APPROX_PERCENTILE_CONT_WITH_WEIGHT = 16;
}
message AggregateExprNode {
diff --git a/datafusion-proto/src/from_proto.rs b/datafusion-proto/src/from_proto.rs
index f351aa85c1..17f03b9236 100644
--- a/datafusion-proto/src/from_proto.rs
+++ b/datafusion-proto/src/from_proto.rs
@@ -453,6 +453,9 @@ impl From<protobuf::AggregateFunction> for AggregateFunction {
protobuf::AggregateFunction::ApproxPercentileCont => {
Self::ApproxPercentileCont
}
+ protobuf::AggregateFunction::ApproxPercentileContWithWeight => {
+ Self::ApproxPercentileContWithWeight
+ }
protobuf::AggregateFunction::ApproxMedian => Self::ApproxMedian,
}
}
diff --git a/datafusion-proto/src/to_proto.rs b/datafusion-proto/src/to_proto.rs
index 753e59c1d1..df91e22f02 100644
--- a/datafusion-proto/src/to_proto.rs
+++ b/datafusion-proto/src/to_proto.rs
@@ -312,6 +312,9 @@ impl From<&AggregateFunction> for protobuf::AggregateFunction {
AggregateFunction::StddevPop => Self::StddevPop,
AggregateFunction::Correlation => Self::Correlation,
AggregateFunction::ApproxPercentileCont => Self::ApproxPercentileCont,
+ AggregateFunction::ApproxPercentileContWithWeight => {
+ Self::ApproxPercentileContWithWeight
+ }
AggregateFunction::ApproxMedian => Self::ApproxMedian,
}
}
@@ -469,6 +472,9 @@ impl TryFrom<&Expr> for protobuf::LogicalExprNode {
AggregateFunction::ApproxPercentileCont => {
protobuf::AggregateFunction::ApproxPercentileCont
}
+ AggregateFunction::ApproxPercentileContWithWeight => {
+ protobuf::AggregateFunction::ApproxPercentileContWithWeight
+ }
AggregateFunction::ArrayAgg => protobuf::AggregateFunction::ArrayAgg,
AggregateFunction::Min => protobuf::AggregateFunction::Min,
AggregateFunction::Max => protobuf::AggregateFunction::Max,
diff --git a/datafusion/src/physical_plan/aggregates.rs b/datafusion/src/physical_plan/aggregates.rs
index ab114643fe..cfa3168c67 100644
--- a/datafusion/src/physical_plan/aggregates.rs
+++ b/datafusion/src/physical_plan/aggregates.rs
@@ -79,6 +79,9 @@ pub fn return_type(
true,
)))),
AggregateFunction::ApproxPercentileCont => Ok(coerced_data_types[0].clone()),
+ AggregateFunction::ApproxPercentileContWithWeight => {
+ Ok(coerced_data_types[0].clone())
+ }
AggregateFunction::ApproxMedian => Ok(coerced_data_types[0].clone()),
}
}
@@ -268,6 +271,20 @@ pub fn create_aggregate_expr(
.to_string(),
));
}
+ (AggregateFunction::ApproxPercentileContWithWeight, false) => {
+ Arc::new(expressions::ApproxPercentileContWithWeight::new(
+ // Pass in the desired percentile expr
+ coerced_phy_exprs,
+ name,
+ return_type,
+ )?)
+ }
+ (AggregateFunction::ApproxPercentileContWithWeight, true) => {
+ return Err(DataFusionError::NotImplemented(
+ "approx_percentile_cont_with_weight(DISTINCT) aggregations are not available"
+ .to_string(),
+ ));
+ }
(AggregateFunction::ApproxMedian, false) => {
Arc::new(expressions::ApproxMedian::new(
coerced_phy_exprs[0].clone(),
@@ -347,6 +364,16 @@ pub(super) fn signature(fun: &AggregateFunction) -> Signature {
.collect(),
Volatility::Immutable,
),
+ AggregateFunction::ApproxPercentileContWithWeight => Signature::one_of(
+ // Accept any numeric value paired with a float64 percentile
+ NUMERICS
+ .iter()
+ .map(|t| {
+ TypeSignature::Exact(vec![t.clone(), t.clone(), DataType::Float64])
+ })
+ .collect(),
+ Volatility::Immutable,
+ ),
}
}
diff --git a/datafusion/tests/sql/aggregates.rs b/datafusion/tests/sql/aggregates.rs
index 8c5640c043..c3553a9cae 100644
--- a/datafusion/tests/sql/aggregates.rs
+++ b/datafusion/tests/sql/aggregates.rs
@@ -476,6 +476,73 @@ async fn csv_query_approx_percentile_cont() -> Result<()> {
Ok(())
}
+#[tokio::test]
+async fn csv_query_approx_percentile_cont_with_weight() -> Result<()> {
+ let mut ctx = SessionContext::new();
+ register_aggregate_csv(&mut ctx).await?;
+
+ // compare approx_percentile_cont and approx_percentile_cont_with_weight
+ let sql = "SELECT c1, approx_percentile_cont(c3, 0.95) AS c3_p95 FROM aggregate_test_100 GROUP BY 1 ORDER BY 1";
+ let actual = execute_to_batches(&ctx, sql).await;
+ let expected = vec![
+ "+----+--------+",
+ "| c1 | c3_p95 |",
+ "+----+--------+",
+ "| a | 73 |",
+ "| b | 68 |",
+ "| c | 122 |",
+ "| d | 124 |",
+ "| e | 115 |",
+ "+----+--------+",
+ ];
+ assert_batches_eq!(expected, &actual);
+
+ let sql = "SELECT c1, approx_percentile_cont_with_weight(c3, 1, 0.95) AS c3_p95 FROM aggregate_test_100 GROUP BY 1 ORDER BY 1";
+ let actual = execute_to_batches(&ctx, sql).await;
+ assert_batches_eq!(expected, &actual);
+
+ let sql = "SELECT c1, approx_percentile_cont_with_weight(c3, c2, 0.95) AS c3_p95 FROM aggregate_test_100 GROUP BY 1 ORDER BY 1";
+ let actual = execute_to_batches(&ctx, sql).await;
+ let expected = vec![
+ "+----+--------+",
+ "| c1 | c3_p95 |",
+ "+----+--------+",
+ "| a | 74 |",
+ "| b | 68 |",
+ "| c | 123 |",
+ "| d | 124 |",
+ "| e | 115 |",
+ "+----+--------+",
+ ];
+ assert_batches_eq!(expected, &actual);
+
+ let results = plan_and_collect(
+ &mut ctx,
+ "SELECT approx_percentile_cont_with_weight(c1, c2, 0.95) FROM aggregate_test_100",
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(results.to_string(), "Error during planning: The function ApproxPercentileContWithWeight does not support inputs of type Utf8.");
+
+ let results = plan_and_collect(
+ &mut ctx,
+ "SELECT approx_percentile_cont_with_weight(c3, c1, 0.95) FROM aggregate_test_100",
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(results.to_string(), "Error during planning: The weight argument for ApproxPercentileContWithWeight does not support inputs of type Utf8.");
+
+ let results = plan_and_collect(
+ &mut ctx,
+ "SELECT approx_percentile_cont_with_weight(c3, c2, c1) FROM aggregate_test_100",
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(results.to_string(), "Error during planning: The percentile argument for ApproxPercentileContWithWeight must be Float64, not Utf8.");
+
+ Ok(())
+}
+
#[tokio::test]
async fn csv_query_sum_crossjoin() {
let mut ctx = SessionContext::new();