datafusion_functions_nested/
map_extract.rs1use crate::utils::{get_map_entry_field, make_scalar_function};
21use arrow::array::{
22 Array, ArrayRef, Capacities, ListArray, MapArray, MutableArrayData, make_array,
23};
24use arrow::buffer::OffsetBuffer;
25use arrow::datatypes::{DataType, Field};
26use datafusion_common::utils::take_function_args;
27use datafusion_common::{Result, cast::as_map_array, exec_err};
28use datafusion_expr::{
29 ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
30 Volatility,
31};
32use datafusion_macros::user_doc;
33use std::sync::Arc;
34use std::vec;
35
36make_udf_expr_and_func!(
38 MapExtract,
39 map_extract,
40 map key,
41 "Return a list containing the value for a given key or an empty list if the key is not contained in the map.",
42 map_extract_udf
43);
44
45#[user_doc(
46 doc_section(label = "Map Functions"),
47 description = "Returns a list containing the value for the given key or an empty list if the key is not present in the map.",
48 syntax_example = "map_extract(map, key)",
49 sql_example = r#"```sql
50SELECT map_extract(MAP {'a': 1, 'b': NULL, 'c': 3}, 'a');
51----
52[1]
53
54SELECT map_extract(MAP {1: 'one', 2: 'two'}, 2);
55----
56['two']
57
58SELECT map_extract(MAP {'x': 10, 'y': NULL, 'z': 30}, 'y');
59----
60[NULL]
61
62-- non-existing key
63SELECT map_extract(MAP {'x': 10, 'y': NULL, 'z': 30}, 'a');
64----
65[]
66```"#,
67 argument(
68 name = "map",
69 description = "Map expression. Can be a constant, column, or function, and any combination of map operators."
70 ),
71 argument(
72 name = "key",
73 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."
74 )
75)]
76#[derive(Debug, PartialEq, Eq, Hash)]
77pub struct MapExtract {
78 signature: Signature,
79 aliases: Vec<String>,
80}
81
82impl Default for MapExtract {
83 fn default() -> Self {
84 Self::new()
85 }
86}
87
88impl MapExtract {
89 pub fn new() -> Self {
90 Self {
91 signature: Signature::user_defined(Volatility::Immutable),
92 aliases: vec![String::from("element_at")],
93 }
94 }
95}
96
97impl ScalarUDFImpl for MapExtract {
98 fn name(&self) -> &str {
99 "map_extract"
100 }
101
102 fn signature(&self) -> &Signature {
103 &self.signature
104 }
105
106 fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
107 let [map_type, _] = take_function_args(self.name(), arg_types)?;
108
109 if map_type.is_null() {
110 return Ok(DataType::Null);
111 }
112
113 let map_fields = get_map_entry_field(map_type)?;
114 Ok(DataType::List(Arc::new(Field::new_list_field(
115 map_fields.last().unwrap().data_type().clone(),
116 true,
117 ))))
118 }
119
120 fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
121 make_scalar_function(map_extract_inner)(&args.args)
122 }
123
124 fn aliases(&self) -> &[String] {
125 &self.aliases
126 }
127
128 fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
129 let [map_type, _] = take_function_args(self.name(), arg_types)?;
130
131 if map_type.is_null() {
132 return Ok(arg_types.to_vec());
133 }
134
135 let field = get_map_entry_field(map_type)?;
136 Ok(vec![
137 map_type.clone(),
138 field.first().unwrap().data_type().clone(),
139 ])
140 }
141
142 fn documentation(&self) -> Option<&Documentation> {
143 self.doc()
144 }
145}
146
147fn general_map_extract_inner(
148 map_array: &MapArray,
149 query_keys_array: &dyn Array,
150) -> Result<ArrayRef> {
151 let keys = map_array.keys();
152 let mut offsets = vec![0_i32];
153
154 let values = map_array.values();
155 let original_data = values.to_data();
156 let capacity = Capacities::Array(original_data.len());
157
158 let mut mutable =
159 MutableArrayData::with_capacities(vec![&original_data], true, capacity);
160
161 for (row_index, offset_window) in map_array.value_offsets().windows(2).enumerate() {
162 let start = offset_window[0] as usize;
163 let end = offset_window[1] as usize;
164 let len = end - start;
165
166 let query_key = query_keys_array.slice(row_index, 1);
167
168 let value_index =
169 (0..len).find(|&i| keys.slice(start + i, 1).as_ref() == query_key.as_ref());
170
171 match value_index {
172 Some(index) => {
173 mutable.extend(0, start + index, start + index + 1);
174 }
175 None => {
176 mutable.extend_nulls(1);
177 }
178 }
179 offsets.push(offsets[row_index] + 1);
180 }
181
182 let data = mutable.freeze();
183
184 Ok(Arc::new(ListArray::new(
185 Arc::new(Field::new_list_field(map_array.value_type().clone(), true)),
186 OffsetBuffer::<i32>::new(offsets.into()),
187 Arc::new(make_array(data)),
188 None,
189 )))
190}
191
192fn map_extract_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
193 let [map_arg, key_arg] = take_function_args("map_extract", args)?;
194
195 let map_array = match map_arg.data_type() {
196 DataType::Map(_, _) => as_map_array(&map_arg)?,
197 DataType::Null => return Ok(Arc::clone(map_arg)),
198 _ => return exec_err!("The first argument in map_extract must be a map"),
199 };
200
201 let key_type = map_array.key_type();
202
203 if key_type != key_arg.data_type() {
204 return exec_err!(
205 "The key type {} does not match the map key type {}",
206 key_arg.data_type(),
207 key_type
208 );
209 }
210
211 general_map_extract_inner(map_array, key_arg)
212}