1use arrow::array::Scalar;
8use arrow::buffer::OffsetBuffer;
9use arrow::datatypes::DataType;
10use arrow::datatypes::{
11 DataType::{LargeList, List, UInt64},
12 Field,
13};
14use datafusion_common::ScalarValue;
15use datafusion_expr::{
16 ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
17 Volatility,
18};
19use datafusion_macros::user_doc;
20
21use std::sync::Arc;
22
23use arrow::array::{
24 Array, ArrayRef, GenericListArray, ListArray, OffsetSizeTrait, UInt64Array,
25 types::UInt64Type,
26};
27use datafusion_common::cast::{
28 as_generic_list_array, as_int64_array, as_large_list_array, as_list_array,
29};
30use datafusion_common::utils::offset_span;
31use datafusion_common::{
32 Result, exec_datafusion_err, exec_err, utils::take_function_args,
33};
34use itertools::Itertools;
35
36use crate::utils::{compare_element_to_list, make_scalar_function};
37
38make_udf_expr_and_func!(
39 ArrayPosition,
40 array_position,
41 array element index,
42 "searches for an element in the array, returns first occurrence.",
43 array_position_udf
44);
45
46#[user_doc(
47 doc_section(label = "Array Functions"),
48 description = "Returns the position of the first occurrence of the specified element in the array, or NULL if not found. Comparisons are done using `IS DISTINCT FROM` semantics, so NULL is considered to match NULL.",
49 syntax_example = "array_position(array, element[, index])",
50 sql_example = r#"```sql
51> select array_position([1, 2, 2, 3, 1, 4], 2);
52+----------------------------------------------+
53| array_position(List([1,2,2,3,1,4]),Int64(2)) |
54+----------------------------------------------+
55| 2 |
56+----------------------------------------------+
57> select array_position([1, 2, 2, 3, 1, 4], 2, 3);
58+--------------------------------------------------------+
59| array_position(List([1,2,2,3,1,4]),Int64(2), Int64(3)) |
60+--------------------------------------------------------+
61| 3 |
62+--------------------------------------------------------+
63```"#,
64 argument(
65 name = "array",
66 description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
67 ),
68 argument(name = "element", description = "Element to search for in the array."),
69 argument(
70 name = "index",
71 description = "Index at which to start searching (1-indexed). Defaults to searching from the start"
72 )
73)]
74#[derive(Debug, PartialEq, Eq, Hash)]
75pub struct ArrayPosition {
76 signature: Signature,
77 aliases: Vec<String>,
78}
79
80impl Default for ArrayPosition {
81 fn default() -> Self {
82 Self::new()
83 }
84}
85impl ArrayPosition {
86 pub fn new() -> Self {
87 Self {
88 signature: Signature::array_and_element_and_optional_index(
89 Volatility::Immutable,
90 ),
91 aliases: vec![
92 String::from("list_position"),
93 String::from("array_indexof"),
94 String::from("list_indexof"),
95 ],
96 }
97 }
98}
99
100impl ScalarUDFImpl for ArrayPosition {
101 fn name(&self) -> &str {
102 "array_position"
103 }
104
105 fn signature(&self) -> &Signature {
106 &self.signature
107 }
108
109 fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
110 Ok(UInt64)
111 }
112
113 fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
114 match try_array_position_scalar(&args.args)? {
115 Some(result) => Ok(result),
116 None => make_scalar_function(array_position_inner)(&args.args),
117 }
118 }
119
120 fn aliases(&self) -> &[String] {
121 &self.aliases
122 }
123
124 fn documentation(&self) -> Option<&Documentation> {
125 self.doc()
126 }
127}
128
129fn try_array_position_scalar(args: &[ColumnarValue]) -> Result<Option<ColumnarValue>> {
131 if args.len() < 2 || args.len() > 3 {
132 return exec_err!("array_position expects two or three arguments");
133 }
134
135 let scalar_needle = match &args[1] {
137 ColumnarValue::Scalar(s) => s,
138 ColumnarValue::Array(_) => return Ok(None),
139 };
140
141 if scalar_needle.data_type().is_nested() {
144 return Ok(None);
145 }
146
147 let (num_rows, all_inputs_scalar) = match (&args[0], args.get(2)) {
150 (ColumnarValue::Array(a), _) => (a.len(), false),
151 (_, Some(ColumnarValue::Array(a))) => (a.len(), false),
152 _ => (1, true),
153 };
154
155 let needle = scalar_needle.to_array_of_size(1)?;
156 let haystack = args[0].to_array(num_rows)?;
157 let arr_from = resolve_start_from(args.get(2), num_rows)?;
158
159 let result = match haystack.data_type() {
160 List(_) => {
161 let list = as_list_array(&haystack)?;
162 array_position_scalar::<i32>(list, &needle, &arr_from)
163 }
164 LargeList(_) => {
165 let list = as_large_list_array(&haystack)?;
166 array_position_scalar::<i64>(list, &needle, &arr_from)
167 }
168 t => exec_err!("array_position does not support type '{t}'"),
169 }?;
170
171 if all_inputs_scalar {
172 Ok(Some(ColumnarValue::Scalar(ScalarValue::try_from_array(
173 &result, 0,
174 )?)))
175 } else {
176 Ok(Some(ColumnarValue::Array(result)))
177 }
178}
179
180fn array_position_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
181 if args.len() < 2 || args.len() > 3 {
182 return exec_err!("array_position expects two or three arguments");
183 }
184 match &args[0].data_type() {
185 List(_) => general_position_dispatch::<i32>(args),
186 LargeList(_) => general_position_dispatch::<i64>(args),
187 dt => exec_err!("array_position does not support type '{dt}'"),
188 }
189}
190
191fn resolve_zero_based_start_from(start_from: i64) -> Result<i64> {
192 start_from.checked_sub(1).ok_or_else(|| {
193 exec_datafusion_err!(
194 "start_from out of bounds: {start_from}, expected {} to {}",
195 i64::MIN + 1,
196 i64::MAX
197 )
198 })
199}
200
201fn resolve_start_from(
204 third_arg: Option<&ColumnarValue>,
205 num_rows: usize,
206) -> Result<Vec<i64>> {
207 match third_arg {
208 None => Ok(vec![0i64; num_rows]),
209 Some(ColumnarValue::Scalar(ScalarValue::Int64(Some(v)))) => {
210 Ok(vec![resolve_zero_based_start_from(*v)?; num_rows])
211 }
212 Some(ColumnarValue::Scalar(s)) => {
213 exec_err!("array_position expected Int64 for start_from, got {s}")
214 }
215 Some(ColumnarValue::Array(a)) => as_int64_array(a)?
216 .values()
217 .iter()
218 .map(|&x| resolve_zero_based_start_from(x))
219 .collect(),
220 }
221}
222
223fn array_position_scalar<O: OffsetSizeTrait>(
229 haystack: &GenericListArray<O>,
230 needle: &ArrayRef,
231 arr_from: &[i64], ) -> Result<ArrayRef> {
233 crate::utils::check_datatypes("array_position", &[haystack.values(), needle])?;
234
235 if haystack.len() == 0 {
236 return Ok(Arc::new(UInt64Array::new_null(0)));
237 }
238
239 let needle_datum = Scalar::new(Arc::clone(needle));
240 let validity = haystack.nulls();
241
242 let offsets = haystack.offsets();
246 let (first_offset, values_len) = offset_span(offsets);
247 let visible_values = haystack.values().slice(first_offset, values_len);
248
249 let eq_array = arrow_ord::cmp::not_distinct(&visible_values, &needle_datum)?;
252 let eq_bits = eq_array.values();
253
254 let mut result: Vec<Option<u64>> = Vec::with_capacity(haystack.len());
255 let mut matches = eq_bits.set_indices().peekable();
256
257 for (i, window) in offsets.windows(2).enumerate() {
260 let start = window[0].as_usize() - first_offset;
261 let end = window[1].as_usize() - first_offset;
262
263 if validity.is_some_and(|v| v.is_null(i)) {
264 while matches.peek().is_some_and(|&p| p < end) {
266 matches.next();
267 }
268 result.push(None);
269 continue;
270 }
271
272 let from = arr_from[i];
273 let row_len = end - start;
274 if !(from >= 0 && (from as usize) <= row_len) {
275 return exec_err!("start_from out of bounds: {}", from + 1);
276 }
277 let search_start = start + from as usize;
278
279 while matches.peek().is_some_and(|&p| p < search_start) {
281 matches.next();
282 }
283
284 if matches.peek().is_some_and(|&p| p < end) {
286 let pos = *matches.peek().unwrap();
287 result.push(Some((pos - start + 1) as u64));
288 while matches.peek().is_some_and(|&p| p < end) {
290 matches.next();
291 }
292 } else {
293 result.push(None);
294 }
295 }
296
297 debug_assert_eq!(result.len(), haystack.len());
298 Ok(Arc::new(UInt64Array::from(result)))
299}
300
301fn general_position_dispatch<O: OffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
302 let haystack = as_generic_list_array::<O>(&args[0])?;
303 let needle = &args[1];
304
305 crate::utils::check_datatypes("array_position", &[haystack.values(), needle])?;
306
307 let arr_from = if args.len() == 3 {
308 as_int64_array(&args[2])?
309 .values()
310 .iter()
311 .map(|&x| resolve_zero_based_start_from(x))
312 .collect::<Result<Vec<_>>>()?
313 } else {
314 vec![0; haystack.len()]
315 };
316
317 for (row, &from) in haystack.iter().zip(arr_from.iter()) {
318 if !row.is_none_or(|row| from >= 0 && (from as usize) <= row.len()) {
319 return exec_err!("start_from out of bounds: {}", from + 1);
320 }
321 }
322
323 generic_position::<O>(haystack, needle, &arr_from)
324}
325
326fn generic_position<O: OffsetSizeTrait>(
327 haystack: &GenericListArray<O>,
328 needle: &ArrayRef,
329 arr_from: &[i64], ) -> Result<ArrayRef> {
331 let mut data = Vec::with_capacity(haystack.len());
332
333 for (row_index, (row, &from)) in haystack.iter().zip(arr_from.iter()).enumerate() {
334 let from = from as usize;
335
336 if let Some(row) = row {
337 let eq_array = compare_element_to_list(&row, needle, row_index, true)?;
338
339 let index = eq_array
341 .iter()
342 .skip(from)
343 .position(|e| e == Some(true))
344 .map(|index| (from + index + 1) as u64);
345
346 data.push(index);
347 } else {
348 data.push(None);
349 }
350 }
351
352 Ok(Arc::new(UInt64Array::from(data)))
353}
354
355make_udf_expr_and_func!(
356 ArrayPositions,
357 array_positions,
358 array element, "searches for an element in the array, returns all occurrences.", array_positions_udf );
362
363#[user_doc(
364 doc_section(label = "Array Functions"),
365 description = "Searches for an element in the array, returns all occurrences.",
366 syntax_example = "array_positions(array, element)",
367 sql_example = r#"```sql
368> select array_positions([1, 2, 2, 3, 1, 4], 2);
369+-----------------------------------------------+
370| array_positions(List([1,2,2,3,1,4]),Int64(2)) |
371+-----------------------------------------------+
372| [2, 3] |
373+-----------------------------------------------+
374```"#,
375 argument(
376 name = "array",
377 description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
378 ),
379 argument(name = "element", description = "Element to search for in the array.")
380)]
381#[derive(Debug, PartialEq, Eq, Hash)]
382pub struct ArrayPositions {
383 signature: Signature,
384 aliases: Vec<String>,
385}
386
387impl Default for ArrayPositions {
388 fn default() -> Self {
389 Self::new()
390 }
391}
392
393impl ArrayPositions {
394 pub fn new() -> Self {
395 Self {
396 signature: Signature::array_and_element(Volatility::Immutable),
397 aliases: vec![String::from("list_positions")],
398 }
399 }
400}
401
402impl ScalarUDFImpl for ArrayPositions {
403 fn name(&self) -> &str {
404 "array_positions"
405 }
406
407 fn signature(&self) -> &Signature {
408 &self.signature
409 }
410
411 fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
412 Ok(List(Arc::new(Field::new_list_field(UInt64, true))))
413 }
414
415 fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
416 match try_array_positions_scalar(&args.args)? {
417 Some(result) => Ok(result),
418 None => make_scalar_function(array_positions_inner)(&args.args),
419 }
420 }
421
422 fn aliases(&self) -> &[String] {
423 &self.aliases
424 }
425
426 fn documentation(&self) -> Option<&Documentation> {
427 self.doc()
428 }
429}
430
431fn try_array_positions_scalar(args: &[ColumnarValue]) -> Result<Option<ColumnarValue>> {
433 let [haystack_arg, needle_arg] = take_function_args("array_positions", args)?;
434
435 let scalar_needle = match needle_arg {
436 ColumnarValue::Scalar(s) => s,
437 ColumnarValue::Array(_) => return Ok(None),
438 };
439
440 if scalar_needle.data_type().is_nested() {
443 return Ok(None);
444 }
445
446 let (num_rows, all_inputs_scalar) = match haystack_arg {
447 ColumnarValue::Array(a) => (a.len(), false),
448 ColumnarValue::Scalar(_) => (1, true),
449 };
450
451 let needle = scalar_needle.to_array_of_size(1)?;
452 let haystack = haystack_arg.to_array(num_rows)?;
453
454 let result = match haystack.data_type() {
455 List(_) => {
456 let list = as_list_array(&haystack)?;
457 array_positions_scalar::<i32>(list, &needle)
458 }
459 LargeList(_) => {
460 let list = as_large_list_array(&haystack)?;
461 array_positions_scalar::<i64>(list, &needle)
462 }
463 t => exec_err!("array_positions does not support type '{t}'"),
464 }?;
465
466 if all_inputs_scalar {
467 Ok(Some(ColumnarValue::Scalar(ScalarValue::try_from_array(
468 &result, 0,
469 )?)))
470 } else {
471 Ok(Some(ColumnarValue::Array(result)))
472 }
473}
474
475fn array_positions_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
476 let [haystack, needle] = take_function_args("array_positions", args)?;
477
478 match &haystack.data_type() {
479 List(_) => general_positions::<i32>(as_list_array(&haystack)?, needle),
480 LargeList(_) => general_positions::<i64>(as_large_list_array(&haystack)?, needle),
481 dt => exec_err!("array_positions does not support type '{dt}'"),
482 }
483}
484
485fn general_positions<O: OffsetSizeTrait>(
486 haystack: &GenericListArray<O>,
487 needle: &ArrayRef,
488) -> Result<ArrayRef> {
489 crate::utils::check_datatypes("array_positions", &[haystack.values(), needle])?;
490 let mut data = Vec::with_capacity(haystack.len());
491
492 for (row_index, row) in haystack.iter().enumerate() {
493 if let Some(row) = row {
494 let eq_array = compare_element_to_list(&row, needle, row_index, true)?;
495
496 let indexes = eq_array
498 .iter()
499 .positions(|e| e == Some(true))
500 .map(|index| Some(index as u64 + 1))
501 .collect::<Vec<_>>();
502
503 data.push(Some(indexes));
504 } else {
505 data.push(None);
506 }
507 }
508
509 Ok(Arc::new(
510 ListArray::from_iter_primitive::<UInt64Type, _, _>(data),
511 ))
512}
513
514fn array_positions_scalar<O: OffsetSizeTrait>(
520 haystack: &GenericListArray<O>,
521 needle: &ArrayRef,
522) -> Result<ArrayRef> {
523 crate::utils::check_datatypes("array_positions", &[haystack.values(), needle])?;
524
525 let num_rows = haystack.len();
526 if num_rows == 0 {
527 return Ok(Arc::new(ListArray::try_new(
528 Arc::new(Field::new_list_field(UInt64, true)),
529 OffsetBuffer::new_zeroed(1),
530 Arc::new(UInt64Array::from(Vec::<u64>::new())),
531 None,
532 )?));
533 }
534
535 let needle_datum = Scalar::new(Arc::clone(needle));
536 let validity = haystack.nulls();
537
538 let offsets = haystack.offsets();
542 let (first_offset, values_len) = offset_span(offsets);
543 let visible_values = haystack.values().slice(first_offset, values_len);
544
545 let eq_array = arrow_ord::cmp::not_distinct(&visible_values, &needle_datum)?;
548 let eq_bits = eq_array.values();
549
550 let num_matches = eq_bits.count_set_bits();
551 let mut positions: Vec<u64> = Vec::with_capacity(num_matches);
552 let mut result_offsets: Vec<i32> = Vec::with_capacity(num_rows + 1);
553 result_offsets.push(0);
554 let mut matches = eq_bits.set_indices().peekable();
555
556 for (i, window) in offsets.windows(2).enumerate() {
559 let start = window[0].as_usize() - first_offset;
560 let end = window[1].as_usize() - first_offset;
561
562 if validity.is_some_and(|v| v.is_null(i)) {
563 while matches.peek().is_some_and(|&p| p < end) {
565 matches.next();
566 }
567 result_offsets.push(positions.len() as i32);
568 continue;
569 }
570
571 while let Some(pos) = matches.next_if(|&p| p < end) {
573 positions.push((pos - start + 1) as u64);
574 }
575 result_offsets.push(positions.len() as i32);
576 }
577
578 debug_assert_eq!(result_offsets.len(), num_rows + 1);
579 Ok(Arc::new(ListArray::try_new(
580 Arc::new(Field::new_list_field(UInt64, true)),
581 OffsetBuffer::new(result_offsets.into()),
582 Arc::new(UInt64Array::from(positions)),
583 validity.cloned(),
584 )?))
585}
586
587#[cfg(test)]
588mod tests {
589 use super::*;
590 use arrow::array::AsArray;
591 use arrow::datatypes::Int32Type;
592 use datafusion_common::config::ConfigOptions;
593
594 #[test]
595 fn test_array_position_sliced_list() -> Result<()> {
596 let list = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
598 Some(vec![Some(10), Some(20)]),
599 Some(vec![Some(30), Some(40)]),
600 Some(vec![Some(50), Some(60)]),
601 Some(vec![Some(70), Some(80)]),
602 ]);
603 let sliced = list.slice(1, 2);
604 let haystack_field =
605 Arc::new(Field::new("haystack", sliced.data_type().clone(), true));
606 let needle_field = Arc::new(Field::new("needle", DataType::Int32, true));
607 let return_field = Arc::new(Field::new("return", UInt64, true));
608
609 let invoke = |needle: i32| -> Result<ArrayRef> {
612 ArrayPosition::new()
613 .invoke_with_args(ScalarFunctionArgs {
614 args: vec![
615 ColumnarValue::Array(Arc::new(sliced.clone())),
616 ColumnarValue::Scalar(ScalarValue::Int32(Some(needle))),
617 ],
618 arg_fields: vec![
619 Arc::clone(&haystack_field),
620 Arc::clone(&needle_field),
621 ],
622 number_rows: 2,
623 return_field: Arc::clone(&return_field),
624 config_options: Arc::new(ConfigOptions::default()),
625 })?
626 .into_array(2)
627 };
628
629 let output = invoke(10)?;
630 let output = output.as_primitive::<UInt64Type>();
631 assert!(output.is_null(0));
632 assert!(output.is_null(1));
633
634 let output = invoke(70)?;
635 let output = output.as_primitive::<UInt64Type>();
636 assert!(output.is_null(0));
637 assert!(output.is_null(1));
638
639 Ok(())
640 }
641
642 #[test]
643 fn test_array_positions_sliced_list() -> Result<()> {
644 let list = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
647 Some(vec![Some(10), Some(20), Some(30)]),
648 Some(vec![Some(30), Some(40), Some(30)]),
649 Some(vec![Some(50), Some(60), Some(30)]),
650 Some(vec![Some(70), Some(80), Some(30)]),
651 ]);
652 let sliced = list.slice(1, 2);
653 let haystack_field =
654 Arc::new(Field::new("haystack", sliced.data_type().clone(), true));
655 let needle_field = Arc::new(Field::new("needle", DataType::Int32, true));
656 let return_field = Arc::new(Field::new(
657 "return",
658 List(Arc::new(Field::new_list_field(UInt64, true))),
659 true,
660 ));
661
662 let invoke = |needle: i32| -> Result<ArrayRef> {
663 ArrayPositions::new()
664 .invoke_with_args(ScalarFunctionArgs {
665 args: vec![
666 ColumnarValue::Array(Arc::new(sliced.clone())),
667 ColumnarValue::Scalar(ScalarValue::Int32(Some(needle))),
668 ],
669 arg_fields: vec![
670 Arc::clone(&haystack_field),
671 Arc::clone(&needle_field),
672 ],
673 number_rows: 2,
674 return_field: Arc::clone(&return_field),
675 config_options: Arc::new(ConfigOptions::default()),
676 })?
677 .into_array(2)
678 };
679
680 let output = invoke(30)?;
683 let output = output.as_list::<i32>();
684 let row0 = output.value(0);
685 let row0 = row0.as_primitive::<UInt64Type>();
686 assert_eq!(row0.values().as_ref(), &[1, 3]);
687 let row1 = output.value(1);
688 let row1 = row1.as_primitive::<UInt64Type>();
689 assert_eq!(row1.values().as_ref(), &[3]);
690
691 let output = invoke(10)?;
693 let output = output.as_list::<i32>();
694 assert!(output.value(0).is_empty());
695 assert!(output.value(1).is_empty());
696
697 let output = invoke(70)?;
699 let output = output.as_list::<i32>();
700 assert!(output.value(0).is_empty());
701 assert!(output.value(1).is_empty());
702
703 Ok(())
704 }
705
706 #[test]
707 fn test_array_positions_sliced_list_with_nulls() -> Result<()> {
708 let list = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
710 Some(vec![Some(1), Some(2)]),
711 None,
712 Some(vec![Some(3), Some(1)]),
713 Some(vec![Some(4), Some(5)]),
714 ]);
715 let sliced = list.slice(1, 2);
716 let haystack_field =
717 Arc::new(Field::new("haystack", sliced.data_type().clone(), true));
718 let needle_field = Arc::new(Field::new("needle", DataType::Int32, true));
719 let return_field = Arc::new(Field::new(
720 "return",
721 List(Arc::new(Field::new_list_field(UInt64, true))),
722 true,
723 ));
724
725 let output = ArrayPositions::new()
726 .invoke_with_args(ScalarFunctionArgs {
727 args: vec![
728 ColumnarValue::Array(Arc::new(sliced)),
729 ColumnarValue::Scalar(ScalarValue::Int32(Some(1))),
730 ],
731 arg_fields: vec![Arc::clone(&haystack_field), Arc::clone(&needle_field)],
732 number_rows: 2,
733 return_field: Arc::clone(&return_field),
734 config_options: Arc::new(ConfigOptions::default()),
735 })?
736 .into_array(2)?;
737
738 let output = output.as_list::<i32>();
739 assert!(output.is_null(0));
741 assert!(!output.is_null(1));
743 let row1 = output.value(1);
744 let row1 = row1.as_primitive::<UInt64Type>();
745 assert_eq!(row1.values().as_ref(), &[2]);
746
747 Ok(())
748 }
749}