Skip to content

Apache DataFusion SQL Query Engine

Port `ArrayRemove`, `ArrayRemoveN`, `ArrayRemoveAll` to `functions-array` subcrate (#9656)

Eren Avsarogullaric7a72e63605e
diff --git a/datafusion/expr/src/built_in_function.rs b/datafusion/expr/src/built_in_function.rs
index 8839bc33f7..fe3397b1af 100644
--- a/datafusion/expr/src/built_in_function.rs
+++ b/datafusion/expr/src/built_in_function.rs
@@ -103,12 +103,6 @@ pub enum BuiltinScalarFunction {
Cot,
// array functions
- /// array_remove
- ArrayRemove,
- /// array_remove_n
- ArrayRemoveN,
- /// array_remove_all
- ArrayRemoveAll,
/// array_replace
ArrayReplace,
/// array_replace_n
@@ -268,9 +262,6 @@ impl BuiltinScalarFunction {
BuiltinScalarFunction::Cbrt => Volatility::Immutable,
BuiltinScalarFunction::Cot => Volatility::Immutable,
BuiltinScalarFunction::Trunc => Volatility::Immutable,
- BuiltinScalarFunction::ArrayRemove => Volatility::Immutable,
- BuiltinScalarFunction::ArrayRemoveN => Volatility::Immutable,
- BuiltinScalarFunction::ArrayRemoveAll => Volatility::Immutable,
BuiltinScalarFunction::ArrayReplace => Volatility::Immutable,
BuiltinScalarFunction::ArrayReplaceN => Volatility::Immutable,
BuiltinScalarFunction::ArrayReplaceAll => Volatility::Immutable,
@@ -331,9 +322,6 @@ impl BuiltinScalarFunction {
// the return type of the built in function.
// Some built-in functions' return type depends on the incoming type.
match self {
- BuiltinScalarFunction::ArrayRemove => Ok(input_expr_types[0].clone()),
- BuiltinScalarFunction::ArrayRemoveN => Ok(input_expr_types[0].clone()),
- BuiltinScalarFunction::ArrayRemoveAll => Ok(input_expr_types[0].clone()),
BuiltinScalarFunction::ArrayReplace => Ok(input_expr_types[0].clone()),
BuiltinScalarFunction::ArrayReplaceN => Ok(input_expr_types[0].clone()),
BuiltinScalarFunction::ArrayReplaceAll => Ok(input_expr_types[0].clone()),
@@ -489,13 +477,6 @@ impl BuiltinScalarFunction {
// for now, the list is small, as we do not have many built-in functions.
match self {
- BuiltinScalarFunction::ArrayRemove => {
- Signature::array_and_element(self.volatility())
- }
- BuiltinScalarFunction::ArrayRemoveN => Signature::any(3, self.volatility()),
- BuiltinScalarFunction::ArrayRemoveAll => {
- Signature::array_and_element(self.volatility())
- }
BuiltinScalarFunction::ArrayReplace => Signature::any(3, self.volatility()),
BuiltinScalarFunction::ArrayReplaceN => Signature::any(4, self.volatility()),
BuiltinScalarFunction::ArrayReplaceAll => {
@@ -800,11 +781,6 @@ impl BuiltinScalarFunction {
BuiltinScalarFunction::FindInSet => &["find_in_set"],
// hashing functions
- BuiltinScalarFunction::ArrayRemove => &["array_remove", "list_remove"],
- BuiltinScalarFunction::ArrayRemoveN => &["array_remove_n", "list_remove_n"],
- BuiltinScalarFunction::ArrayRemoveAll => {
- &["array_remove_all", "list_remove_all"]
- }
BuiltinScalarFunction::ArrayReplace => &["array_replace", "list_replace"],
BuiltinScalarFunction::ArrayReplaceN => {
&["array_replace_n", "list_replace_n"]
diff --git a/datafusion/expr/src/expr_fn.rs b/datafusion/expr/src/expr_fn.rs
index 5e4d7cc1f5..c5ad2a9b3c 100644
--- a/datafusion/expr/src/expr_fn.rs
+++ b/datafusion/expr/src/expr_fn.rs
@@ -584,24 +584,6 @@ scalar_expr!(
scalar_expr!(Uuid, uuid, , "returns uuid v4 as a string value");
scalar_expr!(Log, log, base x, "logarithm of a `x` for a particular `base`");
-scalar_expr!(
- ArrayRemove,
- array_remove,
- array element,
- "removes the first element from the array equal to the given value."
-);
-scalar_expr!(
- ArrayRemoveN,
- array_remove_n,
- array element max,
- "removes the first `max` elements from the array equal to the given value."
-);
-scalar_expr!(
- ArrayRemoveAll,
- array_remove_all,
- array element,
- "removes all elements from the array equal to the given value."
-);
scalar_expr!(
ArrayReplace,
array_replace,
@@ -1164,9 +1146,6 @@ mod test {
test_scalar_expr!(Trim, trim, string);
test_scalar_expr!(Upper, upper, string);
- test_scalar_expr!(ArrayRemove, array_remove, array, element);
- test_scalar_expr!(ArrayRemoveN, array_remove_n, array, element, max);
- test_scalar_expr!(ArrayRemoveAll, array_remove_all, array, element);
test_scalar_expr!(ArrayReplace, array_replace, array, from, to);
test_scalar_expr!(ArrayReplaceN, array_replace_n, array, from, to, max);
test_scalar_expr!(ArrayReplaceAll, array_replace_all, array, from, to);
diff --git a/datafusion/functions-array/src/lib.rs b/datafusion/functions-array/src/lib.rs
index 1f49367958..2c19dfad62 100644
--- a/datafusion/functions-array/src/lib.rs
+++ b/datafusion/functions-array/src/lib.rs
@@ -35,6 +35,7 @@ mod except;
mod extract;
mod kernels;
mod position;
+mod remove;
mod rewrite;
mod set_ops;
mod udf;
@@ -62,6 +63,9 @@ pub mod expr_fn {
pub use super::extract::array_slice;
pub use super::position::array_position;
pub use super::position::array_positions;
+ pub use super::remove::array_remove;
+ pub use super::remove::array_remove_all;
+ pub use super::remove::array_remove_n;
pub use super::set_ops::array_distinct;
pub use super::set_ops::array_intersect;
pub use super::set_ops::array_union;
@@ -115,6 +119,9 @@ pub fn register_all(registry: &mut dyn FunctionRegistry) -> Result<()> {
set_ops::array_union_udf(),
position::array_position_udf(),
position::array_positions_udf(),
+ remove::array_remove_udf(),
+ remove::array_remove_n_udf(),
+ remove::array_remove_all_udf(),
];
functions.into_iter().try_for_each(|udf| {
let existing_udf = registry.register_udf(udf)?;
diff --git a/datafusion/functions-array/src/remove.rs b/datafusion/functions-array/src/remove.rs
new file mode 100644
index 0000000000..91c76a6708
--- /dev/null
+++ b/datafusion/functions-array/src/remove.rs
@@ -0,0 +1,324 @@
+// 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.
+
+//! [`ScalarUDFImpl`] definitions for array_remove, array_remove_n, array_remove_all functions.
+
+use crate::utils;
+use arrow_array::cast::AsArray;
+use arrow_array::{
+ new_empty_array, Array, ArrayRef, BooleanArray, GenericListArray, OffsetSizeTrait,
+};
+use arrow_buffer::OffsetBuffer;
+use arrow_schema::{DataType, Field};
+use datafusion_common::cast::as_int64_array;
+use datafusion_common::exec_err;
+use datafusion_expr::expr::ScalarFunction;
+use datafusion_expr::{ColumnarValue, Expr, ScalarUDFImpl, Signature, Volatility};
+use std::any::Any;
+use std::sync::Arc;
+
+make_udf_function!(
+ ArrayRemove,
+ array_remove,
+ array element,
+ "removes the first element from the array equal to the given value.",
+ array_remove_udf
+);
+
+#[derive(Debug)]
+pub(super) struct ArrayRemove {
+ signature: Signature,
+ aliases: Vec<String>,
+}
+
+impl ArrayRemove {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::array_and_element(Volatility::Immutable),
+ aliases: vec!["array_remove".to_string(), "list_remove".to_string()],
+ }
+ }
+}
+
+impl ScalarUDFImpl for ArrayRemove {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+ fn name(&self) -> &str {
+ "array_remove"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(&self, arg_types: &[DataType]) -> datafusion_common::Result<DataType> {
+ Ok(arg_types[0].clone())
+ }
+
+ fn invoke(&self, args: &[ColumnarValue]) -> datafusion_common::Result<ColumnarValue> {
+ let args = ColumnarValue::values_to_arrays(args)?;
+ array_remove_inner(&args).map(ColumnarValue::Array)
+ }
+
+ fn aliases(&self) -> &[String] {
+ &self.aliases
+ }
+}
+
+make_udf_function!(
+ ArrayRemoveN,
+ array_remove_n,
+ array element max,
+ "removes the first `max` elements from the array equal to the given value.",
+ array_remove_n_udf
+);
+
+#[derive(Debug)]
+pub(super) struct ArrayRemoveN {
+ signature: Signature,
+ aliases: Vec<String>,
+}
+
+impl ArrayRemoveN {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::any(3, Volatility::Immutable),
+ aliases: vec!["array_remove_n".to_string(), "list_remove_n".to_string()],
+ }
+ }
+}
+
+impl ScalarUDFImpl for ArrayRemoveN {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+ fn name(&self) -> &str {
+ "array_remove_n"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(&self, arg_types: &[DataType]) -> datafusion_common::Result<DataType> {
+ Ok(arg_types[0].clone())
+ }
+
+ fn invoke(&self, args: &[ColumnarValue]) -> datafusion_common::Result<ColumnarValue> {
+ let args = ColumnarValue::values_to_arrays(args)?;
+ array_remove_n_inner(&args).map(ColumnarValue::Array)
+ }
+
+ fn aliases(&self) -> &[String] {
+ &self.aliases
+ }
+}
+
+make_udf_function!(
+ ArrayRemoveAll,
+ array_remove_all,
+ array element,
+ "removes all elements from the array equal to the given value.",
+ array_remove_all_udf
+);
+
+#[derive(Debug)]
+pub(super) struct ArrayRemoveAll {
+ signature: Signature,
+ aliases: Vec<String>,
+}
+
+impl ArrayRemoveAll {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::array_and_element(Volatility::Immutable),
+ aliases: vec![
+ "array_remove_all".to_string(),
+ "list_remove_all".to_string(),
+ ],
+ }
+ }
+}
+
+impl ScalarUDFImpl for ArrayRemoveAll {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+ fn name(&self) -> &str {
+ "array_remove_all"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(&self, arg_types: &[DataType]) -> datafusion_common::Result<DataType> {
+ Ok(arg_types[0].clone())
+ }
+
+ fn invoke(&self, args: &[ColumnarValue]) -> datafusion_common::Result<ColumnarValue> {
+ let args = ColumnarValue::values_to_arrays(args)?;
+ array_remove_all_inner(&args).map(ColumnarValue::Array)
+ }
+
+ fn aliases(&self) -> &[String] {
+ &self.aliases
+ }
+}
+
+/// Array_remove SQL function
+pub fn array_remove_inner(args: &[ArrayRef]) -> datafusion_common::Result<ArrayRef> {
+ if args.len() != 2 {
+ return exec_err!("array_remove expects two arguments");
+ }
+
+ let arr_n = vec![1; args[0].len()];
+ array_remove_internal(&args[0], &args[1], arr_n)
+}
+
+/// Array_remove_n SQL function
+pub fn array_remove_n_inner(args: &[ArrayRef]) -> datafusion_common::Result<ArrayRef> {
+ if args.len() != 3 {
+ return exec_err!("array_remove_n expects three arguments");
+ }
+
+ let arr_n = as_int64_array(&args[2])?.values().to_vec();
+ array_remove_internal(&args[0], &args[1], arr_n)
+}
+
+/// Array_remove_all SQL function
+pub fn array_remove_all_inner(args: &[ArrayRef]) -> datafusion_common::Result<ArrayRef> {
+ if args.len() != 2 {
+ return exec_err!("array_remove_all expects two arguments");
+ }
+
+ let arr_n = vec![i64::MAX; args[0].len()];
+ array_remove_internal(&args[0], &args[1], arr_n)
+}
+
+fn array_remove_internal(
+ array: &ArrayRef,
+ element_array: &ArrayRef,
+ arr_n: Vec<i64>,
+) -> datafusion_common::Result<ArrayRef> {
+ match array.data_type() {
+ DataType::List(_) => {
+ let list_array = array.as_list::<i32>();
+ general_remove::<i32>(list_array, element_array, arr_n)
+ }
+ DataType::LargeList(_) => {
+ let list_array = array.as_list::<i64>();
+ general_remove::<i64>(list_array, element_array, arr_n)
+ }
+ array_type => {
+ exec_err!("array_remove_all does not support type '{array_type:?}'.")
+ }
+ }
+}
+
+/// For each element of `list_array[i]`, removed up to `arr_n[i]` occurences
+/// of `element_array[i]`.
+///
+/// The type of each **element** in `list_array` must be the same as the type of
+/// `element_array`. This function also handles nested arrays
+/// ([`arrow_array::ListArray`] of [`arrow_array::ListArray`]s)
+///
+/// For example, when called to remove a list array (where each element is a
+/// list of int32s, the second argument are int32 arrays, and the
+/// third argument is the number of occurrences to remove
+///
+/// ```text
+/// general_remove(
+/// [1, 2, 3, 2], 2, 1 ==> [1, 3, 2] (only the first 2 is removed)
+/// [4, 5, 6, 5], 5, 2 ==> [4, 6] (both 5s are removed)
+/// )
+/// ```
+fn general_remove<OffsetSize: OffsetSizeTrait>(
+ list_array: &GenericListArray<OffsetSize>,
+ element_array: &ArrayRef,
+ arr_n: Vec<i64>,
+) -> datafusion_common::Result<ArrayRef> {
+ let data_type = list_array.value_type();
+ let mut new_values = vec![];
+ // Build up the offsets for the final output array
+ let mut offsets = Vec::<OffsetSize>::with_capacity(arr_n.len() + 1);
+ offsets.push(OffsetSize::zero());
+
+ // n is the number of elements to remove in this row
+ for (row_index, (list_array_row, n)) in
+ list_array.iter().zip(arr_n.iter()).enumerate()
+ {
+ match list_array_row {
+ Some(list_array_row) => {
+ let eq_array = utils::compare_element_to_list(
+ &list_array_row,
+ element_array,
+ row_index,
+ false,
+ )?;
+
+ // We need to keep at most first n elements as `false`, which represent the elements to remove.
+ let eq_array = if eq_array.false_count() < *n as usize {
+ eq_array
+ } else {
+ let mut count = 0;
+ eq_array
+ .iter()
+ .map(|e| {
+ // Keep first n `false` elements, and reverse other elements to `true`.
+ if let Some(false) = e {
+ if count < *n {
+ count += 1;
+ e
+ } else {
+ Some(true)
+ }
+ } else {
+ e
+ }
+ })
+ .collect::<BooleanArray>()
+ };
+
+ let filtered_array = arrow::compute::filter(&list_array_row, &eq_array)?;
+ offsets.push(
+ offsets[row_index] + OffsetSize::usize_as(filtered_array.len()),
+ );
+ new_values.push(filtered_array);
+ }
+ None => {
+ // Null element results in a null row (no new offsets)
+ offsets.push(offsets[row_index]);
+ }
+ }
+ }
+
+ let values = if new_values.is_empty() {
+ new_empty_array(&data_type)
+ } else {
+ let new_values = new_values.iter().map(|x| x.as_ref()).collect::<Vec<_>>();
+ arrow::compute::concat(&new_values)?
+ };
+
+ Ok(Arc::new(GenericListArray::<OffsetSize>::try_new(
+ Arc::new(Field::new("item", data_type, true)),
+ OffsetBuffer::new(offsets.into()),
+ values,
+ list_array.nulls().cloned(),
+ )?))
+}
diff --git a/datafusion/functions-array/src/utils.rs b/datafusion/functions-array/src/utils.rs
index f7c0924893..ad613163c6 100644
--- a/datafusion/functions-array/src/utils.rs
+++ b/datafusion/functions-array/src/utils.rs
@@ -20,10 +20,13 @@
use std::sync::Arc;
use arrow::{array::ArrayRef, datatypes::DataType};
-use arrow_array::{GenericListArray, OffsetSizeTrait};
+use arrow_array::{
+ Array, BooleanArray, GenericListArray, OffsetSizeTrait, Scalar, UInt32Array,
+};
use arrow_buffer::OffsetBuffer;
use arrow_schema::Field;
-use datafusion_common::{plan_err, Result, ScalarValue};
+use datafusion_common::cast::{as_large_list_array, as_list_array};
+use datafusion_common::{exec_err, plan_err, Result, ScalarValue};
use datafusion_expr::{ColumnarValue, ScalarFunctionImplementation};
pub(crate) fn check_datatypes(name: &str, args: &[&ArrayRef]) -> Result<()> {
@@ -108,6 +111,107 @@ pub(crate) fn align_array_dimensions<O: OffsetSizeTrait>(
aligned_args
}
+/// Computes a BooleanArray indicating equality or inequality between elements in a list array and a specified element array.
+///
+/// # Arguments
+///
+/// * `list_array_row` - A reference to a trait object implementing the Arrow `Array` trait. It represents the list array for which the equality or inequality will be compared.
+///
+/// * `element_array` - A reference to a trait object implementing the Arrow `Array` trait. It represents the array with which each element in the `list_array_row` will be compared.
+///
+/// * `row_index` - The index of the row in the `element_array` and `list_array` to use for the comparison.
+///
+/// * `eq` - A boolean flag. If `true`, the function computes equality; if `false`, it computes inequality.
+///
+/// # Returns
+///
+/// Returns a `Result<BooleanArray>` representing the comparison results. The result may contain an error if there are issues with the computation.
+///
+/// # Example
+///
+/// ```text
+/// compare_element_to_list(
+/// [1, 2, 3], [1, 2, 3], 0, true => [true, false, false]
+/// [1, 2, 3, 3, 2, 1], [1, 2, 3], 1, true => [false, true, false, false, true, false]
+///
+/// [[1, 2, 3], [2, 3, 4], [3, 4, 5]], [[1, 2, 3], [2, 3, 4], [3, 4, 5]], 0, true => [true, false, false]
+/// [[1, 2, 3], [2, 3, 4], [2, 3, 4]], [[1, 2, 3], [2, 3, 4], [3, 4, 5]], 1, false => [true, false, false]
+/// )
+/// ```
+pub(crate) fn compare_element_to_list(
+ list_array_row: &dyn Array,
+ element_array: &dyn Array,
+ row_index: usize,
+ eq: bool,
+) -> Result<BooleanArray> {
+ if list_array_row.data_type() != element_array.data_type() {
+ return exec_err!(
+ "compare_element_to_list received incompatible types: '{:?}' and '{:?}'.",
+ list_array_row.data_type(),
+ element_array.data_type()
+ );
+ }
+
+ let indices = UInt32Array::from(vec![row_index as u32]);
+ let element_array_row = arrow::compute::take(element_array, &indices, None)?;
+
+ // Compute all positions in list_row_array (that is itself an
+ // array) that are equal to `from_array_row`
+ let res = match element_array_row.data_type() {
+ // arrow_ord::cmp::eq does not support ListArray, so we need to compare it by loop
+ DataType::List(_) => {
+ // compare each element of the from array
+ let element_array_row_inner = as_list_array(&element_array_row)?.value(0);
+ let list_array_row_inner = as_list_array(list_array_row)?;
+
+ list_array_row_inner
+ .iter()
+ // compare element by element the current row of list_array
+ .map(|row| {
+ row.map(|row| {
+ if eq {
+ row.eq(&element_array_row_inner)
+ } else {
+ row.ne(&element_array_row_inner)
+ }
+ })
+ })
+ .collect::<BooleanArray>()
+ }
+ DataType::LargeList(_) => {
+ // compare each element of the from array
+ let element_array_row_inner =
+ as_large_list_array(&element_array_row)?.value(0);
+ let list_array_row_inner = as_large_list_array(list_array_row)?;
+
+ list_array_row_inner
+ .iter()
+ // compare element by element the current row of list_array
+ .map(|row| {
+ row.map(|row| {
+ if eq {
+ row.eq(&element_array_row_inner)
+ } else {
+ row.ne(&element_array_row_inner)
+ }
+ })
+ })
+ .collect::<BooleanArray>()
+ }
+ _ => {
+ let element_arr = Scalar::new(element_array_row);
+ // use not_distinct so we can compare NULL
+ if eq {
+ arrow::compute::kernels::cmp::not_distinct(&list_array_row, &element_arr)?
+ } else {
+ arrow::compute::kernels::cmp::distinct(&list_array_row, &element_arr)?
+ }
+ }
+ };
+
+ Ok(res)
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/datafusion/physical-expr/src/array_expressions.rs b/datafusion/physical-expr/src/array_expressions.rs
index f53ef954d0..c3c0f4c822 100644
--- a/datafusion/physical-expr/src/array_expressions.rs
+++ b/datafusion/physical-expr/src/array_expressions.rs
@@ -244,145 +244,6 @@ pub fn make_array(arrays: &[ArrayRef]) -> Result<ArrayRef> {
}
}
-/// For each element of `list_array[i]`, removed up to `arr_n[i]` occurences
-/// of `element_array[i]`.
-///
-/// The type of each **element** in `list_array` must be the same as the type of
-/// `element_array`. This function also handles nested arrays
-/// ([`ListArray`] of [`ListArray`]s)
-///
-/// For example, when called to remove a list array (where each element is a
-/// list of int32s, the second argument are int32 arrays, and the
-/// third argument is the number of occurrences to remove
-///
-/// ```text
-/// general_remove(
-/// [1, 2, 3, 2], 2, 1 ==> [1, 3, 2] (only the first 2 is removed)
-/// [4, 5, 6, 5], 5, 2 ==> [4, 6] (both 5s are removed)
-/// )
-/// ```
-fn general_remove<OffsetSize: OffsetSizeTrait>(
- list_array: &GenericListArray<OffsetSize>,
- element_array: &ArrayRef,
- arr_n: Vec<i64>,
-) -> Result<ArrayRef> {
- let data_type = list_array.value_type();
- let mut new_values = vec![];
- // Build up the offsets for the final output array
- let mut offsets = Vec::<OffsetSize>::with_capacity(arr_n.len() + 1);
- offsets.push(OffsetSize::zero());
-
- // n is the number of elements to remove in this row
- for (row_index, (list_array_row, n)) in
- list_array.iter().zip(arr_n.iter()).enumerate()
- {
- match list_array_row {
- Some(list_array_row) => {
- let eq_array = compare_element_to_list(
- &list_array_row,
- element_array,
- row_index,
- false,
- )?;
-
- // We need to keep at most first n elements as `false`, which represent the elements to remove.
- let eq_array = if eq_array.false_count() < *n as usize {
- eq_array
- } else {
- let mut count = 0;
- eq_array
- .iter()
- .map(|e| {
- // Keep first n `false` elements, and reverse other elements to `true`.
- if let Some(false) = e {
- if count < *n {
- count += 1;
- e
- } else {
- Some(true)
- }
- } else {
- e
- }
- })
- .collect::<BooleanArray>()
- };
-
- let filtered_array = arrow::compute::filter(&list_array_row, &eq_array)?;
- offsets.push(
- offsets[row_index] + OffsetSize::usize_as(filtered_array.len()),
- );
- new_values.push(filtered_array);
- }
- None => {
- // Null element results in a null row (no new offsets)
- offsets.push(offsets[row_index]);
- }
- }
- }
-
- let values = if new_values.is_empty() {
- new_empty_array(&data_type)
- } else {
- let new_values = new_values.iter().map(|x| x.as_ref()).collect::<Vec<_>>();
- arrow::compute::concat(&new_values)?
- };
-
- Ok(Arc::new(GenericListArray::<OffsetSize>::try_new(
- Arc::new(Field::new("item", data_type, true)),
- OffsetBuffer::new(offsets.into()),
- values,
- list_array.nulls().cloned(),
- )?))
-}
-
-fn array_remove_internal(
- array: &ArrayRef,
- element_array: &ArrayRef,
- arr_n: Vec<i64>,
-) -> Result<ArrayRef> {
- match array.data_type() {
- DataType::List(_) => {
- let list_array = array.as_list::<i32>();
- general_remove::<i32>(list_array, element_array, arr_n)
- }
- DataType::LargeList(_) => {
- let list_array = array.as_list::<i64>();
- general_remove::<i64>(list_array, element_array, arr_n)
- }
- array_type => {
- exec_err!("array_remove_all does not support type '{array_type:?}'.")
- }
- }
-}
-
-pub fn array_remove_all(args: &[ArrayRef]) -> Result<ArrayRef> {
- if args.len() != 2 {
- return exec_err!("array_remove_all expects two arguments");
- }
-
- let arr_n = vec![i64::MAX; args[0].len()];
- array_remove_internal(&args[0], &args[1], arr_n)
-}
-
-pub fn array_remove(args: &[ArrayRef]) -> Result<ArrayRef> {
- if args.len() != 2 {
- return exec_err!("array_remove expects two arguments");
- }
-
- let arr_n = vec![1; args[0].len()];
- array_remove_internal(&args[0], &args[1], arr_n)
-}
-
-pub fn array_remove_n(args: &[ArrayRef]) -> Result<ArrayRef> {
- if args.len() != 3 {
- return exec_err!("array_remove_n expects three arguments");
- }
-
- let arr_n = as_int64_array(&args[2])?.values().to_vec();
- array_remove_internal(&args[0], &args[1], arr_n)
-}
-
/// For each element of `list_array[i]`, replaces up to `arr_n[i]` occurences
/// of `from_array[i]`, `to_array[i]`.
///
diff --git a/datafusion/physical-expr/src/functions.rs b/datafusion/physical-expr/src/functions.rs
index 53f3127029..994c17309e 100644
--- a/datafusion/physical-expr/src/functions.rs
+++ b/datafusion/physical-expr/src/functions.rs
@@ -255,15 +255,6 @@ pub fn create_physical_fun(
}
// array functions
- BuiltinScalarFunction::ArrayRemove => Arc::new(|args| {
- make_scalar_function_inner(array_expressions::array_remove)(args)
- }),
- BuiltinScalarFunction::ArrayRemoveN => Arc::new(|args| {
- make_scalar_function_inner(array_expressions::array_remove_n)(args)
- }),
- BuiltinScalarFunction::ArrayRemoveAll => Arc::new(|args| {
- make_scalar_function_inner(array_expressions::array_remove_all)(args)
- }),
BuiltinScalarFunction::ArrayReplace => Arc::new(|args| {
make_scalar_function_inner(array_expressions::array_replace)(args)
}),
diff --git a/datafusion/proto/proto/datafusion.proto b/datafusion/proto/proto/datafusion.proto
index 044fe4f49e..5970947585 100644
--- a/datafusion/proto/proto/datafusion.proto
+++ b/datafusion/proto/proto/datafusion.proto
@@ -636,7 +636,7 @@ enum ScalarFunction {
// 92 was ArrayPosition
// 93 was ArrayPositions
// 94 was ArrayPrepend
- ArrayRemove = 95;
+ // 95 was ArrayRemove
ArrayReplace = 96;
// 97 was ArrayToString
// 98 was Cardinality
@@ -646,9 +646,9 @@ enum ScalarFunction {
// 104 was ArrayHas
// 105 was ArrayHasAny
// 106 was ArrayHasAll
- ArrayRemoveN = 107;
+ // 107 was ArrayRemoveN
ArrayReplaceN = 108;
- ArrayRemoveAll = 109;
+ // 109 was ArrayRemoveAll
ArrayReplaceAll = 110;
Nanvl = 111;
// 112 was Flatten
diff --git a/datafusion/proto/src/generated/pbjson.rs b/datafusion/proto/src/generated/pbjson.rs
index 7e684d6848..cb9633338e 100644
--- a/datafusion/proto/src/generated/pbjson.rs
+++ b/datafusion/proto/src/generated/pbjson.rs
@@ -22951,12 +22951,9 @@ impl serde::Serialize for ScalarFunction {
Self::Factorial => "Factorial",
Self::Lcm => "Lcm",
Self::Gcd => "Gcd",
- Self::ArrayRemove => "ArrayRemove",
Self::ArrayReplace => "ArrayReplace",
Self::Cot => "Cot",
- Self::ArrayRemoveN => "ArrayRemoveN",
Self::ArrayReplaceN => "ArrayReplaceN",
- Self::ArrayRemoveAll => "ArrayRemoveAll",
Self::ArrayReplaceAll => "ArrayReplaceAll",
Self::Nanvl => "Nanvl",
Self::Iszero => "Iszero",
@@ -23035,12 +23032,9 @@ impl<'de> serde::Deserialize<'de> for ScalarFunction {
"Factorial",
"Lcm",
"Gcd",
- "ArrayRemove",
"ArrayReplace",
"Cot",
- "ArrayRemoveN",
"ArrayReplaceN",
- "ArrayRemoveAll",
"ArrayReplaceAll",
"Nanvl",
"Iszero",
@@ -23148,12 +23142,9 @@ impl<'de> serde::Deserialize<'de> for ScalarFunction {
"Factorial" => Ok(ScalarFunction::Factorial),
"Lcm" => Ok(ScalarFunction::Lcm),
"Gcd" => Ok(ScalarFunction::Gcd),
- "ArrayRemove" => Ok(ScalarFunction::ArrayRemove),
"ArrayReplace" => Ok(ScalarFunction::ArrayReplace),
"Cot" => Ok(ScalarFunction::Cot),
- "ArrayRemoveN" => Ok(ScalarFunction::ArrayRemoveN),
"ArrayReplaceN" => Ok(ScalarFunction::ArrayReplaceN),
- "ArrayRemoveAll" => Ok(ScalarFunction::ArrayRemoveAll),
"ArrayReplaceAll" => Ok(ScalarFunction::ArrayReplaceAll),
"Nanvl" => Ok(ScalarFunction::Nanvl),
"Iszero" => Ok(ScalarFunction::Iszero),
diff --git a/datafusion/proto/src/generated/prost.rs b/datafusion/proto/src/generated/prost.rs
index dcd28f8b98..f5ef6c1f74 100644
--- a/datafusion/proto/src/generated/prost.rs
+++ b/datafusion/proto/src/generated/prost.rs
@@ -2909,7 +2909,7 @@ pub enum ScalarFunction {
/// 92 was ArrayPosition
/// 93 was ArrayPositions
/// 94 was ArrayPrepend
- ArrayRemove = 95,
+ /// 95 was ArrayRemove
ArrayReplace = 96,
/// 97 was ArrayToString
/// 98 was Cardinality
@@ -2919,9 +2919,9 @@ pub enum ScalarFunction {
/// 104 was ArrayHas
/// 105 was ArrayHasAny
/// 106 was ArrayHasAll
- ArrayRemoveN = 107,
+ /// 107 was ArrayRemoveN
ArrayReplaceN = 108,
- ArrayRemoveAll = 109,
+ /// 109 was ArrayRemoveAll
ArrayReplaceAll = 110,
Nanvl = 111,
/// 112 was Flatten
@@ -3019,12 +3019,9 @@ impl ScalarFunction {
ScalarFunction::Factorial => "Factorial",
ScalarFunction::Lcm => "Lcm",
ScalarFunction::Gcd => "Gcd",
- ScalarFunction::ArrayRemove => "ArrayRemove",
ScalarFunction::ArrayReplace => "ArrayReplace",
ScalarFunction::Cot => "Cot",
- ScalarFunction::ArrayRemoveN => "ArrayRemoveN",
ScalarFunction::ArrayReplaceN => "ArrayReplaceN",
- ScalarFunction::ArrayRemoveAll => "ArrayRemoveAll",
ScalarFunction::ArrayReplaceAll => "ArrayReplaceAll",
ScalarFunction::Nanvl => "Nanvl",
ScalarFunction::Iszero => "Iszero",
@@ -3097,12 +3094,9 @@ impl ScalarFunction {
"Factorial" => Some(Self::Factorial),
"Lcm" => Some(Self::Lcm),
"Gcd" => Some(Self::Gcd),
- "ArrayRemove" => Some(Self::ArrayRemove),
"ArrayReplace" => Some(Self::ArrayReplace),
"Cot" => Some(Self::Cot),
- "ArrayRemoveN" => Some(Self::ArrayRemoveN),
"ArrayReplaceN" => Some(Self::ArrayReplaceN),
- "ArrayRemoveAll" => Some(Self::ArrayRemoveAll),
"ArrayReplaceAll" => Some(Self::ArrayReplaceAll),
"Nanvl" => Some(Self::Nanvl),
"Iszero" => Some(Self::Iszero),
diff --git a/datafusion/proto/src/logical_plan/from_proto.rs b/datafusion/proto/src/logical_plan/from_proto.rs
index 8cd98aeadb..3822b74bc1 100644
--- a/datafusion/proto/src/logical_plan/from_proto.rs
+++ b/datafusion/proto/src/logical_plan/from_proto.rs
@@ -48,10 +48,9 @@ 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_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,
+ acosh, 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,
@@ -467,9 +466,6 @@ impl From<&protobuf::ScalarFunction> for BuiltinScalarFunction {
ScalarFunction::Trim => Self::Trim,
ScalarFunction::Ltrim => Self::Ltrim,
ScalarFunction::Rtrim => Self::Rtrim,
- ScalarFunction::ArrayRemove => Self::ArrayRemove,
- ScalarFunction::ArrayRemoveN => Self::ArrayRemoveN,
- ScalarFunction::ArrayRemoveAll => Self::ArrayRemoveAll,
ScalarFunction::ArrayReplace => Self::ArrayReplace,
ScalarFunction::ArrayReplaceN => Self::ArrayReplaceN,
ScalarFunction::ArrayReplaceAll => Self::ArrayReplaceAll,
@@ -1366,19 +1362,6 @@ pub fn parse_expr(
ScalarFunction::Acosh => {
Ok(acosh(parse_expr(&args[0], registry, codec)?))
}
- ScalarFunction::ArrayRemove => Ok(array_remove(
- parse_expr(&args[0], registry, codec)?,
- parse_expr(&args[1], registry, codec)?,
- )),
- ScalarFunction::ArrayRemoveN => Ok(array_remove_n(
- parse_expr(&args[0], registry, codec)?,
- parse_expr(&args[1], registry, codec)?,
- parse_expr(&args[2], registry, codec)?,
- )),
- ScalarFunction::ArrayRemoveAll => Ok(array_remove_all(
- parse_expr(&args[0], registry, codec)?,
- parse_expr(&args[1], registry, codec)?,
- )),
ScalarFunction::ArrayReplace => Ok(array_replace(
parse_expr(&args[0], registry, codec)?,
parse_expr(&args[1], registry, codec)?,
diff --git a/datafusion/proto/src/logical_plan/to_proto.rs b/datafusion/proto/src/logical_plan/to_proto.rs
index 031ce66252..7a17d2a2b4 100644
--- a/datafusion/proto/src/logical_plan/to_proto.rs
+++ b/datafusion/proto/src/logical_plan/to_proto.rs
@@ -1453,9 +1453,6 @@ impl TryFrom<&BuiltinScalarFunction> for protobuf::ScalarFunction {
BuiltinScalarFunction::Trim => Self::Trim,
BuiltinScalarFunction::Ltrim => Self::Ltrim,
BuiltinScalarFunction::Rtrim => Self::Rtrim,
- BuiltinScalarFunction::ArrayRemove => Self::ArrayRemove,
- BuiltinScalarFunction::ArrayRemoveN => Self::ArrayRemoveN,
- BuiltinScalarFunction::ArrayRemoveAll => Self::ArrayRemoveAll,
BuiltinScalarFunction::ArrayReplace => Self::ArrayReplace,
BuiltinScalarFunction::ArrayReplaceN => Self::ArrayReplaceN,
BuiltinScalarFunction::ArrayReplaceAll => Self::ArrayReplaceAll,
diff --git a/datafusion/proto/tests/cases/roundtrip_logical_plan.rs b/datafusion/proto/tests/cases/roundtrip_logical_plan.rs
index 8d0ff2d304..479f80fbdd 100644
--- a/datafusion/proto/tests/cases/roundtrip_logical_plan.rs
+++ b/datafusion/proto/tests/cases/roundtrip_logical_plan.rs
@@ -595,6 +595,16 @@ async fn roundtrip_expr_api() -> Result<()> {
make_array(vec![lit(1), lit(2), lit(3)]),
make_array(vec![lit(1), lit(2)]),
),
+ array_remove(make_array(vec![lit(4), lit(3), lit(2), lit(1)]), lit(3)),
+ array_remove_n(
+ make_array(vec![lit(1), lit(3), lit(3), lit(3)]),
+ lit(3),
+ lit(2),
+ ),
+ array_remove_all(
+ make_array(vec![lit(3), lit(3), lit(2), lit(3), lit(1)]),
+ lit(3),
+ ),
];
// ensure expressions created with the expr api can be round tripped