Skip to content

Apache DataFusion SQL Query Engine

Port Array Union and Intersect to `functions-array` (#9629)

Jay Zhan37253e57beb2
diff --git a/datafusion/expr/src/built_in_function.rs b/datafusion/expr/src/built_in_function.rs
index fe86b7a153..f838a6a94f 100644
--- a/datafusion/expr/src/built_in_function.rs
+++ b/datafusion/expr/src/built_in_function.rs
@@ -119,10 +119,6 @@ pub enum BuiltinScalarFunction {
ArrayReplaceN,
/// array_replace_all
ArrayReplaceAll,
- /// array_intersect
- ArrayIntersect,
- /// array_union
- ArrayUnion,
/// array_except
ArrayExcept,
@@ -287,8 +283,6 @@ impl BuiltinScalarFunction {
BuiltinScalarFunction::ArrayReplace => Volatility::Immutable,
BuiltinScalarFunction::ArrayReplaceN => Volatility::Immutable,
BuiltinScalarFunction::ArrayReplaceAll => Volatility::Immutable,
- BuiltinScalarFunction::ArrayIntersect => Volatility::Immutable,
- BuiltinScalarFunction::ArrayUnion => Volatility::Immutable,
BuiltinScalarFunction::Ascii => Volatility::Immutable,
BuiltinScalarFunction::BitLength => Volatility::Immutable,
BuiltinScalarFunction::Btrim => Volatility::Immutable,
@@ -356,24 +350,6 @@ impl BuiltinScalarFunction {
BuiltinScalarFunction::ArrayReplace => Ok(input_expr_types[0].clone()),
BuiltinScalarFunction::ArrayReplaceN => Ok(input_expr_types[0].clone()),
BuiltinScalarFunction::ArrayReplaceAll => Ok(input_expr_types[0].clone()),
- BuiltinScalarFunction::ArrayIntersect => {
- match (input_expr_types[0].clone(), input_expr_types[1].clone()) {
- (DataType::Null, DataType::Null) | (DataType::Null, _) => {
- Ok(DataType::Null)
- }
- (_, DataType::Null) => {
- Ok(List(Arc::new(Field::new("item", Null, true))))
- }
- (dt, _) => Ok(dt),
- }
- }
- BuiltinScalarFunction::ArrayUnion => {
- match (input_expr_types[0].clone(), input_expr_types[1].clone()) {
- (DataType::Null, dt) => Ok(dt),
- (dt, DataType::Null) => Ok(dt),
- (dt, _) => Ok(dt),
- }
- }
BuiltinScalarFunction::ArrayExcept => {
match (input_expr_types[0].clone(), input_expr_types[1].clone()) {
(DataType::Null, _) | (_, DataType::Null) => {
@@ -553,9 +529,6 @@ impl BuiltinScalarFunction {
BuiltinScalarFunction::ArrayReplaceAll => {
Signature::any(3, self.volatility())
}
- BuiltinScalarFunction::ArrayIntersect => Signature::any(2, self.volatility()),
- BuiltinScalarFunction::ArrayUnion => Signature::any(2, self.volatility()),
-
BuiltinScalarFunction::Concat
| BuiltinScalarFunction::ConcatWithSeparator => {
Signature::variadic(vec![Utf8], self.volatility())
@@ -877,10 +850,6 @@ impl BuiltinScalarFunction {
BuiltinScalarFunction::ArrayReplaceAll => {
&["array_replace_all", "list_replace_all"]
}
- BuiltinScalarFunction::ArrayUnion => &["array_union", "list_union"],
- BuiltinScalarFunction::ArrayIntersect => {
- &["array_intersect", "list_intersect"]
- }
BuiltinScalarFunction::OverLay => &["overlay"],
}
}
diff --git a/datafusion/expr/src/expr_fn.rs b/datafusion/expr/src/expr_fn.rs
index d37d021149..d852b843ba 100644
--- a/datafusion/expr/src/expr_fn.rs
+++ b/datafusion/expr/src/expr_fn.rs
@@ -638,14 +638,6 @@ scalar_expr!(
array from to,
"replaces all occurrences of the specified element with another specified element."
);
-scalar_expr!(ArrayUnion, array_union, array1 array2, "returns an array of the elements in the union of array1 and array2 without duplicates.");
-
-scalar_expr!(
- ArrayIntersect,
- array_intersect,
- first_array second_array,
- "Returns an array of the elements in the intersection of array1 and array2."
-);
// string functions
scalar_expr!(Ascii, ascii, chr, "ASCII code value of the character");
diff --git a/datafusion/functions-array/src/make_array.rs b/datafusion/functions-array/src/core.rs
similarity index 97%
rename from datafusion/functions-array/src/make_array.rs
rename to datafusion/functions-array/src/core.rs
index a371ea767b..4c84b7018c 100644
--- a/datafusion/functions-array/src/make_array.rs
+++ b/datafusion/functions-array/src/core.rs
@@ -105,7 +105,9 @@ impl ScalarUDFImpl for MakeArray {
}
}
-/// `make_array` SQL function
+/// `make_array_inner` is the implementation of the `make_array` function.
+/// Constructs an array using the input `data` as `ArrayRef`.
+/// Returns a reference-counted `Array` instance result.
pub(crate) fn make_array_inner(arrays: &[ArrayRef]) -> Result<ArrayRef> {
let mut data_type = DataType::Null;
for arg in arrays {
diff --git a/datafusion/functions-array/src/kernels.rs b/datafusion/functions-array/src/kernels.rs
index 53c8021fc1..15cdf8f279 100644
--- a/datafusion/functions-array/src/kernels.rs
+++ b/datafusion/functions-array/src/kernels.rs
@@ -27,7 +27,6 @@ use arrow::compute;
use arrow::datatypes::{
DataType, Date32Type, Field, IntervalMonthDayNanoType, UInt64Type,
};
-use arrow::row::{RowConverter, SortField};
use arrow_array::new_null_array;
use arrow_buffer::{ArrowNativeType, BooleanBufferBuilder, NullBuffer, OffsetBuffer};
use arrow_schema::FieldRef;
@@ -39,10 +38,9 @@ use datafusion_common::cast::{
as_string_array,
};
use datafusion_common::{
- exec_err, internal_datafusion_err, internal_err, not_impl_datafusion_err,
- DataFusionError, Result, ScalarValue,
+ exec_err, internal_datafusion_err, not_impl_datafusion_err, DataFusionError, Result,
+ ScalarValue,
};
-use itertools::Itertools;
use std::any::type_name;
use std::sync::Arc;
@@ -1141,68 +1139,6 @@ pub fn flatten(args: &[ArrayRef]) -> Result<ArrayRef> {
}
}
-/// array_distinct SQL function
-/// example: from list [1, 3, 2, 3, 1, 2, 4] to [1, 2, 3, 4]
-pub fn array_distinct(args: &[ArrayRef]) -> Result<ArrayRef> {
- if args.len() != 1 {
- return exec_err!("array_distinct needs one argument");
- }
-
- // handle null
- if args[0].data_type() == &DataType::Null {
- return Ok(args[0].clone());
- }
-
- // handle for list & largelist
- match args[0].data_type() {
- DataType::List(field) => {
- let array = as_list_array(&args[0])?;
- general_array_distinct(array, field)
- }
- DataType::LargeList(field) => {
- let array = as_large_list_array(&args[0])?;
- general_array_distinct(array, field)
- }
- array_type => exec_err!("array_distinct does not support type '{array_type:?}'"),
- }
-}
-
-pub fn general_array_distinct<OffsetSize: OffsetSizeTrait>(
- array: &GenericListArray<OffsetSize>,
- field: &FieldRef,
-) -> Result<ArrayRef> {
- let dt = array.value_type();
- let mut offsets = Vec::with_capacity(array.len());
- offsets.push(OffsetSize::usize_as(0));
- let mut new_arrays = Vec::with_capacity(array.len());
- let converter = RowConverter::new(vec![SortField::new(dt)])?;
- // distinct for each list in ListArray
- for arr in array.iter().flatten() {
- let values = converter.convert_columns(&[arr])?;
- // sort elements in list and remove duplicates
- let rows = values.iter().sorted().dedup().collect::<Vec<_>>();
- let last_offset: OffsetSize = offsets.last().copied().unwrap();
- offsets.push(last_offset + OffsetSize::usize_as(rows.len()));
- let arrays = converter.convert_rows(rows)?;
- let array = match arrays.first() {
- Some(array) => array.clone(),
- None => {
- return internal_err!("array_distinct: failed to get array from rows")
- }
- };
- new_arrays.push(array);
- }
- let offsets = OffsetBuffer::new(offsets.into());
- let new_arrays_ref = new_arrays.iter().map(|v| v.as_ref()).collect::<Vec<_>>();
- let values = compute::concat(&new_arrays_ref)?;
- Ok(Arc::new(GenericListArray::<OffsetSize>::try_new(
- field.clone(),
- offsets,
- values,
- None,
- )?))
-}
-
/// array_reverse SQL function
pub fn array_reverse(arg: &[ArrayRef]) -> Result<ArrayRef> {
if arg.len() != 1 {
diff --git a/datafusion/functions-array/src/lib.rs b/datafusion/functions-array/src/lib.rs
index 1e0265e53c..d9d2b73592 100644
--- a/datafusion/functions-array/src/lib.rs
+++ b/datafusion/functions-array/src/lib.rs
@@ -30,10 +30,11 @@ pub mod macros;
mod array_has;
mod concat;
+mod core;
mod extract;
mod kernels;
-mod make_array;
mod rewrite;
+mod set_ops;
mod udf;
mod utils;
@@ -51,13 +52,15 @@ pub mod expr_fn {
pub use super::concat::array_append;
pub use super::concat::array_concat;
pub use super::concat::array_prepend;
+ pub use super::core::make_array;
pub use super::extract::array_element;
pub use super::extract::array_pop_back;
pub use super::extract::array_pop_front;
pub use super::extract::array_slice;
- pub use super::make_array::make_array;
+ pub use super::set_ops::array_distinct;
+ pub use super::set_ops::array_intersect;
+ pub use super::set_ops::array_union;
pub use super::udf::array_dims;
- pub use super::udf::array_distinct;
pub use super::udf::array_empty;
pub use super::udf::array_length;
pub use super::udf::array_ndims;
@@ -90,7 +93,7 @@ pub fn register_all(registry: &mut dyn FunctionRegistry) -> Result<()> {
extract::array_pop_back_udf(),
extract::array_pop_front_udf(),
extract::array_slice_udf(),
- make_array::make_array_udf(),
+ core::make_array_udf(),
array_has::array_has_udf(),
array_has::array_has_all_udf(),
array_has::array_has_any_udf(),
@@ -98,10 +101,12 @@ pub fn register_all(registry: &mut dyn FunctionRegistry) -> Result<()> {
udf::array_length_udf(),
udf::flatten_udf(),
udf::array_sort_udf(),
- udf::array_distinct_udf(),
udf::array_repeat_udf(),
udf::array_resize_udf(),
udf::array_reverse_udf(),
+ set_ops::array_distinct_udf(),
+ set_ops::array_intersect_udf(),
+ set_ops::array_union_udf(),
];
functions.into_iter().try_for_each(|udf| {
let existing_udf = registry.register_udf(udf)?;
diff --git a/datafusion/functions-array/src/set_ops.rs b/datafusion/functions-array/src/set_ops.rs
new file mode 100644
index 0000000000..df5bc91a26
--- /dev/null
+++ b/datafusion/functions-array/src/set_ops.rs
@@ -0,0 +1,440 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Array Intersection, Union, and Distinct functions
+
+use crate::core::make_array_inner;
+use crate::utils::make_scalar_function;
+use arrow::array::{new_empty_array, Array, ArrayRef, GenericListArray, OffsetSizeTrait};
+use arrow::buffer::OffsetBuffer;
+use arrow::compute;
+use arrow::datatypes::{DataType, Field, FieldRef};
+use arrow::row::{RowConverter, SortField};
+use datafusion_common::cast::{as_large_list_array, as_list_array};
+use datafusion_common::{exec_err, internal_err, Result};
+use datafusion_expr::expr::ScalarFunction;
+use datafusion_expr::Expr;
+use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+use itertools::Itertools;
+use std::any::Any;
+use std::collections::HashSet;
+use std::fmt::{Display, Formatter};
+use std::sync::Arc;
+
+// Create static instances of ScalarUDFs for each function
+make_udf_function!(
+ ArrayUnion,
+ array_union,
+ array1 array2,
+ "returns an array of the elements in the union of array1 and array2 without duplicates.",
+ array_union_udf
+);
+
+make_udf_function!(
+ ArrayIntersect,
+ array_intersect,
+ first_array second_array,
+ "Returns an array of the elements in the intersection of array1 and array2.",
+ array_intersect_udf
+);
+
+make_udf_function!(
+ ArrayDistinct,
+ array_distinct,
+ array,
+ "return distinct values from the array after removing duplicates.",
+ array_distinct_udf
+);
+
+#[derive(Debug)]
+pub(super) struct ArrayUnion {
+ signature: Signature,
+ aliases: Vec<String>,
+}
+
+impl ArrayUnion {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::any(2, Volatility::Immutable),
+ aliases: vec![String::from("array_union"), String::from("list_union")],
+ }
+ }
+}
+
+impl ScalarUDFImpl for ArrayUnion {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+ fn name(&self) -> &str {
+ "array_union"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+ match (&arg_types[0], &arg_types[1]) {
+ (&DataType::Null, dt) => Ok(dt.clone()),
+ (dt, DataType::Null) => Ok(dt.clone()),
+ (dt, _) => Ok(dt.clone()),
+ }
+ }
+
+ fn invoke(&self, args: &[ColumnarValue]) -> Result<ColumnarValue> {
+ make_scalar_function(array_union_inner)(args)
+ }
+
+ fn aliases(&self) -> &[String] {
+ &self.aliases
+ }
+}
+
+#[derive(Debug)]
+pub(super) struct ArrayIntersect {
+ signature: Signature,
+ aliases: Vec<String>,
+}
+
+impl ArrayIntersect {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::any(2, Volatility::Immutable),
+ aliases: vec![
+ String::from("array_intersect"),
+ String::from("list_intersect"),
+ ],
+ }
+ }
+}
+
+impl ScalarUDFImpl for ArrayIntersect {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+ fn name(&self) -> &str {
+ "array_intersect"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+ match (arg_types[0].clone(), arg_types[1].clone()) {
+ (DataType::Null, DataType::Null) | (DataType::Null, _) => Ok(DataType::Null),
+ (_, DataType::Null) => Ok(DataType::List(Arc::new(Field::new(
+ "item",
+ DataType::Null,
+ true,
+ )))),
+ (dt, _) => Ok(dt),
+ }
+ }
+
+ fn invoke(&self, args: &[ColumnarValue]) -> Result<ColumnarValue> {
+ make_scalar_function(array_intersect_inner)(args)
+ }
+
+ fn aliases(&self) -> &[String] {
+ &self.aliases
+ }
+}
+
+#[derive(Debug)]
+pub(super) struct ArrayDistinct {
+ signature: Signature,
+ aliases: Vec<String>,
+}
+
+impl ArrayDistinct {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::array(Volatility::Immutable),
+ aliases: vec!["array_distinct".to_string(), "list_distinct".to_string()],
+ }
+ }
+}
+
+impl ScalarUDFImpl for ArrayDistinct {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+ fn name(&self) -> &str {
+ "array_distinct"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+ use DataType::*;
+ match &arg_types[0] {
+ List(field) | FixedSizeList(field, _) => Ok(List(Arc::new(Field::new(
+ "item",
+ field.data_type().clone(),
+ true,
+ )))),
+ LargeList(field) => Ok(LargeList(Arc::new(Field::new(
+ "item",
+ field.data_type().clone(),
+ true,
+ )))),
+ _ => exec_err!(
+ "Not reachable, data_type should be List, LargeList or FixedSizeList"
+ ),
+ }
+ }
+
+ fn invoke(&self, args: &[ColumnarValue]) -> Result<ColumnarValue> {
+ make_scalar_function(array_distinct_inner)(args)
+ }
+
+ fn aliases(&self) -> &[String] {
+ &self.aliases
+ }
+}
+
+/// array_distinct SQL function
+/// example: from list [1, 3, 2, 3, 1, 2, 4] to [1, 2, 3, 4]
+fn array_distinct_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
+ if args.len() != 1 {
+ return exec_err!("array_distinct needs one argument");
+ }
+
+ // handle null
+ if args[0].data_type() == &DataType::Null {
+ return Ok(args[0].clone());
+ }
+
+ // handle for list & largelist
+ match args[0].data_type() {
+ DataType::List(field) => {
+ let array = as_list_array(&args[0])?;
+ general_array_distinct(array, field)
+ }
+ DataType::LargeList(field) => {
+ let array = as_large_list_array(&args[0])?;
+ general_array_distinct(array, field)
+ }
+ array_type => exec_err!("array_distinct does not support type '{array_type:?}'"),
+ }
+}
+
+#[derive(Debug, PartialEq)]
+enum SetOp {
+ Union,
+ Intersect,
+}
+
+impl Display for SetOp {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ match self {
+ SetOp::Union => write!(f, "array_union"),
+ SetOp::Intersect => write!(f, "array_intersect"),
+ }
+ }
+}
+
+fn generic_set_lists<OffsetSize: OffsetSizeTrait>(
+ l: &GenericListArray<OffsetSize>,
+ r: &GenericListArray<OffsetSize>,
+ field: Arc<Field>,
+ set_op: SetOp,
+) -> Result<ArrayRef> {
+ if matches!(l.value_type(), DataType::Null) {
+ let field = Arc::new(Field::new("item", r.value_type(), true));
+ return general_array_distinct::<OffsetSize>(r, &field);
+ } else if matches!(r.value_type(), DataType::Null) {
+ let field = Arc::new(Field::new("item", l.value_type(), true));
+ return general_array_distinct::<OffsetSize>(l, &field);
+ }
+
+ if l.value_type() != r.value_type() {
+ return internal_err!("{set_op:?} is not implemented for '{l:?}' and '{r:?}'");
+ }
+
+ let dt = l.value_type();
+
+ let mut offsets = vec![OffsetSize::usize_as(0)];
+ let mut new_arrays = vec![];
+
+ let converter = RowConverter::new(vec![SortField::new(dt)])?;
+ for (first_arr, second_arr) in l.iter().zip(r.iter()) {
+ if let (Some(first_arr), Some(second_arr)) = (first_arr, second_arr) {
+ let l_values = converter.convert_columns(&[first_arr])?;
+ let r_values = converter.convert_columns(&[second_arr])?;
+
+ let l_iter = l_values.iter().sorted().dedup();
+ let values_set: HashSet<_> = l_iter.clone().collect();
+ let mut rows = if set_op == SetOp::Union {
+ l_iter.collect::<Vec<_>>()
+ } else {
+ vec![]
+ };
+ for r_val in r_values.iter().sorted().dedup() {
+ match set_op {
+ SetOp::Union => {
+ if !values_set.contains(&r_val) {
+ rows.push(r_val);
+ }
+ }
+ SetOp::Intersect => {
+ if values_set.contains(&r_val) {
+ rows.push(r_val);
+ }
+ }
+ }
+ }
+
+ let last_offset = match offsets.last().copied() {
+ Some(offset) => offset,
+ None => return internal_err!("offsets should not be empty"),
+ };
+ offsets.push(last_offset + OffsetSize::usize_as(rows.len()));
+ let arrays = converter.convert_rows(rows)?;
+ let array = match arrays.first() {
+ Some(array) => array.clone(),
+ None => {
+ return internal_err!("{set_op}: failed to get array from rows");
+ }
+ };
+ new_arrays.push(array);
+ }
+ }
+
+ let offsets = OffsetBuffer::new(offsets.into());
+ let new_arrays_ref = new_arrays.iter().map(|v| v.as_ref()).collect::<Vec<_>>();
+ let values = compute::concat(&new_arrays_ref)?;
+ let arr = GenericListArray::<OffsetSize>::try_new(field, offsets, values, None)?;
+ Ok(Arc::new(arr))
+}
+
+fn general_set_op(
+ array1: &ArrayRef,
+ array2: &ArrayRef,
+ set_op: SetOp,
+) -> Result<ArrayRef> {
+ match (array1.data_type(), array2.data_type()) {
+ (DataType::Null, DataType::List(field)) => {
+ if set_op == SetOp::Intersect {
+ return Ok(new_empty_array(&DataType::Null));
+ }
+ let array = as_list_array(&array2)?;
+ general_array_distinct::<i32>(array, field)
+ }
+
+ (DataType::List(field), DataType::Null) => {
+ if set_op == SetOp::Intersect {
+ return make_array_inner(&[]);
+ }
+ let array = as_list_array(&array1)?;
+ general_array_distinct::<i32>(array, field)
+ }
+ (DataType::Null, DataType::LargeList(field)) => {
+ if set_op == SetOp::Intersect {
+ return Ok(new_empty_array(&DataType::Null));
+ }
+ let array = as_large_list_array(&array2)?;
+ general_array_distinct::<i64>(array, field)
+ }
+ (DataType::LargeList(field), DataType::Null) => {
+ if set_op == SetOp::Intersect {
+ return make_array_inner(&[]);
+ }
+ let array = as_large_list_array(&array1)?;
+ general_array_distinct::<i64>(array, field)
+ }
+ (DataType::Null, DataType::Null) => Ok(new_empty_array(&DataType::Null)),
+
+ (DataType::List(field), DataType::List(_)) => {
+ let array1 = as_list_array(&array1)?;
+ let array2 = as_list_array(&array2)?;
+ generic_set_lists::<i32>(array1, array2, field.clone(), set_op)
+ }
+ (DataType::LargeList(field), DataType::LargeList(_)) => {
+ let array1 = as_large_list_array(&array1)?;
+ let array2 = as_large_list_array(&array2)?;
+ generic_set_lists::<i64>(array1, array2, field.clone(), set_op)
+ }
+ (data_type1, data_type2) => {
+ internal_err!(
+ "{set_op} does not support types '{data_type1:?}' and '{data_type2:?}'"
+ )
+ }
+ }
+}
+
+/// Array_union SQL function
+fn array_union_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
+ if args.len() != 2 {
+ return exec_err!("array_union needs two arguments");
+ }
+ let array1 = &args[0];
+ let array2 = &args[1];
+
+ general_set_op(array1, array2, SetOp::Union)
+}
+
+/// array_intersect SQL function
+fn array_intersect_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
+ if args.len() != 2 {
+ return exec_err!("array_intersect needs two arguments");
+ }
+
+ let array1 = &args[0];
+ let array2 = &args[1];
+
+ general_set_op(array1, array2, SetOp::Intersect)
+}
+
+fn general_array_distinct<OffsetSize: OffsetSizeTrait>(
+ array: &GenericListArray<OffsetSize>,
+ field: &FieldRef,
+) -> Result<ArrayRef> {
+ let dt = array.value_type();
+ let mut offsets = Vec::with_capacity(array.len());
+ offsets.push(OffsetSize::usize_as(0));
+ let mut new_arrays = Vec::with_capacity(array.len());
+ let converter = RowConverter::new(vec![SortField::new(dt)])?;
+ // distinct for each list in ListArray
+ for arr in array.iter().flatten() {
+ let values = converter.convert_columns(&[arr])?;
+ // sort elements in list and remove duplicates
+ let rows = values.iter().sorted().dedup().collect::<Vec<_>>();
+ let last_offset: OffsetSize = offsets.last().copied().unwrap();
+ offsets.push(last_offset + OffsetSize::usize_as(rows.len()));
+ let arrays = converter.convert_rows(rows)?;
+ let array = match arrays.first() {
+ Some(array) => array.clone(),
+ None => {
+ return internal_err!("array_distinct: failed to get array from rows")
+ }
+ };
+ new_arrays.push(array);
+ }
+ let offsets = OffsetBuffer::new(offsets.into());
+ let new_arrays_ref = new_arrays.iter().map(|v| v.as_ref()).collect::<Vec<_>>();
+ let values = compute::concat(&new_arrays_ref)?;
+ Ok(Arc::new(GenericListArray::<OffsetSize>::try_new(
+ field.clone(),
+ offsets,
+ values,
+ None,
+ )?))
+}
diff --git a/datafusion/functions-array/src/udf.rs b/datafusion/functions-array/src/udf.rs
index 64305cf1e5..e0793900c6 100644
--- a/datafusion/functions-array/src/udf.rs
+++ b/datafusion/functions-array/src/udf.rs
@@ -819,70 +819,6 @@ impl ScalarUDFImpl for Flatten {
}
}
-make_udf_function!(
- ArrayDistinct,
- array_distinct,
- array,
- "return distinct values from the array after removing duplicates.",
- array_distinct_udf
-);
-
-#[derive(Debug)]
-pub(super) struct ArrayDistinct {
- signature: Signature,
- aliases: Vec<String>,
-}
-
-impl crate::udf::ArrayDistinct {
- pub fn new() -> Self {
- Self {
- signature: Signature::array(Volatility::Immutable),
- aliases: vec!["array_distinct".to_string(), "list_distinct".to_string()],
- }
- }
-}
-
-impl ScalarUDFImpl for crate::udf::ArrayDistinct {
- fn as_any(&self) -> &dyn Any {
- self
- }
- fn name(&self) -> &str {
- "array_distinct"
- }
-
- fn signature(&self) -> &Signature {
- &self.signature
- }
-
- fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
- use DataType::*;
- match &arg_types[0] {
- List(field) | FixedSizeList(field, _) => Ok(List(Arc::new(Field::new(
- "item",
- field.data_type().clone(),
- true,
- )))),
- LargeList(field) => Ok(LargeList(Arc::new(Field::new(
- "item",
- field.data_type().clone(),
- true,
- )))),
- _ => exec_err!(
- "Not reachable, data_type should be List, LargeList or FixedSizeList"
- ),
- }
- }
-
- fn invoke(&self, args: &[ColumnarValue]) -> Result<ColumnarValue> {
- let args = ColumnarValue::values_to_arrays(args)?;
- crate::kernels::array_distinct(&args).map(ColumnarValue::Array)
- }
-
- fn aliases(&self) -> &[String] {
- &self.aliases
- }
-}
-
make_udf_function!(
ArrayReverse,
array_reverse,
diff --git a/datafusion/functions-array/src/utils.rs b/datafusion/functions-array/src/utils.rs
index 3a6bb723c1..f7c0924893 100644
--- a/datafusion/functions-array/src/utils.rs
+++ b/datafusion/functions-array/src/utils.rs
@@ -39,6 +39,7 @@ pub(crate) fn check_datatypes(name: &str, args: &[&ArrayRef]) -> Result<()> {
Ok(())
}
+/// array function wrapper that differentiates between scalar (length 1) and array.
pub(crate) fn make_scalar_function<F>(inner: F) -> ScalarFunctionImplementation
where
F: Fn(&[ArrayRef]) -> Result<ArrayRef> + Sync + Send + 'static,
diff --git a/datafusion/physical-expr/src/array_expressions.rs b/datafusion/physical-expr/src/array_expressions.rs
index ca19d3052c..0352cf2b0f 100644
--- a/datafusion/physical-expr/src/array_expressions.rs
+++ b/datafusion/physical-expr/src/array_expressions.rs
@@ -18,12 +18,10 @@
//! Array expressions
use std::collections::HashSet;
-use std::fmt::{Display, Formatter};
use std::sync::Arc;
use arrow::array::*;
use arrow::buffer::OffsetBuffer;
-use arrow::compute::{self};
use arrow::datatypes::{DataType, Field, UInt64Type};
use arrow::row::{RowConverter, SortField};
use arrow_buffer::NullBuffer;
@@ -788,205 +786,71 @@ pub fn array_replace_all(args: &[ArrayRef]) -> Result<ArrayRef> {
}
}
-#[derive(Debug, PartialEq)]
-enum SetOp {
- Union,
- Intersect,
-}
-
-impl Display for SetOp {
- fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
- match self {
- SetOp::Union => write!(f, "array_union"),
- SetOp::Intersect => write!(f, "array_intersect"),
- }
- }
-}
-
-fn generic_set_lists<OffsetSize: OffsetSizeTrait>(
- l: &GenericListArray<OffsetSize>,
- r: &GenericListArray<OffsetSize>,
- field: Arc<Field>,
- set_op: SetOp,
-) -> Result<ArrayRef> {
- if matches!(l.value_type(), DataType::Null) {
- let field = Arc::new(Field::new("item", r.value_type(), true));
- return general_array_distinct::<OffsetSize>(r, &field);
- } else if matches!(r.value_type(), DataType::Null) {
- let field = Arc::new(Field::new("item", l.value_type(), true));
- return general_array_distinct::<OffsetSize>(l, &field);
+/// array_reverse SQL function
+pub fn array_reverse(arg: &[ArrayRef]) -> Result<ArrayRef> {
+ if arg.len() != 1 {
+ return exec_err!("array_reverse needs one argument");
}
- if l.value_type() != r.value_type() {
- return internal_err!("{set_op:?} is not implemented for '{l:?}' and '{r:?}'");
- }
-
- let dt = l.value_type();
-
- let mut offsets = vec![OffsetSize::usize_as(0)];
- let mut new_arrays = vec![];
-
- let converter = RowConverter::new(vec![SortField::new(dt)])?;
- for (first_arr, second_arr) in l.iter().zip(r.iter()) {
- if let (Some(first_arr), Some(second_arr)) = (first_arr, second_arr) {
- let l_values = converter.convert_columns(&[first_arr])?;
- let r_values = converter.convert_columns(&[second_arr])?;
-
- let l_iter = l_values.iter().sorted().dedup();
- let values_set: HashSet<_> = l_iter.clone().collect();
- let mut rows = if set_op == SetOp::Union {
- l_iter.collect::<Vec<_>>()
- } else {
- vec![]
- };
- for r_val in r_values.iter().sorted().dedup() {
- match set_op {
- SetOp::Union => {
- if !values_set.contains(&r_val) {
- rows.push(r_val);
- }
- }
- SetOp::Intersect => {
- if values_set.contains(&r_val) {
- rows.push(r_val);
- }
- }
- }
- }
-
- let last_offset = match offsets.last().copied() {
- Some(offset) => offset,
- None => return internal_err!("offsets should not be empty"),
- };
- offsets.push(last_offset + OffsetSize::usize_as(rows.len()));
- let arrays = converter.convert_rows(rows)?;
- let array = match arrays.first() {
- Some(array) => array.clone(),
- None => {
- return internal_err!("{set_op}: failed to get array from rows");
- }
- };
- new_arrays.push(array);
+ match &arg[0].data_type() {
+ DataType::List(field) => {
+ let array = as_list_array(&arg[0])?;
+ general_array_reverse::<i32>(array, field)
+ }
+ DataType::LargeList(field) => {
+ let array = as_large_list_array(&arg[0])?;
+ general_array_reverse::<i64>(array, field)
}
+ DataType::Null => Ok(arg[0].clone()),
+ array_type => exec_err!("array_reverse does not support type '{array_type:?}'."),
}
-
- let offsets = OffsetBuffer::new(offsets.into());
- let new_arrays_ref = new_arrays.iter().map(|v| v.as_ref()).collect::<Vec<_>>();
- let values = compute::concat(&new_arrays_ref)?;
- let arr = GenericListArray::<OffsetSize>::try_new(field, offsets, values, None)?;
- Ok(Arc::new(arr))
}
-fn general_set_op(
- array1: &ArrayRef,
- array2: &ArrayRef,
- set_op: SetOp,
-) -> Result<ArrayRef> {
- match (array1.data_type(), array2.data_type()) {
- (DataType::Null, DataType::List(field)) => {
- if set_op == SetOp::Intersect {
- return Ok(new_empty_array(&DataType::Null));
- }
- let array = as_list_array(&array2)?;
- general_array_distinct::<i32>(array, field)
- }
-
- (DataType::List(field), DataType::Null) => {
- if set_op == SetOp::Intersect {
- return make_array(&[]);
- }
- let array = as_list_array(&array1)?;
- general_array_distinct::<i32>(array, field)
- }
- (DataType::Null, DataType::LargeList(field)) => {
- if set_op == SetOp::Intersect {
- return Ok(new_empty_array(&DataType::Null));
- }
- let array = as_large_list_array(&array2)?;
- general_array_distinct::<i64>(array, field)
- }
- (DataType::LargeList(field), DataType::Null) => {
- if set_op == SetOp::Intersect {
- return make_array(&[]);
- }
- let array = as_large_list_array(&array1)?;
- general_array_distinct::<i64>(array, field)
- }
- (DataType::Null, DataType::Null) => Ok(new_empty_array(&DataType::Null)),
-
- (DataType::List(field), DataType::List(_)) => {
- let array1 = as_list_array(&array1)?;
- let array2 = as_list_array(&array2)?;
- generic_set_lists::<i32>(array1, array2, field.clone(), set_op)
- }
- (DataType::LargeList(field), DataType::LargeList(_)) => {
- let array1 = as_large_list_array(&array1)?;
- let array2 = as_large_list_array(&array2)?;
- generic_set_lists::<i64>(array1, array2, field.clone(), set_op)
- }
- (data_type1, data_type2) => {
- internal_err!(
- "{set_op} does not support types '{data_type1:?}' and '{data_type2:?}'"
- )
+fn general_array_reverse<O: OffsetSizeTrait>(
+ array: &GenericListArray<O>,
+ field: &FieldRef,
+) -> Result<ArrayRef>
+where
+ O: TryFrom<i64>,
+{
+ let values = array.values();
+ let original_data = values.to_data();
+ let capacity = Capacities::Array(original_data.len());
+ let mut offsets = vec![O::usize_as(0)];
+ let mut nulls = vec![];
+ let mut mutable =
+ MutableArrayData::with_capacities(vec![&original_data], false, capacity);
+
+ for (row_index, offset_window) in array.offsets().windows(2).enumerate() {
+ // skip the null value
+ if array.is_null(row_index) {
+ nulls.push(false);
+ offsets.push(offsets[row_index] + O::one());
+ mutable.extend(0, 0, 1);
+ continue;
+ } else {
+ nulls.push(true);
}
- }
-}
-/// Array_union SQL function
-pub fn array_union(args: &[ArrayRef]) -> Result<ArrayRef> {
- if args.len() != 2 {
- return exec_err!("array_union needs two arguments");
- }
- let array1 = &args[0];
- let array2 = &args[1];
+ let start = offset_window[0];
+ let end = offset_window[1];
- general_set_op(array1, array2, SetOp::Union)
-}
+ let mut index = end - O::one();
+ let mut cnt = 0;
-/// array_intersect SQL function
-pub fn array_intersect(args: &[ArrayRef]) -> Result<ArrayRef> {
- if args.len() != 2 {
- return exec_err!("array_intersect needs two arguments");
+ while index >= start {
+ mutable.extend(0, index.to_usize().unwrap(), index.to_usize().unwrap() + 1);
+ index = index - O::one();
+ cnt += 1;
+ }
+ offsets.push(offsets[row_index] + O::usize_as(cnt));
}
- let array1 = &args[0];
- let array2 = &args[1];
-
- general_set_op(array1, array2, SetOp::Intersect)
-}
-
-pub fn general_array_distinct<OffsetSize: OffsetSizeTrait>(
- array: &GenericListArray<OffsetSize>,
- field: &FieldRef,
-) -> Result<ArrayRef> {
- let dt = array.value_type();
- let mut offsets = Vec::with_capacity(array.len());
- offsets.push(OffsetSize::usize_as(0));
- let mut new_arrays = Vec::with_capacity(array.len());
- let converter = RowConverter::new(vec![SortField::new(dt)])?;
- // distinct for each list in ListArray
- for arr in array.iter().flatten() {
- let values = converter.convert_columns(&[arr])?;
- // sort elements in list and remove duplicates
- let rows = values.iter().sorted().dedup().collect::<Vec<_>>();
- let last_offset: OffsetSize = offsets.last().copied().unwrap();
- offsets.push(last_offset + OffsetSize::usize_as(rows.len()));
- let arrays = converter.convert_rows(rows)?;
- let array = match arrays.first() {
- Some(array) => array.clone(),
- None => {
- return internal_err!("array_distinct: failed to get array from rows")
- }
- };
- new_arrays.push(array);
- }
- let offsets = OffsetBuffer::new(offsets.into());
- let new_arrays_ref = new_arrays.iter().map(|v| v.as_ref()).collect::<Vec<_>>();
- let values = compute::concat(&new_arrays_ref)?;
- Ok(Arc::new(GenericListArray::<OffsetSize>::try_new(
+ let data = mutable.freeze();
+ Ok(Arc::new(GenericListArray::<O>::try_new(
field.clone(),
- offsets,
- values,
- None,
+ OffsetBuffer::<O>::new(offsets.into()),
+ arrow_array::make_array(data),
+ Some(nulls.into()),
)?))
}
diff --git a/datafusion/physical-expr/src/functions.rs b/datafusion/physical-expr/src/functions.rs
index f0eab1c857..406f50c9b4 100644
--- a/datafusion/physical-expr/src/functions.rs
+++ b/datafusion/physical-expr/src/functions.rs
@@ -282,12 +282,6 @@ pub fn create_physical_fun(
BuiltinScalarFunction::ArrayReplaceAll => Arc::new(|args| {
make_scalar_function_inner(array_expressions::array_replace_all)(args)
}),
- BuiltinScalarFunction::ArrayIntersect => Arc::new(|args| {
- make_scalar_function_inner(array_expressions::array_intersect)(args)
- }),
- BuiltinScalarFunction::ArrayUnion => Arc::new(|args| {
- make_scalar_function_inner(array_expressions::array_union)(args)
- }),
// string functions
BuiltinScalarFunction::Ascii => Arc::new(|args| match args[0].data_type() {
diff --git a/datafusion/proto/proto/datafusion.proto b/datafusion/proto/proto/datafusion.proto
index 3754e60c3c..54c3651874 100644
--- a/datafusion/proto/proto/datafusion.proto
+++ b/datafusion/proto/proto/datafusion.proto
@@ -658,8 +658,8 @@ enum ScalarFunction {
// 116 was ArrayPopBack
// 117 was StringToArray
// 118 was ToTimestampNanos
- ArrayIntersect = 119;
- ArrayUnion = 120;
+ // 119 was ArrayIntersect
+ // 120 was ArrayUnion
OverLay = 121;
// 122 is Range
ArrayExcept = 123;
diff --git a/datafusion/proto/src/generated/pbjson.rs b/datafusion/proto/src/generated/pbjson.rs
index ba619cb81d..1280eb1e18 100644
--- a/datafusion/proto/src/generated/pbjson.rs
+++ b/datafusion/proto/src/generated/pbjson.rs
@@ -22962,8 +22962,6 @@ impl serde::Serialize for ScalarFunction {
Self::ArrayReplaceAll => "ArrayReplaceAll",
Self::Nanvl => "Nanvl",
Self::Iszero => "Iszero",
- Self::ArrayIntersect => "ArrayIntersect",
- Self::ArrayUnion => "ArrayUnion",
Self::OverLay => "OverLay",
Self::ArrayExcept => "ArrayExcept",
Self::Levenshtein => "Levenshtein",
@@ -23051,8 +23049,6 @@ impl<'de> serde::Deserialize<'de> for ScalarFunction {
"ArrayReplaceAll",
"Nanvl",
"Iszero",
- "ArrayIntersect",
- "ArrayUnion",
"OverLay",
"ArrayExcept",
"Levenshtein",
@@ -23169,8 +23165,6 @@ impl<'de> serde::Deserialize<'de> for ScalarFunction {
"ArrayReplaceAll" => Ok(ScalarFunction::ArrayReplaceAll),
"Nanvl" => Ok(ScalarFunction::Nanvl),
"Iszero" => Ok(ScalarFunction::Iszero),
- "ArrayIntersect" => Ok(ScalarFunction::ArrayIntersect),
- "ArrayUnion" => Ok(ScalarFunction::ArrayUnion),
"OverLay" => Ok(ScalarFunction::OverLay),
"ArrayExcept" => Ok(ScalarFunction::ArrayExcept),
"Levenshtein" => Ok(ScalarFunction::Levenshtein),
diff --git a/datafusion/proto/src/generated/prost.rs b/datafusion/proto/src/generated/prost.rs
index c091ffa35f..0ea20e39a6 100644
--- a/datafusion/proto/src/generated/prost.rs
+++ b/datafusion/proto/src/generated/prost.rs
@@ -2931,8 +2931,8 @@ pub enum ScalarFunction {
/// 116 was ArrayPopBack
/// 117 was StringToArray
/// 118 was ToTimestampNanos
- ArrayIntersect = 119,
- ArrayUnion = 120,
+ /// 119 was ArrayIntersect
+ /// 120 was ArrayUnion
OverLay = 121,
/// 122 is Range
ArrayExcept = 123,
@@ -3030,8 +3030,6 @@ impl ScalarFunction {
ScalarFunction::ArrayReplaceAll => "ArrayReplaceAll",
ScalarFunction::Nanvl => "Nanvl",
ScalarFunction::Iszero => "Iszero",
- ScalarFunction::ArrayIntersect => "ArrayIntersect",
- ScalarFunction::ArrayUnion => "ArrayUnion",
ScalarFunction::OverLay => "OverLay",
ScalarFunction::ArrayExcept => "ArrayExcept",
ScalarFunction::Levenshtein => "Levenshtein",
@@ -3113,8 +3111,6 @@ impl ScalarFunction {
"ArrayReplaceAll" => Some(Self::ArrayReplaceAll),
"Nanvl" => Some(Self::Nanvl),
"Iszero" => Some(Self::Iszero),
- "ArrayIntersect" => Some(Self::ArrayIntersect),
- "ArrayUnion" => Some(Self::ArrayUnion),
"OverLay" => Some(Self::OverLay),
"ArrayExcept" => Some(Self::ArrayExcept),
"Levenshtein" => Some(Self::Levenshtein),
diff --git a/datafusion/proto/src/logical_plan/from_proto.rs b/datafusion/proto/src/logical_plan/from_proto.rs
index 8699daadd4..0dcd2dd27a 100644
--- a/datafusion/proto/src/logical_plan/from_proto.rs
+++ b/datafusion/proto/src/logical_plan/from_proto.rs
@@ -48,11 +48,10 @@ use datafusion_expr::expr::Unnest;
use datafusion_expr::expr::{Alias, Placeholder};
use datafusion_expr::window_frame::{check_window_frame, regularize_window_order_by};
use datafusion_expr::{
- acosh, array_except, array_intersect, array_position, array_positions, array_remove,
- array_remove_all, array_remove_n, array_replace, array_replace_all, array_replace_n,
- array_union, ascii, asinh, atan, atan2, atanh, bit_length, btrim, cbrt, ceil,
- character_length, chr, coalesce, concat_expr, concat_ws_expr, cos, cosh, cot,
- degrees, ends_with, exp,
+ acosh, array_except, array_position, array_positions, array_remove, array_remove_all,
+ array_remove_n, array_replace, array_replace_all, array_replace_n, ascii, asinh,
+ atan, atan2, atanh, bit_length, btrim, cbrt, ceil, character_length, chr, coalesce,
+ concat_expr, concat_ws_expr, cos, cosh, cot, degrees, ends_with, exp,
expr::{self, InList, Sort, WindowFunction},
factorial, find_in_set, floor, gcd, initcap, iszero, lcm, left, levenshtein, ln, log,
log10, log2,
@@ -477,8 +476,6 @@ impl From<&protobuf::ScalarFunction> for BuiltinScalarFunction {
ScalarFunction::ArrayReplace => Self::ArrayReplace,
ScalarFunction::ArrayReplaceN => Self::ArrayReplaceN,
ScalarFunction::ArrayReplaceAll => Self::ArrayReplaceAll,
- ScalarFunction::ArrayIntersect => Self::ArrayIntersect,
- ScalarFunction::ArrayUnion => Self::ArrayUnion,
ScalarFunction::Log2 => Self::Log2,
ScalarFunction::Signum => Self::Signum,
ScalarFunction::Ascii => Self::Ascii,
@@ -1376,10 +1373,6 @@ pub fn parse_expr(
parse_expr(&args[0], registry, codec)?,
parse_expr(&args[1], registry, codec)?,
)),
- ScalarFunction::ArrayIntersect => Ok(array_intersect(
- parse_expr(&args[0], registry, codec)?,
- parse_expr(&args[1], registry, codec)?,
- )),
ScalarFunction::ArrayPosition => Ok(array_position(
parse_expr(&args[0], registry, codec)?,
parse_expr(&args[1], registry, codec)?,
@@ -1418,10 +1411,6 @@ pub fn parse_expr(
parse_expr(&args[1], registry, codec)?,
parse_expr(&args[2], registry, codec)?,
)),
- ScalarFunction::ArrayUnion => Ok(array_union(
- parse_expr(&args[0], registry, codec)?,
- parse_expr(&args[1], registry, codec)?,
- )),
ScalarFunction::Sqrt => Ok(sqrt(parse_expr(&args[0], registry, codec)?)),
ScalarFunction::Cbrt => Ok(cbrt(parse_expr(&args[0], registry, codec)?)),
ScalarFunction::Sin => Ok(sin(parse_expr(&args[0], registry, codec)?)),
diff --git a/datafusion/proto/src/logical_plan/to_proto.rs b/datafusion/proto/src/logical_plan/to_proto.rs
index bbf842712e..0d9909ca8e 100644
--- a/datafusion/proto/src/logical_plan/to_proto.rs
+++ b/datafusion/proto/src/logical_plan/to_proto.rs
@@ -1462,8 +1462,6 @@ impl TryFrom<&BuiltinScalarFunction> for protobuf::ScalarFunction {
BuiltinScalarFunction::ArrayReplace => Self::ArrayReplace,
BuiltinScalarFunction::ArrayReplaceN => Self::ArrayReplaceN,
BuiltinScalarFunction::ArrayReplaceAll => Self::ArrayReplaceAll,
- BuiltinScalarFunction::ArrayIntersect => Self::ArrayIntersect,
- BuiltinScalarFunction::ArrayUnion => Self::ArrayUnion,
BuiltinScalarFunction::Log2 => Self::Log2,
BuiltinScalarFunction::Signum => Self::Signum,
BuiltinScalarFunction::Ascii => Self::Ascii,
diff --git a/datafusion/proto/tests/cases/roundtrip_logical_plan.rs b/datafusion/proto/tests/cases/roundtrip_logical_plan.rs
index ac3e0209ed..97dd32607b 100644
--- a/datafusion/proto/tests/cases/roundtrip_logical_plan.rs
+++ b/datafusion/proto/tests/cases/roundtrip_logical_plan.rs
@@ -566,6 +566,14 @@ async fn roundtrip_expr_api() -> Result<()> {
lit("NULLS LAST"),
),
array_distinct(make_array(vec![lit(1), lit(3), lit(3), lit(2), lit(2)])),
+ array_intersect(
+ make_array(vec![lit(1), lit(3)]),
+ make_array(vec![lit(1), lit(4)]),
+ ),
+ array_union(
+ make_array(vec![lit(1), lit(3)]),
+ make_array(vec![lit(1), lit(4)]),
+ ),
array_resize(make_array(vec![lit(1), lit(2), lit(3)]), lit(5), lit(0)),
array_element(make_array(vec![lit(1), lit(2), lit(3)]), lit(2)),
array_slice(