datafusion_functions_aggregate/
approx_median.rs1use std::any::Any;
21use std::fmt::Debug;
22
23use arrow::datatypes::DataType::{Float64, UInt64};
24use arrow::datatypes::{DataType, Field};
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(x, 0.5)`.",
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<Field>> {
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 }
108
109 fn name(&self) -> &str {
110 "approx_median"
111 }
112
113 fn signature(&self) -> &Signature {
114 &self.signature
115 }
116
117 fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
118 if !arg_types[0].is_numeric() {
119 return plan_err!("ApproxMedian requires numeric input types");
120 }
121 Ok(arg_types[0].clone())
122 }
123
124 fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> {
125 if acc_args.is_distinct {
126 return not_impl_err!(
127 "APPROX_MEDIAN(DISTINCT) aggregations are not available"
128 );
129 }
130
131 Ok(Box::new(ApproxPercentileAccumulator::new(
132 0.5_f64,
133 acc_args.exprs[0].data_type(acc_args.schema)?,
134 )))
135 }
136
137 fn documentation(&self) -> Option<&Documentation> {
138 self.doc()
139 }
140}