Skip to main content

datafusion_functions_nested/
min_max.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! [`ScalarUDFImpl`] definitions for array_min and array_max functions.
6use crate::utils::make_scalar_function;
7use arrow::array::{
8    Array, ArrayRef, ArrowNativeTypeOp, ArrowPrimitiveType, AsArray, GenericListArray,
9    OffsetSizeTrait, PrimitiveBuilder, downcast_primitive,
10};
11use arrow::buffer::NullBuffer;
12use arrow::datatypes::DataType;
13use arrow::datatypes::DataType::{LargeList, List};
14use datafusion_common::Result;
15use datafusion_common::cast::{as_large_list_array, as_list_array};
16use datafusion_common::utils::take_function_args;
17use datafusion_common::{ScalarValue, exec_err, plan_err};
18use datafusion_doc::Documentation;
19use datafusion_expr::{
20    ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
21};
22use datafusion_functions_aggregate_common::min_max::{max_batch, min_batch};
23use datafusion_macros::user_doc;
24use itertools::Itertools;
25use std::sync::Arc;
26
27make_udf_expr_and_func!(
28    ArrayMax,
29    array_max,
30    array,
31    "returns the maximum value in the array.",
32    array_max_udf
33);
34
35#[user_doc(
36    doc_section(label = "Array Functions"),
37    description = "Returns the maximum value in the array.",
38    syntax_example = "array_max(array)",
39    sql_example = r#"```sql
40> select array_max([3,1,4,2]);
41+-----------------------------------------+
42| array_max(List([3,1,4,2]))              |
43+-----------------------------------------+
44| 4                                       |
45+-----------------------------------------+
46```"#,
47    argument(
48        name = "array",
49        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
50    )
51)]
52#[derive(Debug, PartialEq, Eq, Hash)]
53pub struct ArrayMax {
54    signature: Signature,
55    aliases: Vec<String>,
56}
57
58impl Default for ArrayMax {
59    fn default() -> Self {
60        Self::new()
61    }
62}
63
64impl ArrayMax {
65    pub fn new() -> Self {
66        Self {
67            signature: Signature::array(Volatility::Immutable),
68            aliases: vec!["list_max".to_string()],
69        }
70    }
71}
72
73impl ScalarUDFImpl for ArrayMax {
74    fn name(&self) -> &str {
75        "array_max"
76    }
77
78    fn signature(&self) -> &Signature {
79        &self.signature
80    }
81
82    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
83        let [array] = take_function_args(self.name(), arg_types)?;
84        match array {
85            List(field) | LargeList(field) => Ok(field.data_type().clone()),
86            arg_type => plan_err!("{} does not support type {arg_type}", self.name()),
87        }
88    }
89
90    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
91        make_scalar_function(array_max_inner)(&args.args)
92    }
93
94    fn aliases(&self) -> &[String] {
95        &self.aliases
96    }
97
98    fn documentation(&self) -> Option<&Documentation> {
99        self.doc()
100    }
101}
102
103fn array_max_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
104    let [array] = take_function_args("array_max", args)?;
105    match array.data_type() {
106        List(_) => array_min_max_helper(as_list_array(array)?, false),
107        LargeList(_) => array_min_max_helper(as_large_list_array(array)?, false),
108        arg_type => exec_err!("array_max does not support type: {arg_type}"),
109    }
110}
111
112make_udf_expr_and_func!(
113    ArrayMin,
114    array_min,
115    array,
116    "returns the minimum value in the array",
117    array_min_udf
118);
119#[user_doc(
120    doc_section(label = "Array Functions"),
121    description = "Returns the minimum value in the array.",
122    syntax_example = "array_min(array)",
123    sql_example = r#"```sql
124> select array_min([3,1,4,2]);
125+-----------------------------------------+
126| array_min(List([3,1,4,2]))              |
127+-----------------------------------------+
128| 1                                       |
129+-----------------------------------------+
130```"#,
131    argument(
132        name = "array",
133        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
134    )
135)]
136#[derive(Debug, PartialEq, Eq, Hash)]
137struct ArrayMin {
138    signature: Signature,
139}
140
141impl Default for ArrayMin {
142    fn default() -> Self {
143        Self::new()
144    }
145}
146
147impl ArrayMin {
148    fn new() -> Self {
149        Self {
150            signature: Signature::array(Volatility::Immutable),
151        }
152    }
153}
154
155impl ScalarUDFImpl for ArrayMin {
156    fn name(&self) -> &str {
157        "array_min"
158    }
159
160    fn signature(&self) -> &Signature {
161        &self.signature
162    }
163
164    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
165        let [array] = take_function_args(self.name(), arg_types)?;
166        match array {
167            List(field) | LargeList(field) => Ok(field.data_type().clone()),
168            arg_type => plan_err!("{} does not support type {}", self.name(), arg_type),
169        }
170    }
171
172    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
173        make_scalar_function(array_min_inner)(&args.args)
174    }
175
176    fn documentation(&self) -> Option<&Documentation> {
177        self.doc()
178    }
179}
180
181fn array_min_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
182    let [array] = take_function_args("array_min", args)?;
183    match array.data_type() {
184        List(_) => array_min_max_helper(as_list_array(array)?, true),
185        LargeList(_) => array_min_max_helper(as_large_list_array(array)?, true),
186        arg_type => exec_err!("array_min does not support type: {arg_type}"),
187    }
188}
189
190fn array_min_max_helper<O: OffsetSizeTrait>(
191    array: &GenericListArray<O>,
192    is_min: bool,
193) -> Result<ArrayRef> {
194    // Try the primitive fast path first
195    if let Some(result) = try_primitive_array_min_max(array, is_min) {
196        return result;
197    }
198
199    // Fallback: per-row ScalarValue path for non-primitive types
200    let agg_fn = if is_min { min_batch } else { max_batch };
201    let null_value = ScalarValue::try_from(array.value_type())?;
202    let result_vec: Vec<ScalarValue> = array
203        .iter()
204        .map(|arr| arr.as_ref().map_or_else(|| Ok(null_value.clone()), agg_fn))
205        .try_collect()?;
206    ScalarValue::iter_to_array(result_vec)
207}
208
209/// Dispatches to a typed primitive min/max implementation, or returns `None` if
210/// the element type is not a primitive.
211fn try_primitive_array_min_max<O: OffsetSizeTrait>(
212    list_array: &GenericListArray<O>,
213    is_min: bool,
214) -> Option<Result<ArrayRef>> {
215    macro_rules! helper {
216        ($t:ty) => {
217            return Some(primitive_array_min_max::<O, $t>(list_array, is_min))
218        };
219    }
220    downcast_primitive! {
221        list_array.value_type() => (helper),
222        _ => {}
223    }
224    None
225}
226
227/// Threshold to switch from direct iteration to using `min` / `max` kernel from
228/// `arrow::compute`. The latter has enough per-invocation overhead that direct
229/// iteration is faster for small lists.
230const ARROW_COMPUTE_THRESHOLD: usize = 32;
231
232/// Computes min or max for each row of a primitive ListArray.
233fn primitive_array_min_max<O: OffsetSizeTrait, T: ArrowPrimitiveType>(
234    list_array: &GenericListArray<O>,
235    is_min: bool,
236) -> Result<ArrayRef> {
237    let values_array = list_array.values().as_primitive::<T>();
238    let values_slice = values_array.values();
239    let values_nulls = values_array.nulls();
240    let mut result_builder = PrimitiveBuilder::<T>::with_capacity(list_array.len())
241        .with_data_type(values_array.data_type().clone());
242
243    for (row, w) in list_array.offsets().windows(2).enumerate() {
244        let row_result = if list_array.is_null(row) {
245            None
246        } else {
247            let start = w[0].as_usize();
248            let end = w[1].as_usize();
249            let len = end - start;
250
251            match len {
252                0 => None,
253                _ if len < ARROW_COMPUTE_THRESHOLD => {
254                    scalar_min_max(values_slice, values_nulls, start, end, is_min)
255                }
256                _ => {
257                    let slice = values_array.slice(start, len);
258                    if is_min {
259                        arrow::compute::min::<T>(&slice)
260                    } else {
261                        arrow::compute::max::<T>(&slice)
262                    }
263                }
264            }
265        };
266
267        result_builder.append_option(row_result);
268    }
269
270    Ok(Arc::new(result_builder.finish()) as ArrayRef)
271}
272
273/// Computes min or max for a single list row by directly scanning a slice of
274/// the flat values buffer.
275#[inline]
276fn scalar_min_max<N: ArrowNativeTypeOp>(
277    values_slice: &[N],
278    values_nulls: Option<&NullBuffer>,
279    start: usize,
280    end: usize,
281    is_min: bool,
282) -> Option<N> {
283    let mut best: Option<N> = None;
284    for (i, &val) in values_slice[start..end].iter().enumerate() {
285        if let Some(nulls) = values_nulls
286            && !nulls.is_valid(start + i)
287        {
288            continue;
289        }
290        let update_best = match best {
291            None => true,
292            Some(current) if is_min => val.is_lt(current),
293            Some(current) => val.is_gt(current),
294        };
295        if update_best {
296            best = Some(val);
297        }
298    }
299    best
300}