You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by GitBox <gi...@apache.org> on 2022/05/18 13:40:08 UTC

[GitHub] [arrow-datafusion] alamb commented on a diff in pull request #2549: feat: support for AnyExpression

alamb commented on code in PR #2549:
URL: https://github.com/apache/arrow-datafusion/pull/2549#discussion_r875910788


##########
datafusion/physical-expr/src/expressions/any.rs:
##########
@@ -0,0 +1,674 @@
+// 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.
+
+//! Any expression
+
+use std::any::Any;
+use std::sync::Arc;
+
+use arrow::array::{
+    BooleanArray, Int16Array, Int32Array, Int64Array, Int8Array, ListArray,
+    PrimitiveArray, UInt16Array, UInt32Array, UInt64Array, UInt8Array,
+};
+use arrow::datatypes::ArrowPrimitiveType;
+use arrow::{
+    datatypes::{DataType, Schema},
+    record_batch::RecordBatch,
+};
+
+use crate::expressions::try_cast;
+use crate::PhysicalExpr;
+use arrow::array::*;
+
+use datafusion_common::{DataFusionError, Result};
+use datafusion_expr::{ColumnarValue, Operator};
+
+macro_rules! compare_op_scalar {
+    ($LEFT: expr, $LIST_VALUES:expr, $OP:expr, $LIST_VALUES_TYPE:ty, $LIST_FROM_SCALAR: expr) => {{
+        let mut builder = BooleanBuilder::new($LEFT.len());
+
+        if $LIST_FROM_SCALAR {
+            for i in 0..$LEFT.len() {
+                if $LEFT.is_null(i) {
+                    builder.append_null()?;
+                } else {
+                    if $LIST_VALUES.is_null(0) {
+                        builder.append_null()?;
+                    } else {
+                        builder.append_value($OP(
+                            $LEFT.value(i),
+                            $LIST_VALUES
+                                .value(0)
+                                .as_any()
+                                .downcast_ref::<$LIST_VALUES_TYPE>()
+                                .unwrap(),
+                        ))?;
+                    }
+                }
+            }
+        } else {
+            for i in 0..$LEFT.len() {
+                if $LEFT.is_null(i) {
+                    builder.append_null()?;
+                } else {
+                    if $LIST_VALUES.is_null(i) {
+                        builder.append_null()?;
+                    } else {
+                        builder.append_value($OP(
+                            $LEFT.value(i),
+                            $LIST_VALUES
+                                .value(i)
+                                .as_any()
+                                .downcast_ref::<$LIST_VALUES_TYPE>()
+                                .unwrap(),
+                        ))?;
+                    }
+                }
+            }
+        }
+
+        Ok(builder.finish())
+    }};
+}
+
+macro_rules! make_primitive {
+    ($VALUES:expr, $IN_VALUES:expr, $NEGATED:expr, $TYPE:ident, $LIST_FROM_SCALAR: expr) => {{
+        let left = $VALUES.as_any().downcast_ref::<$TYPE>().expect(&format!(
+            "Unable to downcast values to {}",
+            stringify!($TYPE)
+        ));
+
+        if $NEGATED {
+            Ok(ColumnarValue::Array(Arc::new(neq_primitive(
+                left,
+                $IN_VALUES,
+                $LIST_FROM_SCALAR,
+            )?)))
+        } else {
+            Ok(ColumnarValue::Array(Arc::new(eq_primitive(
+                left,
+                $IN_VALUES,
+                $LIST_FROM_SCALAR,
+            )?)))
+        }
+    }};
+}
+
+fn eq_primitive<T: ArrowPrimitiveType>(
+    array: &PrimitiveArray<T>,
+    list: &ListArray,
+    list_from_scalar: bool,
+) -> Result<BooleanArray> {
+    compare_op_scalar!(
+        array,
+        list,
+        |x, v: &PrimitiveArray<T>| v.values().contains(&x),
+        PrimitiveArray<T>,
+        list_from_scalar
+    )
+}
+
+fn neq_primitive<T: ArrowPrimitiveType>(
+    array: &PrimitiveArray<T>,
+    list: &ListArray,
+    list_from_scalar: bool,
+) -> Result<BooleanArray> {
+    compare_op_scalar!(
+        array,
+        list,
+        |x, v: &PrimitiveArray<T>| !v.values().contains(&x),
+        PrimitiveArray<T>,
+        list_from_scalar
+    )
+}
+
+fn eq_bool(
+    array: &BooleanArray,
+    list: &ListArray,
+    list_from_scalar: bool,
+) -> Result<BooleanArray> {
+    compare_op_scalar!(
+        array,
+        list,
+        |x, v: &BooleanArray| unsafe {
+            for i in 0..v.len() {
+                if v.value_unchecked(i) == x {
+                    return true;
+                }
+            }
+
+            false
+        },
+        BooleanArray,
+        list_from_scalar
+    )
+}
+
+fn neq_bool(
+    array: &BooleanArray,
+    list: &ListArray,
+    list_from_scalar: bool,
+) -> Result<BooleanArray> {
+    compare_op_scalar!(
+        array,
+        list,
+        |x, v: &BooleanArray| unsafe {
+            for i in 0..v.len() {
+                if v.value_unchecked(i) == x {
+                    return false;
+                }
+            }
+
+            true
+        },
+        BooleanArray,
+        list_from_scalar
+    )
+}
+
+fn eq_utf8<OffsetSize: OffsetSizeTrait>(
+    array: &GenericStringArray<OffsetSize>,
+    list: &ListArray,
+    list_from_scalar: bool,
+) -> Result<BooleanArray> {
+    compare_op_scalar!(
+        array,
+        list,
+        |x, v: &GenericStringArray<OffsetSize>| unsafe {
+            for i in 0..v.len() {
+                if v.value_unchecked(i) == x {
+                    return true;
+                }
+            }
+
+            false
+        },
+        GenericStringArray<OffsetSize>,
+        list_from_scalar
+    )
+}
+
+fn neq_utf8<OffsetSize: OffsetSizeTrait>(
+    array: &GenericStringArray<OffsetSize>,
+    list: &ListArray,
+    list_from_scalar: bool,
+) -> Result<BooleanArray> {
+    compare_op_scalar!(
+        array,
+        list,
+        |x, v: &GenericStringArray<OffsetSize>| unsafe {
+            for i in 0..v.len() {
+                if v.value_unchecked(i) == x {
+                    return false;
+                }
+            }
+
+            true
+        },
+        GenericStringArray<OffsetSize>,
+        list_from_scalar
+    )
+}
+
+/// AnyExpr
+#[derive(Debug)]
+pub struct AnyExpr {
+    value: Arc<dyn PhysicalExpr>,
+    op: Operator,
+    list: Arc<dyn PhysicalExpr>,
+}
+
+impl AnyExpr {
+    /// Create a new Any expression
+    pub fn new(
+        value: Arc<dyn PhysicalExpr>,
+        op: Operator,
+        list: Arc<dyn PhysicalExpr>,
+    ) -> Self {
+        Self { value, op, list }
+    }
+
+    /// Compare for specific utf8 types
+    fn compare_utf8<T: OffsetSizeTrait>(
+        &self,
+        array: ArrayRef,
+        list: &ListArray,
+        negated: bool,
+        list_from_scalar: bool,
+    ) -> Result<ColumnarValue> {
+        let array = array
+            .as_any()
+            .downcast_ref::<GenericStringArray<T>>()
+            .unwrap();
+
+        if negated {
+            Ok(ColumnarValue::Array(Arc::new(neq_utf8(
+                array,
+                list,
+                list_from_scalar,
+            )?)))
+        } else {
+            Ok(ColumnarValue::Array(Arc::new(eq_utf8(
+                array,
+                list,
+                list_from_scalar,
+            )?)))
+        }
+    }
+
+    /// Get the left side of the binary expression
+    pub fn left(&self) -> &Arc<dyn PhysicalExpr> {
+        &self.value
+    }
+
+    /// Get the right side of the binary expression
+    pub fn right(&self) -> &Arc<dyn PhysicalExpr> {
+        &self.list
+    }
+
+    /// Get the operator for this binary expression
+    pub fn op(&self) -> &Operator {
+        &self.op
+    }
+
+    /// Compare for specific utf8 types
+    fn compare_bool(
+        &self,
+        array: ArrayRef,
+        list: &ListArray,
+        negated: bool,
+        list_from_scalar: bool,
+    ) -> Result<ColumnarValue> {
+        let array = array.as_any().downcast_ref::<BooleanArray>().unwrap();
+
+        if negated {
+            Ok(ColumnarValue::Array(Arc::new(neq_bool(
+                array,
+                list,
+                list_from_scalar,
+            )?)))
+        } else {
+            Ok(ColumnarValue::Array(Arc::new(eq_bool(
+                array,
+                list,
+                list_from_scalar,
+            )?)))
+        }
+    }
+}
+
+impl std::fmt::Display for AnyExpr {
+    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+        write!(f, "{} {} ANY({})", self.value, self.op, self.list)
+    }
+}
+
+impl PhysicalExpr for AnyExpr {
+    /// Return a reference to Any that can be used for downcasting
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
+        Ok(DataType::Boolean)
+    }
+
+    fn nullable(&self, input_schema: &Schema) -> Result<bool> {
+        self.value.nullable(input_schema)
+    }
+
+    fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
+        let value = match self.value.evaluate(batch)? {
+            ColumnarValue::Array(array) => array,
+            ColumnarValue::Scalar(scalar) => scalar.to_array(),
+        };

Review Comment:
   Thank you @ovr  -- this is looking quite cool.
   
   I haven't reviewed this code super carefully but I wonder what you think about reusing more of the code for `InList`?
   
   https://github.com/cube-js/arrow-datafusion/blob/binary-df-pr/datafusion/physical-expr/src/expressions/in_list.rs#L439
   
   It seems like the implementations of `x IN (<expr>, <expr>)` and `x  ANY (<expr>)` are almost exactly the same except for the fact that the the `x = ANY(<expr>)` has the list as a single `<expr>` ?
   
   The implementation of `get_set` needs to be different, but otherwise the rest of the code could probably be called directly.
   
   I mention this as it is likely the `IN` / `NOT IN` are more optimized (use a hashset for testing, for example) as well as already written. 
   
   Let me know what you think 



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org