Skip to content

Commit b4421d4

Browse files
Issue-14416 - feat: Add array_min function
1 parent f47ea73 commit b4421d4

File tree

5 files changed

+259
-1
lines changed

5 files changed

+259
-1
lines changed

datafusion/functions-aggregate/src/min_max.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -530,7 +530,7 @@ macro_rules! min_max_batch {
530530
}
531531

532532
/// dynamically-typed min(array) -> ScalarValue
533-
fn min_batch(values: &ArrayRef) -> Result<ScalarValue> {
533+
pub fn min_batch(values: &ArrayRef) -> Result<ScalarValue> {
534534
Ok(match values.data_type() {
535535
DataType::Utf8 => {
536536
typed_min_max_batch_string!(values, StringArray, Utf8, min_string)

datafusion/functions-nested/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ pub mod map_extract;
5353
pub mod map_keys;
5454
pub mod map_values;
5555
pub mod max;
56+
pub mod min;
5657
pub mod planner;
5758
pub mod position;
5859
pub mod range;
@@ -146,6 +147,7 @@ pub fn all_default_nested_functions() -> Vec<Arc<ScalarUDF>> {
146147
distance::array_distance_udf(),
147148
flatten::flatten_udf(),
148149
max::array_max_udf(),
150+
min::array_min_udf(),
149151
sort::array_sort_udf(),
150152
repeat::array_repeat_udf(),
151153
resize::array_resize_udf(),
Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
// Licensed to the Apache Software Foundation (ASF) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The ASF licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// with the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
18+
//! [`ScalarUDFImpl`] definitions for array_min function.
19+
20+
use crate::utils::make_scalar_function;
21+
use arrow::array::ArrayRef;
22+
use arrow::datatypes::DataType;
23+
use arrow::datatypes::DataType::List;
24+
use datafusion_common::cast::as_list_array;
25+
use datafusion_common::utils::take_function_args;
26+
use datafusion_common::{exec_err, ScalarValue};
27+
use datafusion_doc::Documentation;
28+
use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
29+
use datafusion_functions_aggregate::min_max;
30+
use datafusion_macros::user_doc;
31+
use itertools::Itertools;
32+
use std::any::Any;
33+
34+
make_udf_expr_and_func!(
35+
ArrayMin,
36+
array_min,
37+
array,
38+
"returns the minimum value in the array.",
39+
array_min_udf
40+
);
41+
42+
#[user_doc(
43+
doc_section(label = "Array Functions"),
44+
description = "Returns the minimum value in the array.",
45+
syntax_example = "array_min(array)",
46+
sql_example = r#"```sql
47+
> select array_min([3,1,4,2]);
48+
+-----------------------------------------+
49+
| array_min(List([3,1,4,2])) |
50+
+-----------------------------------------+
51+
| 1 |
52+
+-----------------------------------------+
53+
```"#,
54+
argument(
55+
name = "array",
56+
description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
57+
)
58+
)]
59+
#[derive(Debug)]
60+
pub struct ArrayMin {
61+
signature: Signature,
62+
aliases: Vec<String>,
63+
}
64+
65+
impl Default for ArrayMin {
66+
fn default() -> Self {
67+
Self::new()
68+
}
69+
}
70+
71+
impl ArrayMin {
72+
pub fn new() -> Self {
73+
Self {
74+
signature: Signature::array(Volatility::Immutable),
75+
aliases: vec!["list_min".to_string()],
76+
}
77+
}
78+
}
79+
80+
impl ScalarUDFImpl for ArrayMin {
81+
fn as_any(&self) -> &dyn Any {
82+
self
83+
}
84+
85+
fn name(&self) -> &str {
86+
"array_min"
87+
}
88+
89+
fn signature(&self) -> &Signature {
90+
&self.signature
91+
}
92+
93+
fn return_type(&self, arg_types: &[DataType]) -> datafusion_common::Result<DataType> {
94+
match &arg_types[0] {
95+
List(field) => Ok(field.data_type().clone()),
96+
_ => exec_err!("Not reachable, data_type should be List"),
97+
}
98+
}
99+
100+
fn invoke_batch(
101+
&self,
102+
args: &[ColumnarValue],
103+
_number_rows: usize,
104+
) -> datafusion_common::Result<ColumnarValue> {
105+
make_scalar_function(array_min_inner)(args)
106+
}
107+
108+
fn aliases(&self) -> &[String] {
109+
&self.aliases
110+
}
111+
112+
fn documentation(&self) -> Option<&Documentation> {
113+
self.doc()
114+
}
115+
}
116+
117+
/// array_min SQL function
118+
///
119+
/// There is one argument for array_min as the array.
120+
/// `array_min(array)`
121+
///
122+
/// For example:
123+
/// > array_min(\[3, 1, 2]) -> 1
124+
pub fn array_min_inner(args: &[ArrayRef]) -> datafusion_common::Result<ArrayRef> {
125+
let [arg1] = take_function_args("array_min", args)?;
126+
127+
match &arg1.data_type() {
128+
List(_) => {
129+
let input_list_array = as_list_array(&arg1)?;
130+
let result_vec = input_list_array
131+
.iter()
132+
.flat_map(|arr| min_max::min_batch(&arr.unwrap()))
133+
.collect_vec();
134+
135+
ScalarValue::iter_to_array(result_vec)
136+
}
137+
_ => exec_err!("array_min does not support type: {:?}", args[0].data_type()),
138+
}
139+
}

datafusion/sqllogictest/test_files/array.slt

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1521,6 +1521,90 @@ NULL
15211521
query error DataFusion error: Error during planning: 'array_max' does not support zero arguments
15221522
select array_max();
15231523

1524+
## array_min
1525+
# array_min scalar function #1 (with positive index)
1526+
query I
1527+
select array_min(make_array(5, 3, 4, 6));
1528+
----
1529+
3
1530+
1531+
query I
1532+
select array_min(make_array(5, 3, 4, NULL, 6, NULL));
1533+
----
1534+
3
1535+
1536+
query I
1537+
select array_min(make_array(NULL, NULL));
1538+
----
1539+
NULL
1540+
1541+
query T
1542+
select array_min(make_array('h', 'e', 'l', 'l', 'o'));
1543+
----
1544+
e
1545+
1546+
query T
1547+
select array_min(make_array('h', 'e', 'l', NULL, 'l', 'o', NULL));
1548+
----
1549+
e
1550+
1551+
query B
1552+
select array_min(make_array(true, true, false, true));
1553+
----
1554+
false
1555+
1556+
query B
1557+
select array_min(make_array(true, true, NULL, false, true));
1558+
----
1559+
false
1560+
1561+
query D
1562+
select array_min(make_array(DATE '1992-09-01', DATE '1993-03-01', DATE '1985-11-01', DATE '1999-05-01'));
1563+
----
1564+
1985-11-01
1565+
1566+
query D
1567+
select array_min(make_array(DATE '1995-09-01', DATE '1993-03-01', NULL, DATE '1999-05-01'));
1568+
----
1569+
1993-03-01
1570+
1571+
query P
1572+
select array_min(make_array(TIMESTAMP '1992-09-01', TIMESTAMP '1984-10-01', TIMESTAMP '1995-06-01'));
1573+
----
1574+
1984-10-01T00:00:00
1575+
1576+
query R
1577+
select array_min(make_array(5.1, -3.2, 6.3, 4.9));
1578+
----
1579+
-3.2
1580+
1581+
query P
1582+
select array_min(make_array(NULL, TIMESTAMP '1996-10-01', TIMESTAMP '1995-06-01'));
1583+
----
1584+
1995-06-01T00:00:00
1585+
1586+
query ?I
1587+
select input, array_min(input) from (select make_array(d - 1, d, d + 1) input from (values (0), (10), (20), (30), (NULL)) t(d))
1588+
----
1589+
[-1, 0, 1] -1
1590+
[9, 10, 11] 9
1591+
[19, 20, 21] 19
1592+
[29, 30, 31] 29
1593+
[NULL, NULL, NULL] NULL
1594+
1595+
query II
1596+
select array_min(arrow_cast(make_array(2, 1, 3), 'FixedSizeList(3, Int64)')), array_min(arrow_cast(make_array(2), 'FixedSizeList(1, Int64)'));
1597+
----
1598+
1 2
1599+
1600+
query I
1601+
select array_min(make_array());
1602+
----
1603+
NULL
1604+
1605+
# Testing with empty arguments should result in an error
1606+
query error DataFusion error: Error during planning: 'array_min' does not support zero arguments
1607+
select array_min();
15241608

15251609
## array_pop_back (aliases: `list_pop_back`)
15261610

docs/source/user-guide/sql/scalar_functions.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2525,6 +2525,7 @@ _Alias of [current_date](#current_date)._
25252525
- [array_join](#array_join)
25262526
- [array_length](#array_length)
25272527
- [array_max](#array_max)
2528+
- [array_min](#array_min)
25282529
- [array_ndims](#array_ndims)
25292530
- [array_pop_back](#array_pop_back)
25302531
- [array_pop_front](#array_pop_front)
@@ -2571,6 +2572,7 @@ _Alias of [current_date](#current_date)._
25712572
- [list_join](#list_join)
25722573
- [list_length](#list_length)
25732574
- [list_max](#list_max)
2575+
- [list_min](#list_min)
25742576
- [list_ndims](#list_ndims)
25752577
- [list_pop_back](#list_pop_back)
25762578
- [list_pop_front](#list_pop_front)
@@ -3031,6 +3033,33 @@ array_max(array)
30313033

30323034
- list_max
30333035

3036+
### `array_min`
3037+
3038+
Returns the minimum value in the array.
3039+
3040+
```sql
3041+
array_min(array)
3042+
```
3043+
3044+
#### Arguments
3045+
3046+
- **array**: Array expression. Can be a constant, column, or function, and any combination of array operators.
3047+
3048+
#### Example
3049+
3050+
```sql
3051+
> select array_min([3,1,4,2]);
3052+
+-----------------------------------------+
3053+
| array_min(List([3,1,4,2])) |
3054+
+-----------------------------------------+
3055+
| 1 |
3056+
+-----------------------------------------+
3057+
```
3058+
3059+
#### Aliases
3060+
3061+
- list_min
3062+
30343063
### `array_ndims`
30353064

30363065
Returns the number of dimensions of the array.
@@ -3792,6 +3821,10 @@ _Alias of [array_length](#array_length)._
37923821

37933822
_Alias of [array_max](#array_max)._
37943823

3824+
### `list_min`
3825+
3826+
_Alias of [array_min](#array_min)._
3827+
37953828
### `list_ndims`
37963829

37973830
_Alias of [array_ndims](#array_ndims)._

0 commit comments

Comments
 (0)