sunchao commented on code in PR #7717:
URL: https://github.com/apache/datafusion-comet/pull/7717#discussion_r4793787301


##########
native/spark-expr/src/array_funcs/array_position.rs:
##########
@@ -15,300 +15,108 @@
 // specific language governing permissions and limitations
 // under the License.
 
+use std::sync::Arc;
+
+use super::array_match::{invoke_match, MatchOperation, MatchRows};
+use crate::float_semantics::spark_equality_by_ordinal;
 use arrow::array::{
-    make_comparator, Array, ArrayRef, AsArray, BooleanArray, GenericListArray, 
Int64Array,
-    OffsetSizeTrait,
-};
-use arrow::buffer::{NullBuffer, ScalarBuffer};
-use arrow::compute::SortOptions;
-use arrow::datatypes::{
-    ArrowPrimitiveType, DataType, Date32Type, Decimal128Type, Float32Type, 
Float64Type, Int16Type,
-    Int32Type, Int64Type, Int8Type, TimestampMicrosecondType,
+    Array, ArrayRef, AsArray, BooleanArray, Date32Array, Decimal128Array, 
GenericListArray,
+    Int16Array, Int32Array, Int64Array, Int8Array, LargeStringArray, 
OffsetSizeTrait, StringArray,
+    TimestampMicrosecondArray,
 };
-use datafusion::common::{exec_err, DataFusionError, Result as 
DataFusionResult, ScalarValue};
+use arrow::datatypes::{DataType, TimeUnit};
+use datafusion::common::{exec_err, Result};
 use datafusion::logical_expr::{
     ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, 
TypeSignature, Volatility,
 };
