Skip to main content

datafusion_functions_nested/
map_extract.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 map_extract functions.
6
7use crate::utils::get_map_entry_field;
8use arrow::array::{Array, ArrayRef, ListArray, MapArray, UInt32Array};
9use arrow::buffer::OffsetBuffer;
10use arrow::compute::take;
11use arrow::datatypes::{DataType, Field};
12use datafusion_common::utils::take_function_args;
13use datafusion_common::{Result, cast::as_map_array, exec_err};
14use datafusion_expr::function::Hint;
15use datafusion_expr::{
16    ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
17    Volatility,
18};
19use datafusion_functions::utils::{make_scalar_function, map_lookup};
20use datafusion_macros::user_doc;
21use std::sync::Arc;
22
23// Create static instances of ScalarUDFs for each function
24make_udf_expr_and_func!(
25    MapExtract,
26    map_extract,
27    map key,
28    "Return a list containing the value for a given key or an empty list if the key is not contained in the map.",
29    map_extract_udf
30);
31
32#[user_doc(
33    doc_section(label = "Map Functions"),
34    description = "Returns a list containing the value for the given key or an empty list if the key is not present in the map.",
35    syntax_example = "map_extract(map, key)",
36    sql_example = r#"```sql
37SELECT map_extract(MAP {'a': 1, 'b': NULL, 'c': 3}, 'a');
38----
39[1]
40
41SELECT map_extract(MAP {1: 'one', 2: 'two'}, 2);
42----
43['two']
44
45SELECT map_extract(MAP {'x': 10, 'y': NULL, 'z': 30}, 'y');
46----
47[NULL]
48
49-- non-existing key
50SELECT map_extract(MAP {'x': 10, 'y': NULL, 'z': 30}, 'a');
51----
52[]
53```"#,
54    argument(
55        name = "map",
56        description = "Map expression. Can be a constant, column, or function, and any combination of map operators."
57    ),
58    argument(
59        name = "key",
60        description = "Key to extract from the map. Can be a constant, column, or function, any combination of arithmetic or string operators, or a named expression of the previously listed."
61    )
62)]
63#[derive(Debug, PartialEq, Eq, Hash)]
64pub struct MapExtract {
65    signature: Signature,
66    aliases: Vec<String>,
67}
68
69impl Default for MapExtract {
70    fn default() -> Self {
71        Self::new()
72    }
73}
74
75impl MapExtract {
76    pub fn new() -> Self {
77        Self {
78            signature: Signature::user_defined(Volatility::Immutable),
79            aliases: vec![String::from("element_at")],
80        }
81    }
82}
83
84impl ScalarUDFImpl for MapExtract {
85    fn name(&self) -> &str {
86        "map_extract"
87    }
88
89    fn signature(&self) -> &Signature {
90        &self.signature
91    }
92
93    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
94        let [map_type, _] = take_function_args(self.name(), arg_types)?;
95
96        if map_type.is_null() {
97            return Ok(DataType::Null);
98        }
99
100        let map_fields = get_map_entry_field(map_type)?;
101        Ok(DataType::List(Arc::new(Field::new_list_field(
102            map_fields.last().unwrap().data_type().clone(),
103            true,
104        ))))
105    }
106
107    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
108        // A scalar key is passed through as a single row rather than expanded
109        // to the batch size; the lookup applies it to every map row.
110        make_scalar_function(map_extract_inner, vec![Hint::Pad, Hint::AcceptsSingular])(
111            &args.args,
112        )
113    }
114
115    fn aliases(&self) -> &[String] {
116        &self.aliases
117    }
118
119    fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
120        let [map_type, _] = take_function_args(self.name(), arg_types)?;
121
122        if map_type.is_null() {
123            return Ok(arg_types.to_vec());
124        }
125
126        let field = get_map_entry_field(map_type)?;
127        Ok(vec![
128            map_type.clone(),
129            field.first().unwrap().data_type().clone(),
130        ])
131    }
132
133    fn documentation(&self) -> Option<&Documentation> {
134        self.doc()
135    }
136}
137
138fn general_map_extract_inner(
139    map_array: &MapArray,
140    query_keys_array: &dyn Array,
141) -> Result<ArrayRef> {
142    let indices = map_lookup(map_array, query_keys_array)?;
143    // Each matched row contributes one list element. Every other row is an
144    // empty list, or NULL when the map itself is NULL.
145    let lengths = indices.iter().map(|index| usize::from(index.is_some()));
146    let mut matched = Vec::with_capacity(indices.len() - indices.null_count());
147    matched.extend(indices.iter().flatten());
148    let values = take(
149        map_array.values().as_ref(),
150        &UInt32Array::from(matched),
151        None,
152    )?;
153    Ok(Arc::new(ListArray::new(
154        Arc::new(Field::new_list_field(map_array.value_type().clone(), true)),
155        OffsetBuffer::from_lengths(lengths),
156        values,
157        map_array.nulls().cloned(),
158    )))
159}
160
161fn map_extract_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
162    let [map_arg, key_arg] = take_function_args("map_extract", args)?;
163    match map_arg.data_type() {
164        DataType::Map(_, _) => {
165            general_map_extract_inner(as_map_array(map_arg.as_ref())?, key_arg.as_ref())
166        }
167        DataType::Null => Ok(Arc::clone(map_arg)),
168        _ => exec_err!("The first argument in map_extract must be a map"),
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175    use arrow::array::{Float64Array, Int32Array, NullArray, StructArray};
176    use arrow::buffer::NullBuffer;
177    use arrow::datatypes::Int32Type;
178
179    fn make_map(
180        keys: ArrayRef,
181        values: Vec<i32>,
182        offsets: Vec<i32>,
183        nulls: Option<NullBuffer>,
184    ) -> MapArray {
185        let entries = StructArray::from(vec![
186            (
187                Arc::new(Field::new("key", keys.data_type().clone(), false)),
188                keys,
189            ),
190            (
191                Arc::new(Field::new("value", DataType::Int32, true)),
192                Arc::new(Int32Array::from(values)) as ArrayRef,
193            ),
194        ]);
195        MapArray::new(
196            Arc::new(Field::new("entries", entries.data_type().clone(), false)),
197            OffsetBuffer::new(offsets.into()),
198            entries,
199            nulls,
200            false,
201        )
202    }
203
204    #[test]
205    fn map_extract_sliced_maps() -> Result<()> {
206        let map = make_map(
207            Arc::new(Int32Array::from(vec![0, 1, 2, 3])),
208            vec![0, 10, 20, 30],
209            vec![0, 1, 3, 4],
210            None,
211        );
212        let query_keys = Int32Array::from(vec![0, 2, 9]);
213
214        // Map offsets address the original entries; query indices address the slice.
215        let result =
216            general_map_extract_inner(&map.slice(1, 2), &query_keys.slice(1, 2))?;
217        let expected = ListArray::from_iter_primitive::<Int32Type, _, _>([
218            Some(vec![Some(20)]),
219            Some(vec![]),
220        ]);
221        assert_eq!(result.as_ref(), &expected);
222
223        // Empty slices may retain the original nonempty keys and values buffers.
224        let result =
225            general_map_extract_inner(&map.slice(1, 0), &query_keys.slice(1, 0))?;
226        assert_eq!(result.len(), 0);
227        Ok(())
228    }
229
230    #[test]
231    fn map_extract_all_empty_maps_with_nulls() -> Result<()> {
232        // No entries exist to scan, but the null map must still produce NULL
233        // rather than an empty list.
234        let map = make_map(
235            Arc::new(Int32Array::from(Vec::<i32>::new())),
236            vec![],
237            vec![0, 0, 0],
238            Some(NullBuffer::from(vec![true, false])),
239        );
240        let result = general_map_extract_inner(&map, &Int32Array::from(vec![1, 1]))?;
241        let expected =
242            ListArray::from_iter_primitive::<Int32Type, _, _>([Some(vec![]), None]);
243        assert_eq!(result.as_ref(), &expected);
244        Ok(())
245    }
246
247    #[test]
248    fn map_extract_untyped_null_keys() -> Result<()> {
249        let map = make_map(
250            Arc::new(Int32Array::from(vec![1, 2])),
251            vec![10, 20],
252            vec![0, 1, 2],
253            Some(NullBuffer::from(vec![true, false])),
254        );
255        let expected =
256            ListArray::from_iter_primitive::<Int32Type, _, _>([Some(vec![]), None]);
257        // Direct callers can pass untyped NULLs without SQL's key coercion.
258        for len in [1, map.len()] {
259            let result = general_map_extract_inner(&map, &NullArray::new(len))?;
260            assert_eq!(result.as_ref(), &expected);
261        }
262        Ok(())
263    }
264
265    #[test]
266    fn map_extract_float_keys() -> Result<()> {
267        let nan = f64::NAN;
268        let other_nan = f64::from_bits(nan.to_bits() + 1);
269        let map = make_map(
270            Arc::new(Float64Array::from(vec![-0.0, 0.0, nan, other_nan])),
271            vec![1, 2, 3, 4],
272            vec![0, 4],
273            None,
274        );
275
276        // Signed zeros and distinct NaN payloads identify different keys.
277        for (query, expected) in [(-0.0, 1), (0.0, 2), (nan, 3), (other_nan, 4)] {
278            let result =
279                general_map_extract_inner(&map, &Float64Array::from(vec![query]))?;
280            let expected = ListArray::from_iter_primitive::<Int32Type, _, _>([Some(
281                vec![Some(expected)],
282            )]);
283            assert_eq!(result.as_ref(), &expected);
284        }
285        Ok(())
286    }
287}