rich7420 commented on code in PR #417:
URL: https://github.com/apache/datafusion-spark/pull/417#discussion_r4732626707


##########
crates/spark/src/function/predicate/at_least_n_non_nulls.rs:
##########
@@ -0,0 +1,524 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for 
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) 
under one or more contributor license agreements
+
+use std::fmt::{Display, Formatter};
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanArray, RecordBatch};
+use arrow::buffer::{BooleanBuffer, Buffer};
+use arrow::compute::cast;
+use arrow::datatypes::{DataType, Field, FieldRef, Float32Type, Float64Type, 
Schema};
+use datafusion_common::{Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, ExpressionPlacement};
+use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
+
+/// Spark's internal `AtLeastNNonNulls` predicate, used by `DataFrame.na.drop`.
+///
+/// Counts values that are neither NULL nor NaN, stopping evaluation of a row's
+/// children once `n` is reached. Non-positive thresholds return true without
+/// evaluating children. An unreachable positive threshold still evaluates 
every
+/// child. Empty batches evaluate no children.
+///
+/// Complex values use their outer validity: empty collections and non-null
+/// structs with null fields count as valid values. Only Float32 and Float64 
NaNs
+/// are excluded.
+///
+/// This predicate has no Spark SQL function name. Consumers construct it 
directly
+/// from already-planned, Spark-compatible children; it does not perform 
coercion.
+/// Callers must account for shared subexpressions hoisted out of this 
expression,
+/// which may require evaluation even on rows that have reached the threshold.
+///
+/// Children reporting Column or Literal placement are read for the entire 
batch.
+/// This fast path assumes those children only read existing values.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct SparkAtLeastNNonNullsExpr {
+    n: i32,
+    children: Vec<Arc<dyn PhysicalExpr>>,
+}
+
+impl SparkAtLeastNNonNullsExpr {
+    /// Construct a predicate with a fixed threshold and ordered children.
+    ///
+    /// # Example
+    ///
+    /// ```
+    /// use std::sync::Arc;
+    /// use arrow::array::{ArrayRef, BooleanArray, Float64Array, Int32Array};
+    /// use arrow::record_batch::RecordBatch;
+    /// use datafusion::physical_expr::expressions::Column;
+    /// use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
+    /// use 
datafusion_spark::function::predicate::at_least_n_non_nulls::SparkAtLeastNNonNullsExpr;
+    ///
+    /// let batch = RecordBatch::try_from_iter([
+    ///     ("a", Arc::new(Float64Array::from(vec![Some(f64::NAN), None, 
Some(1.0)])) as ArrayRef),
+    ///     ("b", Arc::new(Int32Array::from(vec![Some(2), None, Some(3)])) as 
ArrayRef),
+    /// ])?;
+    /// let expr = SparkAtLeastNNonNullsExpr::new(2, vec![
+    ///     Arc::new(Column::new("a", 0)),
+    ///     Arc::new(Column::new("b", 1)),
+    /// ]);
+    /// let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
+    /// assert_eq!(result.as_ref(), &BooleanArray::from(vec![false, false, 
true]));
+    /// # Ok::<(), datafusion_common::DataFusionError>(())
+    /// ```
+    pub fn new(n: i32, children: Vec<Arc<dyn PhysicalExpr>>) -> Self {
+        Self { n, children }
+    }
+}
+
+impl Display for SparkAtLeastNNonNullsExpr {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        write!(f, "atleastnnonnulls({}", self.n)?;
+        for child in &self.children {
+            write!(f, ", {child}")?;
+        }
+        write!(f, ")")
+    }
+}
+
+impl PhysicalExpr for SparkAtLeastNNonNullsExpr {
+    fn fmt_sql(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        write!(f, "atleastnnonnulls({}", self.n)?;
+        for child in &self.children {
+            write!(f, ", ")?;
+            child.fmt_sql(f)?;
+        }
+        write!(f, ")")
+    }
+
+    fn return_field(&self, _input_schema: &Schema) -> Result<FieldRef> {
+        Ok(Arc::new(Field::new(
+            "atleastnnonnulls",
+            DataType::Boolean,
+            false,
+        )))
+    }
+
+    fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
+        if self.n <= 0 {
+            return Ok(ColumnarValue::Scalar(ScalarValue::Boolean(Some(true))));
+        }
+        // The standard na.drop("all"/"any") cases reduce to bitmap OR/AND and 
do not
+        // need a per-row counter. For AND, still evaluate every child: Spark 
does not
+        // skip later expressions just because a row can no longer reach the 
threshold.
+        if self.n == 1 || self.n as usize == self.children.len() {
+            let all = self.n != 1;
+            let mut result = if all {
+                BooleanBuffer::new_set(batch.num_rows())
+            } else {
+                BooleanBuffer::new_unset(batch.num_rows())
+            };
+            for child in &self.children {
+                if batch.num_rows() == 0
+                    || (!all && result.count_set_bits() == batch.num_rows())
+                {
+                    break;
+                }
+                let value = if all
+                    || matches!(
+                        child.placement(),
+                        ExpressionPlacement::Column | 
ExpressionPlacement::Literal
+                    ) {
+                    child.evaluate(batch)?
+                } else {
+                    child.evaluate_selection(batch, 
&BooleanArray::new(!&result, None))?
+                };
+                let valid = valid_rows(value, batch.num_rows())?;
+                result = if all {
+                    &result & &valid
+                } else {
+                    &result | &valid
+                };
+            }
+            return Ok(ColumnarValue::Array(Arc::new(BooleanArray::new(
+                result, None,
+            ))));
+        }
+        // One bit plane per binary digit holds 64 row counts in each chunk.

Review Comment:
   I measured it with 8192 rows and `n` set to half the column count. Compared 
with a `Vec<u32>` updated from `valid.set_indices()`, the bit planes are 3 to 6 
times faster on Float64 columns and 9 to 20 times faster on strings. On a 
65-row batch the speedup is about 1.2 times. The table is in the PR description 
now.
   
   I also made the counter simpler in b4efef4. Counts start at `2^bits - n`, so 
the carry out of the top plane marks the rows that reached `n`.
   



-- 
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