datafusion_functions_aggregate/
approx_median.rs1use arrow::datatypes::DataType::{Float64, UInt64};
21use arrow::datatypes::{DataType, Field, FieldRef};
22use std::any::Any;
23use std::fmt::Debug;
24use std::sync::Arc;
25
26use datafusion_common::{not_impl_err, plan_err, Result};
27use datafusion_expr::function::{AccumulatorArgs, StateFieldsArgs};
28use datafusion_expr::type_coercion::aggregates::NUMERICS;
29use datafusion_expr::utils::format_state_name;
30use datafusion_expr::{
31 Accumulator, AggregateUDFImpl, Documentation, Signature, Volatility,
32};
33use datafusion_macros::user_doc;
34
35use crate::approx_percentile_cont::ApproxPercentileAccumulator;
36
37make_udaf_expr_and_func!(
38 ApproxMedian,
39 approx_median,
40 expression,
41 "Computes the approximate median of a set of numbers",
42 approx_median_udaf
43);
44
45#[user_doc(
47 doc_section(label = "Approximate Functions"),
48 description = "Returns the approximate median (50th percentile) of input values. It is an alias of `approx_percentile_cont(0.5) WITHIN GROUP (ORDER BY x)`.",
49 syntax_example = "approx_median(expression)",
50 sql_example = r#"```sql
51> SELECT approx_median(column_name) FROM table_name;
52+-----------------------------------+
53| approx_median(column_name) |
54+-----------------------------------+
55| 23.5 |
56+-----------------------------------+
57```"#,
58 standard_argument(name = "expression",)
59)]
60pub struct ApproxMedian {
61 signature: Signature,
62}
63
64impl Debug for ApproxMedian {
65 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
66 f.debug_struct("ApproxMedian")
67 .field("name", &self.name())
68 .field("signature", &self.signature)
69 .finish()
70 }
71}
72
73impl Default for ApproxMedian {
74 fn default() -> Self {
75 Self::new()
76 }
77}
78
79impl ApproxMedian {
80 pub fn new() -> Self {
82 Self {
83 signature: Signature::uniform(1, NUMERICS.to_vec(), Volatility::Immutable),
84 }
85 }
86}
87
88impl AggregateUDFImpl for ApproxMedian {
89 fn as_any(&self) -> &dyn Any {
91 self
92 }
93
94 fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
95 Ok(vec![
96 Field::new(format_state_name(args.name, "max_size"), UInt64, false),
97 Field::new(format_state_name(args.name, "sum"), Float64, false),
98 Field::new(format_state_name(args.name, "count"), UInt64, false),
99 Field::new(format_state_name(args.name, "max"), Float64, false),
100 Field::new(format_state_name(args.name, "min"), Float64, false),
101 Field::new_list(
102 format_state_name(args.name, "centroids"),
103 Field::new_list_field(Float64, true),
104 false,
105 ),
106 ]
107 .into_iter()
108 .map(Arc::new)
109 .collect())
110 }
111
112 fn name(&self) -> &str {
113 "approx_median"
114 }
115
116 fn signature(&self) -> &Signature {
117 &self.signature
118 }
119
120 fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
121 if !arg_types[0].is_numeric() {
122 return plan_err!("ApproxMedian requires numeric input types");
123 }
124 Ok(arg_types[0].clone())
125 }
126
127 fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> {
128 if acc_args.is_distinct {
129 return not_impl_err!(
130 "APPROX_MEDIAN(DISTINCT) aggregations are not available"
131 );
132 }
133
134 Ok(Box::new(ApproxPercentileAccumulator::new(
135 0.5_f64,
136 acc_args.exprs[0].data_type(acc_args.schema)?,
137 )))
138 }
139
140 fn documentation(&self) -> Option<&Documentation> {
141 self.doc()
142 }
143}