Skip to main content

datafusion_functions_nested/
array_first.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//! [`datafusion_expr::HigherOrderUDF`] definitions for array_first function.
6
7use arrow::{
8    array::{Array, BooleanArray, UInt64Array, UInt64Builder},
9    compute::take,
10    datatypes::{DataType, FieldRef},
11};
12use datafusion_common::{Result, exec_err, plan_err};
13use datafusion_expr::{
14    ColumnarValue, Documentation, HigherOrderFunctionArgs, HigherOrderReturnFieldArgs,
15    HigherOrderSignature, HigherOrderUDFImpl, LambdaParametersProgress, ValueOrLambda,
16    Volatility,
17};
18use datafusion_macros::user_doc;
19use std::sync::Arc;
20
21use crate::lambda_utils::{
22    SingleListLambdaResult, coerce_single_list_arg, evaluate_single_list_predicate,
23    single_list_lambda_parameters, value_lambda_pair,
24};
25
26make_higher_order_function_expr_and_func!(
27    ArrayFirst,
28    array_first,
29    array lambda,
30    "returns the first element of an array that satisfies the predicate",
31    array_first_higher_order_function
32);
33
34#[user_doc(
35    doc_section(label = "Array Functions"),
36    description = "Returns the first element of an array that satisfies the given predicate. Returns null if the array is empty or no element matches. A predicate that returns null for an element is treated as not matching.",
37    syntax_example = "array_first(array, predicate)",
38    sql_example = r#"```sql
39> select array_first([1, 2, 3, 4], x -> x > 2);
40+----------------------------------------+
41| array_first([1,2,3,4],x -> x > 2)      |
42+----------------------------------------+
43| 3                                      |
44+----------------------------------------+
45```"#,
46    argument(
47        name = "array",
48        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
49    ),
50    argument(
51        name = "predicate",
52        description = "Lambda predicate that returns a boolean. The first element for which it returns true is returned."
53    )
54)]
55#[derive(Debug, PartialEq, Eq, Hash)]
56pub struct ArrayFirst {
57    signature: HigherOrderSignature,
58    aliases: Vec<String>,
59}
60
61impl Default for ArrayFirst {
62    fn default() -> Self {
63        Self::new()
64    }
65}
66
67impl ArrayFirst {
68    pub fn new() -> Self {
69        Self {
70            signature: HigherOrderSignature::exact(
71                vec![ValueOrLambda::Value(()), ValueOrLambda::Lambda(())],
72                Volatility::Immutable,
73            ),
74            aliases: vec![String::from("list_first")],
75        }
76    }
77}
78
79impl HigherOrderUDFImpl for ArrayFirst {
80    fn name(&self) -> &str {
81        "array_first"
82    }
83
84    fn aliases(&self) -> &[String] {
85        &self.aliases
86    }
87
88    fn signature(&self) -> &HigherOrderSignature {
89        &self.signature
90    }
91
92    fn coerce_value_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
93        coerce_single_list_arg(self.name(), arg_types)
94    }
95
96    fn lambda_parameters(
97        &self,
98        _step: usize,
99        fields: &[ValueOrLambda<FieldRef, Option<FieldRef>>],
100    ) -> Result<LambdaParametersProgress> {
101        single_list_lambda_parameters(self.name(), fields)
102    }
103
104    fn return_field_from_args(
105        &self,
106        args: HigherOrderReturnFieldArgs,
107    ) -> Result<FieldRef> {
108        let (list, _lambda) = value_lambda_pair(self.name(), args.arg_fields)?;
109
110        let element_field = match list.data_type() {
111            DataType::List(field) | DataType::LargeList(field) => field,
112            other => {
113                return plan_err!(
114                    "{} expected a list as first argument, got {other}",
115                    self.name()
116                );
117            }
118        };
119
120        // The result is a single element of the array. It is always nullable
121        // because an empty array (or no matching element) yields null.
122        Ok(Arc::new(
123            element_field
124                .as_ref()
125                .clone()
126                .with_name("")
127                .with_nullable(true),
128        ))
129    }
130
131    fn invoke_with_args(&self, args: HigherOrderFunctionArgs) -> Result<ColumnarValue> {
132        let evaluated = match evaluate_single_list_predicate(self.name(), &args)? {
133            SingleListLambdaResult::EarlyReturn(v) => return Ok(v),
134            SingleListLambdaResult::Ready(v) => v,
135        };
136
137        let predicate = evaluated.boolean_predicate(self.name())?;
138        let indices = match evaluated.original_list.data_type() {
139            DataType::List(_) | DataType::LargeList(_) => {
140                first_match_indices(&evaluated.row_offsets()?, &predicate)
141            }
142            other => return exec_err!("expected list, got {other}"),
143        };
144
145        let result = take(evaluated.flattened_values.as_ref(), &indices, None)?;
146        Ok(ColumnarValue::Array(result))
147    }
148
149    fn documentation(&self) -> Option<&Documentation> {
150        self.doc()
151    }
152}
153
154/// Builds a `UInt64` index array (one entry per sublist) pointing at the first
155/// element whose predicate is true, or null when no element matches. Indices are
156/// absolute into the (sliced) flat values array, so `take` gathers the matches.
157///
158/// A null predicate value is treated as not matching. The matched element itself
159/// may be null and is still returned.
160fn first_match_indices(row_offsets: &[usize], predicate: &BooleanArray) -> UInt64Array {
161    let mut builder = UInt64Builder::with_capacity(row_offsets.len() - 1);
162
163    for window in row_offsets.windows(2) {
164        let (start, end) = (window[0], window[1]);
165
166        match (start..end).find(|&j| predicate.is_valid(j) && predicate.value(j)) {
167            Some(j) => builder.append_value(j as u64),
168            None => builder.append_null(),
169        }
170    }
171
172    builder.finish()
173}
174
175#[cfg(test)]
176mod tests {
177    use arrow::{
178        array::{Array, AsArray, Int32Array, StringArray},
179        buffer::{NullBuffer, OffsetBuffer},
180        datatypes::Int32Type,
181    };
182
183    use crate::array_first::array_first_higher_order_function;
184    use crate::lambda_utils::test_utils::{
185        create_i32_large_list, create_i32_list, eval_hof_on_i32_list,
186        eval_hof_on_i32_list_with_outer, v,
187    };
188    use datafusion_common::Result;
189    use datafusion_expr::{col, lit};
190
191    fn first_greater_than_two(
192        list: impl Array + Clone + 'static,
193    ) -> Result<arrow::array::ArrayRef> {
194        eval_hof_on_i32_list(array_first_higher_order_function(), list, v().gt(lit(2i32)))
195    }
196
197    // predicate: (100 / v) > 5; panics on divide by zero if v == 0 is evaluated
198    fn first_where_hundred_div_gt_five(
199        list: impl Array + Clone + 'static,
200    ) -> Result<arrow::array::ArrayRef> {
201        eval_hof_on_i32_list(
202            array_first_higher_order_function(),
203            list,
204            (lit(100i32) / v()).gt(lit(5i32)),
205        )
206    }
207
208    #[test]
209    fn test_first_basic() -> Result<()> {
210        let list = create_i32_list(
211            vec![1, 2, 3, 4, 5],
212            OffsetBuffer::<i32>::from_lengths(vec![5]),
213            None,
214        );
215        let res = first_greater_than_two(list)?;
216        assert_eq!(
217            res.as_primitive::<Int32Type>(),
218            &Int32Array::from(vec![Some(3)])
219        );
220        Ok(())
221    }
222
223    #[test]
224    fn test_first_no_match_is_null() -> Result<()> {
225        let list =
226            create_i32_list(vec![1, 2], OffsetBuffer::<i32>::from_lengths(vec![2]), None);
227        let res = first_greater_than_two(list)?;
228        assert_eq!(
229            res.as_primitive::<Int32Type>(),
230            &Int32Array::from(vec![None])
231        );
232        Ok(())
233    }
234
235    #[test]
236    fn test_first_empty_array_is_null() -> Result<()> {
237        let list = create_i32_list(
238            Vec::<i32>::new(),
239            OffsetBuffer::<i32>::from_lengths(vec![0]),
240            None,
241        );
242        let res = first_greater_than_two(list)?;
243        assert_eq!(
244            res.as_primitive::<Int32Type>(),
245            &Int32Array::from(vec![None])
246        );
247        Ok(())
248    }
249
250    #[test]
251    fn test_first_multiple_sublists() -> Result<()> {
252        // [1,5] -> 5, [2,4,3] -> 4, [1,2] -> null
253        let list = create_i32_list(
254            vec![1, 5, 2, 4, 3, 1, 2],
255            OffsetBuffer::<i32>::from_lengths(vec![2, 3, 2]),
256            None,
257        );
258        let res = first_greater_than_two(list)?;
259        assert_eq!(
260            res.as_primitive::<Int32Type>(),
261            &Int32Array::from(vec![Some(5), Some(4), None])
262        );
263        Ok(())
264    }
265
266    #[test]
267    fn test_first_null_predicate_element_is_skipped() -> Result<()> {
268        // [1, NULL, 4] with v > 2: the NULL element's predicate is null and is
269        // skipped, so the first match is 4.
270        let list = create_i32_list(
271            Int32Array::from(vec![Some(1), None, Some(4)]),
272            OffsetBuffer::<i32>::from_lengths(vec![3]),
273            None,
274        );
275        let res = first_greater_than_two(list)?;
276        assert_eq!(
277            res.as_primitive::<Int32Type>(),
278            &Int32Array::from(vec![Some(4)])
279        );
280        Ok(())
281    }
282
283    #[test]
284    fn test_first_matched_null_element_is_returned() -> Result<()> {
285        // [1, NULL, 3] with `v IS NULL`: the first match is the null element,
286        // which is returned as null.
287        let list = create_i32_list(
288            Int32Array::from(vec![Some(1), None, Some(3)]),
289            OffsetBuffer::<i32>::from_lengths(vec![3]),
290            None,
291        );
292        let res = eval_hof_on_i32_list(
293            array_first_higher_order_function(),
294            list,
295            v().is_null(),
296        )?;
297        assert_eq!(
298            res.as_primitive::<Int32Type>(),
299            &Int32Array::from(vec![None])
300        );
301        Ok(())
302    }
303
304    // The 0 in the null row would divide by zero if the predicate were evaluated
305    // on it. The result for the null row must be null.
306    #[test]
307    fn test_first_does_not_evaluate_predicate_on_null_row_values() -> Result<()> {
308        let list = create_i32_list(
309            vec![1, 2, 0, 4, 5],
310            OffsetBuffer::<i32>::from_lengths(vec![3, 2]),
311            Some(NullBuffer::from(vec![false, true])),
312        );
313        let res = first_where_hundred_div_gt_five(list)?;
314        assert_eq!(
315            res.as_primitive::<Int32Type>(),
316            &Int32Array::from(vec![None, Some(4)])
317        );
318        Ok(())
319    }
320
321    // The 0 before the slice offset would divide by zero if evaluated.
322    #[test]
323    fn test_first_does_not_evaluate_predicate_on_unreachable_values() -> Result<()> {
324        // sublists: [0], [4,5], [50,100]; slice away the first
325        let list = create_i32_list(
326            vec![0, 4, 5, 50, 100],
327            OffsetBuffer::<i32>::from_lengths(vec![1, 2, 2]),
328            None,
329        )
330        .slice(1, 2);
331        let res = first_where_hundred_div_gt_five(list)?;
332        // [4,5]: 100/4=25>5 -> 4. [50,100]: 2>5 false, 1>5 false -> null
333        assert_eq!(
334            res.as_primitive::<Int32Type>(),
335            &Int32Array::from(vec![Some(4), None])
336        );
337        Ok(())
338    }
339
340    #[test]
341    fn test_first_eagerly_evaluates_predicate_after_match() {
342        // Although 4 is the first match, the predicate is evaluated for the
343        // later 0 in the same sublist and produces a division-by-zero error.
344        let list =
345            create_i32_list(vec![4, 0], OffsetBuffer::<i32>::from_lengths(vec![2]), None);
346
347        let err = first_where_hundred_div_gt_five(list).unwrap_err();
348        assert!(
349            err.to_string().contains("Divide by zero"),
350            "unexpected error: {err}"
351        );
352    }
353
354    #[test]
355    fn test_first_large_list_parity() -> Result<()> {
356        let list = create_i32_large_list(
357            vec![1, 2, 3, 4, 5],
358            OffsetBuffer::<i64>::from_lengths(vec![5]),
359            None,
360        );
361        let res = first_greater_than_two(list)?;
362        assert_eq!(
363            res.as_primitive::<Int32Type>(),
364            &Int32Array::from(vec![Some(3)])
365        );
366        Ok(())
367    }
368
369    #[test]
370    fn test_first_captured_outer_column() -> Result<()> {
371        let list = create_i32_list(
372            vec![1, 50, 4, 50, 7, 50],
373            OffsetBuffer::<i32>::from_lengths(vec![2, 2, 2]),
374            None,
375        );
376        let number = Int32Array::from(vec![10, 40, 60]);
377        let res = eval_hof_on_i32_list_with_outer(
378            array_first_higher_order_function(),
379            list,
380            number,
381            v().gt(col("number")),
382        )?;
383        assert_eq!(
384            res.as_primitive::<Int32Type>(),
385            &Int32Array::from(vec![Some(50), Some(50), None])
386        );
387        Ok(())
388    }
389
390    #[test]
391    fn test_first_string_elements() -> Result<()> {
392        use arrow::array::ListArray;
393        use arrow::datatypes::{DataType, Field};
394        use datafusion_expr::Expr;
395        use datafusion_expr::expr::LambdaVariable;
396        use std::sync::Arc;
397
398        // ['a', 'bb', 'ccc'] with v > 'a' -> 'bb' (exercises take on a non-primitive type)
399        let values = StringArray::from(vec!["a", "bb", "ccc"]);
400        let list = ListArray::new(
401            Arc::new(Field::new_list_field(DataType::Utf8, true)),
402            OffsetBuffer::<i32>::from_lengths(vec![3]),
403            Arc::new(values),
404            None,
405        );
406
407        let x = Expr::LambdaVariable(LambdaVariable::new(
408            "v".to_string(),
409            Some(Arc::new(Field::new("v", DataType::Utf8, true))),
410        ));
411        let body = x.gt(lit("a"));
412
413        let res = eval_hof_on_i32_list(array_first_higher_order_function(), list, body)?;
414        assert_eq!(res.as_string::<i32>(), &StringArray::from(vec![Some("bb")]));
415        Ok(())
416    }
417}