-use std::cmp::Ordering;
-use std::sync::Arc;
-
-use crate::float_semantics::{compare_floats, has_float_leaf, 
normalize_nested_floats};
-
-/// Spark array_position() function that returns the 1-based position of an 
element in an array.
-/// Returns 0 if the element is not found (Spark behavior differs from 
DataFusion which returns null).
-fn spark_array_position(args: &[ColumnarValue]) -> Result<ColumnarValue, 
DataFusionError> {
-    if args.len() != 2 {
-        return exec_err!("array_position function takes exactly two 
arguments");
-    }
-
-    let len = args
-        .iter()
-        .fold(Option::<usize>::None, |acc, arg| match arg {
-            ColumnarValue::Scalar(_) => acc,
-            ColumnarValue::Array(a) => Some(a.len()),
-        });
-
-    let is_scalar = len.is_none();
-    let arrays = ColumnarValue::values_to_arrays(args)?;
-
-    let result = array_position_inner(&arrays)?;
-
-    if is_scalar {
-        let scalar = ScalarValue::try_from_array(&result, 0)?;
-        Ok(ColumnarValue::Scalar(scalar))
-    } else {
-        Ok(ColumnarValue::Array(result))
-    }
-}
-
-fn array_position_inner(args: &[ArrayRef]) -> Result<ArrayRef, 
DataFusionError> {
-    let array = &args[0];
-    let element = &args[1];
 
+fn array_position(array: &ArrayRef, needle: &ColumnarValue) -> 
Result<ArrayRef> {
     match array.data_type() {
-        DataType::List(_) => generic_array_position::<i32>(array, element),
-        DataType::LargeList(_) => generic_array_position::<i64>(array, 
element),
+        DataType::List(_) => position(array.as_list::<i32>(), needle),
+        DataType::LargeList(_) => position(array.as_list::<i64>(), needle),
         other => exec_err!("array_position does not support type '{other:?}'"),
     }
 }
 
-/// Searches for an element in a list array using the flat values buffer and 
offsets directly,
-/// avoiding per-row subarray allocation. Dispatches to typed fast paths by 
element data type.
-fn generic_array_position<O: OffsetSizeTrait>(
-    array: &ArrayRef,
-    element: &ArrayRef,
-) -> Result<ArrayRef, DataFusionError> {
-    let list_array = array
-        .as_any()
-        .downcast_ref::<GenericListArray<O>>()
-        .ok_or_else(|| DataFusionError::Internal("expected list 
array".into()))?;
-
-    let values = list_array.values();
-    let offsets = list_array.offsets();
-    let elem_type = values.data_type().clone();
-
-    match &elem_type {
-        DataType::Boolean => position_boolean::<O>(list_array, offsets, 
values, element),
-        DataType::Int8 => position_primitive::<O, Int8Type>(list_array, 
offsets, values, element),
-        DataType::Int16 => position_primitive::<O, Int16Type>(list_array, 
offsets, values, element),
-        DataType::Int32 => position_primitive::<O, Int32Type>(list_array, 
offsets, values, element),
-        DataType::Int64 => position_primitive::<O, Int64Type>(list_array, 
offsets, values, element),
-        DataType::Float32 => position_float::<O, Float32Type>(list_array, 
offsets, values, element),
-        DataType::Float64 => position_float::<O, Float64Type>(list_array, 
offsets, values, element),
-        DataType::Decimal128(_, _) => {
-            position_primitive::<O, Decimal128Type>(list_array, offsets, 
values, element)
-        }
-        DataType::Date32 => {
-            position_primitive::<O, Date32Type>(list_array, offsets, values, 
element)
-        }
-        DataType::Timestamp(arrow::datatypes::TimeUnit::Microsecond, _) => {
-            position_primitive::<O, TimestampMicrosecondType>(list_array, 
offsets, values, element)
-        }
-        DataType::Utf8 => position_string::<O, i32>(list_array, offsets, 
values, element),
-        DataType::LargeUtf8 => position_string::<O, i64>(list_array, offsets, 
values, element),
-        // Fallback to Arrow's comparator for complex types (nested arrays, 
etc.)
-        _ => position_fallback::<O>(list_array, offsets, values, element),
-    }
-}
-
-/// Compute the combined null buffer from list array and element nulls.
-fn combined_nulls(
-    list_array_nulls: Option<&NullBuffer>,
-    element_nulls: Option<&NullBuffer>,
-) -> Option<NullBuffer> {
-    match (list_array_nulls, element_nulls) {
-        (Some(a), Some(b)) => NullBuffer::union(Some(a), Some(b)),
-        (Some(a), None) => Some(a.clone()),
-        (None, Some(b)) => Some(b.clone()),
-        (None, None) => None,
-    }
-}
-
-/// Fast path for primitive types: downcast once, iterate using offsets into 
the flat buffer.
-fn position_primitive<O: OffsetSizeTrait, T: ArrowPrimitiveType>(
-    list_array: &GenericListArray<O>,
-    offsets: &arrow::buffer::OffsetBuffer<O>,
-    values: &ArrayRef,
-    element: &ArrayRef,
-) -> Result<ArrayRef, DataFusionError>
-where
-    T::Native: PartialEq,
-{
-    let values_typed = values.as_primitive::<T>();
-    let element_typed = element.as_primitive::<T>();
-    let num_rows = list_array.len();
-    let nulls = combined_nulls(list_array.nulls(), element.nulls());
-    let mut result = vec![0i64; num_rows];
-
-    for (row_index, w) in offsets.windows(2).enumerate() {
-        if nulls.as_ref().is_some_and(|n| n.is_null(row_index)) {
-            continue;
-        }
-        let start = w[0].as_usize();
-        let end = w[1].as_usize();
-        let search_val = element_typed.value(row_index);
-        for i in start..end {
-            if !values_typed.is_null(i) && values_typed.value(i) == search_val 
{
-                result[row_index] = (i - start + 1) as i64;
-                break;
+fn position<O: OffsetSizeTrait>(
+    array: &GenericListArray<O>,
+    needle: &ColumnarValue,
+) -> Result<ArrayRef> {
+    let rows = MatchRows::new(array, needle)?;
+    let values = array.values();
+
+    // Only position needs typed non-float comparisons: contains and remove 
use DataFusion here.
+    macro_rules! typed_position {
+        ($ty:ty) => {
+            if let (Some(values), Some(needles)) = (
+                values.as_any().downcast_ref::<$ty>(),
+                rows.needles.as_any().downcast_ref::<$ty>(),
+            ) {
+                return SparkArrayPositionFunc::apply(&rows, |i, j| {
+                    values.value(i) == needles.value(j)
+                });
             }
-        }
-    }
-
-    Ok(Arc::new(Int64Array::new(ScalarBuffer::from(result), nulls)))
+        };
+    }
+    match values.data_type() {
+        DataType::Boolean => typed_position!(BooleanArray),
+        DataType::Int8 => typed_position!(Int8Array),
+        DataType::Int16 => typed_position!(Int16Array),
+        DataType::Int32 => typed_position!(Int32Array),
+        DataType::Int64 => typed_position!(Int64Array),
+        DataType::Decimal128(_, _) => typed_position!(Decimal128Array),
+        DataType::Date32 => typed_position!(Date32Array),
+        DataType::Timestamp(TimeUnit::Microsecond, _) => 
typed_position!(TimestampMicrosecondArray),
+        DataType::Utf8 => typed_position!(StringArray),
+        DataType::LargeUtf8 => typed_position!(LargeStringArray),
+        _ => {}
+    }
+    rows.evaluate::<SparkArrayPositionFunc>(spark_equality_by_ordinal)

Review Comment:
   Kept ordinal struct matching for the public SparkArrayPositionFunc UDF 
(Any(2)), preserving its existing Rust-call behavior when field names differ. I 
added a comment and regression coverage for that case. Spark coerces the SQL 
inputs to the same element type, so I do not know of a SQL case with different 
timestamp time zones; the flat native timestamp path continues to compare 
microsecond values as before.



##########
native/spark-expr/src/array_funcs/array_match.rs:
##########
@@ -0,0 +1,194 @@
+// 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.
+
+//! Element matching for Spark's array_contains, array_position and 
array_remove.
+
+use std::ops::Range;
+use std::sync::Arc;
+
+use crate::float_semantics::{compare_float_array_scalar, compare_floats, 
spark_equality};
+use arrow::array::{
+    Array, ArrayRef, AsArray, BooleanArray, GenericListArray, ListArray, 
OffsetSizeTrait,
+    PrimitiveArray,
+};
+use arrow::buffer::{BooleanBuffer, NullBuffer};
+use arrow::datatypes::{ArrowPrimitiveType, DataType, Float32Type, Float64Type};
+use datafusion::common::{exec_err, utils::take_function_args, Result, 
ScalarValue};
+use datafusion::logical_expr::{ColumnarValue, Operator, ScalarFunctionArgs, 
ScalarUDFImpl};
+use num::Float;
+
+pub(super) fn invoke_match(
+    udf: &impl ScalarUDFImpl,
+    args: ScalarFunctionArgs,
+    evaluate: impl FnOnce(&ArrayRef, &ColumnarValue) -> Result<ArrayRef>,
+) -> Result<ColumnarValue> {
+    let [array, needle] = take_function_args(udf.name(), &args.args)?;
+    let rows = match (array, needle) {
+        (_, ColumnarValue::Array(values)) => Some(values.len()),
+        (ColumnarValue::Array(list), _) => Some(list.len()),
+        _ => None,
+    };
+    let result = evaluate(&array.to_array_of_size(rows.unwrap_or(1))?, 
needle)?;
+    match rows {
+        None => Ok(ColumnarValue::Scalar(ScalarValue::try_from_array(
+            &result, 0,
+        )?)),
+        Some(_) => Ok(ColumnarValue::Array(result)),
+    }
+}
+
+/// Contains and remove can consume a bitmap for a scalar float. `IS [NOT] 
DISTINCT FROM`
+/// applies Spark's float equality and treats null elements as distinct from 
the non-null needle.
+pub(super) fn invoke_with_mask<M: ScalarUDFImpl + MatchOperation<i32>>(
+    udf: &M,
+    args: ScalarFunctionArgs,
+    op: Operator,
+    from_mask: impl FnOnce(&ListArray, &ArrayRef, BooleanBuffer) -> 
Result<ArrayRef>,
+) -> Result<ColumnarValue> {
+    invoke_match(udf, args, |array, needle| {
+        let Some(list) = array.as_list_opt::<i32>() else {
+            return exec_err!("{} takes a list, got {}", udf.name(), 
array.data_type());
+        };
+        // array_contains accepts a null scalar of any type. For array_remove, 
let
+        // the row matcher validate the element type even when the needle is 
null.
+        if op == Operator::IsNotDistinctFrom

Review Comment:
   Moved the null-scalar case into array_contains, before invoking the shared 
mask helper. The operator now only selects the comparison mask.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to