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