diff --git a/datafusion/functions-aggregate/src/min_max.rs b/datafusion/functions-aggregate/src/min_max.rs index ea4cad548803..cc43d5a7dfef 100644 --- a/datafusion/functions-aggregate/src/min_max.rs +++ b/datafusion/functions-aggregate/src/min_max.rs @@ -572,7 +572,7 @@ macro_rules! min_max_batch { } /// dynamically-typed min(array) -> ScalarValue -fn min_batch(values: &ArrayRef) -> Result { +pub fn min_batch(values: &ArrayRef) -> Result { Ok(match values.data_type() { DataType::Utf8 => { typed_min_max_batch_string!(values, StringArray, Utf8, min_string) diff --git a/datafusion/functions-nested/src/lib.rs b/datafusion/functions-nested/src/lib.rs index c9a61d98cd44..d3b2728a7be6 100644 --- a/datafusion/functions-nested/src/lib.rs +++ b/datafusion/functions-nested/src/lib.rs @@ -54,6 +54,7 @@ pub mod map_extract; pub mod map_keys; pub mod map_values; pub mod max; +pub mod min; pub mod planner; pub mod position; pub mod range; @@ -147,6 +148,7 @@ pub fn all_default_nested_functions() -> Vec> { distance::array_distance_udf(), flatten::flatten_udf(), max::array_max_udf(), + min::array_min_udf(), sort::array_sort_udf(), repeat::array_repeat_udf(), resize::array_resize_udf(), diff --git a/datafusion/functions-nested/src/min.rs b/datafusion/functions-nested/src/min.rs new file mode 100644 index 000000000000..64fda4e12fd1 --- /dev/null +++ b/datafusion/functions-nested/src/min.rs @@ -0,0 +1,140 @@ +// 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. + +//! [`ScalarUDFImpl`] definitions for array_min function. + +use crate::utils::make_scalar_function; +use arrow::array::ArrayRef; +use arrow::datatypes::DataType; +use arrow::datatypes::DataType::List; +use datafusion_common::cast::as_list_array; +use datafusion_common::utils::take_function_args; +use datafusion_common::{exec_err, ScalarValue}; +use datafusion_doc::Documentation; +use datafusion_expr::{ + ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility, +}; +use datafusion_functions_aggregate::min_max; +use datafusion_macros::user_doc; +use itertools::Itertools; +use std::any::Any; + +make_udf_expr_and_func!( + ArrayMin, + array_min, + array, + "returns the minimum value in the array.", + array_min_udf +); + +#[user_doc( + doc_section(label = "Array Functions"), + description = "Returns the minimum value in the array.", + syntax_example = "array_min(array)", + sql_example = r#"```sql +> select array_min([3,1,4,2]); ++-----------------------------------------+ +| array_min(List([3,1,4,2])) | ++-----------------------------------------+ +| 1 | ++-----------------------------------------+ +```"#, + argument( + name = "array", + description = "Array expression. Can be a constant, column, or function, and any combination of array operators." + ) +)] +#[derive(Debug)] +pub struct ArrayMin { + signature: Signature, + aliases: Vec, +} + +impl Default for ArrayMin { + fn default() -> Self { + Self::new() + } +} + +impl ArrayMin { + pub fn new() -> Self { + Self { + signature: Signature::array(Volatility::Immutable), + aliases: vec!["list_min".to_string()], + } + } +} + +impl ScalarUDFImpl for ArrayMin { + fn as_any(&self) -> &dyn Any { + self + } + + fn name(&self) -> &str { + "array_min" + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type(&self, arg_types: &[DataType]) -> datafusion_common::Result { + match &arg_types[0] { + List(field) => Ok(field.data_type().clone()), + _ => exec_err!("Not reachable, data_type should be List"), + } + } + + fn invoke_with_args( + &self, + args: ScalarFunctionArgs, + ) -> datafusion_common::Result { + make_scalar_function(array_min_inner)(&args.args) + } + + fn aliases(&self) -> &[String] { + &self.aliases + } + + fn documentation(&self) -> Option<&Documentation> { + self.doc() + } +} + +/// array_min SQL function +/// +/// There is one argument for array_min as the array. +/// `array_min(array)` +/// +/// For example: +/// > array_min(\[3, 1, 2]) -> 1 +pub fn array_min_inner(args: &[ArrayRef]) -> datafusion_common::Result { + let [arg1] = take_function_args("array_min", args)?; + + match &arg1.data_type() { + List(_) => { + let input_list_array = as_list_array(&arg1)?; + let result_vec = input_list_array + .iter() + .flat_map(|arr| min_max::min_batch(&arr.unwrap())) + .collect_vec(); + + ScalarValue::iter_to_array(result_vec) + } + _ => exec_err!("array_min does not support type: {:?}", args[0].data_type()), + } +} diff --git a/datafusion/sqllogictest/test_files/array.slt b/datafusion/sqllogictest/test_files/array.slt index 9772de3db365..a3719351dd07 100644 --- a/datafusion/sqllogictest/test_files/array.slt +++ b/datafusion/sqllogictest/test_files/array.slt @@ -1521,6 +1521,90 @@ NULL query error DataFusion error: Error during planning: 'array_max' does not support zero arguments select array_max(); +## array_min +# array_min scalar function #1 (with positive index) +query I +select array_min(make_array(5, 3, 4, 6)); +---- +3 + +query I +select array_min(make_array(5, 3, 4, NULL, 6, NULL)); +---- +3 + +query I +select array_min(make_array(NULL, NULL)); +---- +NULL + +query T +select array_min(make_array('h', 'e', 'l', 'l', 'o')); +---- +e + +query T +select array_min(make_array('h', 'e', 'l', NULL, 'l', 'o', NULL)); +---- +e + +query B +select array_min(make_array(true, true, false, true)); +---- +false + +query B +select array_min(make_array(true, true, NULL, false, true)); +---- +false + +query D +select array_min(make_array(DATE '1992-09-01', DATE '1993-03-01', DATE '1985-11-01', DATE '1999-05-01')); +---- +1985-11-01 + +query D +select array_min(make_array(DATE '1995-09-01', DATE '1993-03-01', NULL, DATE '1999-05-01')); +---- +1993-03-01 + +query P +select array_min(make_array(TIMESTAMP '1992-09-01', TIMESTAMP '1984-10-01', TIMESTAMP '1995-06-01')); +---- +1984-10-01T00:00:00 + +query R +select array_min(make_array(5.1, -3.2, 6.3, 4.9)); +---- +-3.2 + +query P +select array_min(make_array(NULL, TIMESTAMP '1996-10-01', TIMESTAMP '1995-06-01')); +---- +1995-06-01T00:00:00 + +query ?I +select input, array_min(input) from (select make_array(d - 1, d, d + 1) input from (values (0), (10), (20), (30), (NULL)) t(d)) +---- +[-1, 0, 1] -1 +[9, 10, 11] 9 +[19, 20, 21] 19 +[29, 30, 31] 29 +[NULL, NULL, NULL] NULL + +query II +select array_min(arrow_cast(make_array(2, 1, 3), 'FixedSizeList(3, Int64)')), array_min(arrow_cast(make_array(2), 'FixedSizeList(1, Int64)')); +---- +1 2 + +query I +select array_min(make_array()); +---- +NULL + +# Testing with empty arguments should result in an error +query error DataFusion error: Error during planning: 'array_min' does not support zero arguments +select array_min(); ## array_pop_back (aliases: `list_pop_back`) diff --git a/docs/source/user-guide/sql/scalar_functions.md b/docs/source/user-guide/sql/scalar_functions.md index 0f08934c8a9c..22876b6a126f 100644 --- a/docs/source/user-guide/sql/scalar_functions.md +++ b/docs/source/user-guide/sql/scalar_functions.md @@ -2552,6 +2552,7 @@ _Alias of [current_date](#current_date)._ - [array_join](#array_join) - [array_length](#array_length) - [array_max](#array_max) +- [array_min](#array_min) - [array_ndims](#array_ndims) - [array_pop_back](#array_pop_back) - [array_pop_front](#array_pop_front) @@ -2598,6 +2599,7 @@ _Alias of [current_date](#current_date)._ - [list_join](#list_join) - [list_length](#list_length) - [list_max](#list_max) +- [list_min](#list_min) - [list_ndims](#list_ndims) - [list_pop_back](#list_pop_back) - [list_pop_front](#list_pop_front) @@ -3058,6 +3060,33 @@ array_max(array) - list_max +### `array_min` + +Returns the minimum value in the array. + +```sql +array_min(array) +``` + +#### Arguments + +- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators. + +#### Example + +```sql +> select array_min([3,1,4,2]); ++-----------------------------------------+ +| array_min(List([3,1,4,2])) | ++-----------------------------------------+ +| 1 | ++-----------------------------------------+ +``` + +#### Aliases + +- list_min + ### `array_ndims` Returns the number of dimensions of the array. @@ -3819,6 +3848,10 @@ _Alias of [array_length](#array_length)._ _Alias of [array_max](#array_max)._ +### `list_min` + +_Alias of [array_min](#array_min)._ + ### `list_ndims` _Alias of [array_ndims](#array_ndims)._