datafusion_functions_nested/
array_avg.rs1use crate::utils::make_scalar_function;
8use arrow::array::{Array, ArrayRef, Float64Array, OffsetSizeTrait};
9use arrow::datatypes::{
10 DataType,
11 DataType::{FixedSizeList, LargeList, List, Null},
12 Field,
13};
14use datafusion_common::cast::{as_float64_array, as_generic_list_array};
15use datafusion_common::utils::{ListCoercion, coerced_type_with_base_type_only};
16use datafusion_common::{Result, internal_err, plan_err, utils::take_function_args};
17use datafusion_expr::{
18 ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
19 Volatility,
20};
21use datafusion_macros::user_doc;
22use std::sync::Arc;
23
24make_udf_expr_and_func!(
25 ArrayAvg,
26 array_avg,
27 array,
28 "returns the arithmetic mean of elements in a numeric array.",
29 array_avg_udf
30);
31
32#[user_doc(
33 doc_section(label = "Array Functions"),
34 description = "Returns the arithmetic mean (sum divided by count) of the elements of the input array. NULL elements are skipped (per SQL aggregate convention) and excluded from the count. Returns NULL if the input row is NULL, every element is NULL, or the array is empty.",
35 syntax_example = "array_avg(array)",
36 sql_example = r#"```sql
37> select array_avg([1.0, 2.0, 3.0]);
38+--------------------------------+
39| array_avg(List([1.0,2.0,3.0])) |
40+--------------------------------+
41| 2.0 |
42+--------------------------------+
43```"#,
44 argument(
45 name = "array",
46 description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
47 )
48)]
49#[derive(Debug, PartialEq, Eq, Hash)]
50pub struct ArrayAvg {
51 signature: Signature,
52 aliases: Vec<String>,
53}
54
55impl Default for ArrayAvg {
56 fn default() -> Self {
57 Self::new()
58 }
59}
60
61impl ArrayAvg {
62 pub fn new() -> Self {
63 Self {
64 signature: Signature::user_defined(Volatility::Immutable),
65 aliases: vec!["list_avg".to_string()],
66 }
67 }
68}
69
70impl ScalarUDFImpl for ArrayAvg {
71 fn name(&self) -> &str {
72 "array_avg"
73 }
74
75 fn signature(&self) -> &Signature {
76 &self.signature
77 }
78
79 fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
80 Ok(DataType::Float64)
81 }
82
83 fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
84 let [arg_type] = take_function_args(self.name(), arg_types)?;
85 let coercion = Some(&ListCoercion::FixedSizedListToList);
86
87 if !matches!(arg_type, Null | List(_) | LargeList(_) | FixedSizeList(..)) {
88 return plan_err!("{} does not support type {arg_type}", self.name());
89 }
90
91 let coerced = if matches!(arg_type, Null) {
92 List(Arc::new(Field::new_list_field(DataType::Float64, true)))
93 } else {
94 coerced_type_with_base_type_only(arg_type, &DataType::Float64, coercion)
95 };
96
97 Ok(vec![coerced])
98 }
99
100 fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
101 make_scalar_function(array_avg_inner)(&args.args)
102 }
103
104 fn aliases(&self) -> &[String] {
105 &self.aliases
106 }
107
108 fn documentation(&self) -> Option<&Documentation> {
109 self.doc()
110 }
111}
112
113fn array_avg_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
114 let [array] = take_function_args("array_avg", args)?;
115 match array.data_type() {
116 List(_) => general_array_avg::<i32>(array),
117 LargeList(_) => general_array_avg::<i64>(array),
118 arg_type => {
119 internal_err!("array_avg received unexpected type after coercion: {arg_type}")
120 }
121 }
122}
123
124fn general_array_avg<O: OffsetSizeTrait>(array: &ArrayRef) -> Result<ArrayRef> {
125 let list_array = as_generic_list_array::<O>(array)?;
126 let values = as_float64_array(list_array.values())?;
127 let offsets = list_array.value_offsets();
128
129 let mut builder = Float64Array::builder(list_array.len());
130
131 for row in 0..list_array.len() {
132 if list_array.is_null(row) {
133 builder.append_null();
134 continue;
135 }
136
137 let start = offsets[row].as_usize();
138 let end = offsets[row + 1].as_usize();
139
140 let mut sum = 0.0_f64;
145 let mut count: u64 = 0;
146 for i in start..end {
147 if values.is_valid(i) {
148 sum += values.value(i);
149 count += 1;
150 }
151 }
152
153 if count > 0 {
154 builder.append_value(sum / count as f64);
155 } else {
156 builder.append_null();
157 }
158 }
159
160 Ok(Arc::new(builder.finish()))
161}