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 2021/06/27 11:41:36 UTC

[GitHub] [arrow-datafusion] alamb commented on a change in pull request #631: implement rank and dense_rank function and refactor built-in window function evaluation

alamb commented on a change in pull request #631:
URL: https://github.com/apache/arrow-datafusion/pull/631#discussion_r659306810



##########
File path: datafusion/src/physical_plan/expressions/rank.rs
##########
@@ -0,0 +1,172 @@
+// 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.
+
+//! Defines physical expressions that can evaluated at runtime during query execution

Review comment:
       ```suggestion
   //! Defines rank and dense_rank physical expressions that can evaluated at runtime during query execution
   ```

##########
File path: datafusion/src/physical_plan/expressions/rank.rs
##########
@@ -0,0 +1,172 @@
+// 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.
+
+//! Defines physical expressions that can evaluated at runtime during query execution
+
+use crate::error::Result;
+use crate::physical_plan::window_functions::PartitionEvaluator;
+use crate::physical_plan::{window_functions::BuiltInWindowFunctionExpr, PhysicalExpr};
+use arrow::array::ArrayRef;
+use arrow::array::UInt64Array;
+use arrow::datatypes::{DataType, Field};
+use arrow::record_batch::RecordBatch;
+use std::any::Any;
+use std::iter;
+use std::ops::Range;
+use std::sync::Arc;
+
+/// Rank calculates the rank in the window function with order by
+#[derive(Debug)]
+pub struct Rank {
+    name: String,
+    dense: bool,
+}
+
+/// Create a rank window function
+pub fn rank(name: String) -> Rank {
+    Rank { name, dense: false }
+}
+
+/// Create a dense rank window function
+pub fn dense_rank(name: String) -> Rank {
+    Rank { name, dense: true }
+}
+
+impl BuiltInWindowFunctionExpr for Rank {
+    /// Return a reference to Any that can be used for downcasting
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn field(&self) -> Result<Field> {
+        let nullable = false;
+        let data_type = DataType::UInt64;
+        Ok(Field::new(self.name(), data_type, nullable))
+    }
+
+    fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+        vec![]
+    }
+
+    fn name(&self) -> &str {
+        &self.name
+    }
+
+    fn create_evaluator(
+        &self,
+        _batch: &RecordBatch,
+    ) -> Result<Box<dyn PartitionEvaluator>> {
+        Ok(Box::new(RankEvaluator { dense: self.dense }))
+    }
+}
+
+pub(crate) struct RankEvaluator {
+    dense: bool,
+}
+
+impl PartitionEvaluator for RankEvaluator {
+    fn include_rank(&self) -> bool {
+        true
+    }
+
+    fn evaluate_partition(&self, _partition: Range<usize>) -> Result<ArrayRef> {
+        unreachable!("rank evaluation must be called with evaluate_partition_with_rank")
+    }
+
+    fn evaluate_partition_with_rank(
+        &self,
+        _partition: Range<usize>,
+        ranks_in_partition: &[Range<usize>],
+    ) -> Result<ArrayRef> {
+        let result = if self.dense {
+            UInt64Array::from_iter_values(ranks_in_partition.iter().enumerate().flat_map(
+                |(index, range)| {
+                    let len = range.end - range.start;
+                    iter::repeat((index as u64) + 1).take(len)

Review comment:
       👨‍🍳 ❤️  -- nice

##########
File path: datafusion/src/physical_plan/expressions/nth_value.rs
##########
@@ -111,25 +114,33 @@ impl BuiltInWindowFunctionExpr for NthValue {
         &self.name
     }
 
-    fn evaluate(&self, num_rows: usize, values: &[ArrayRef]) -> Result<ArrayRef> {
-        if values.is_empty() {
-            return Err(DataFusionError::Execution(format!(
-                "No arguments supplied to {}",
-                self.name()
-            )));
-        }
-        let value = &values[0];
-        if value.len() != num_rows {
-            return Err(DataFusionError::Execution(format!(
-                "Invalid data supplied to {}, expect {} rows, got {} rows",
-                self.name(),
-                num_rows,
-                value.len()
-            )));
-        }
-        if num_rows == 0 {
-            return Ok(new_empty_array(value.data_type()));
-        }
+    fn create_evaluator(
+        &self,
+        batch: &RecordBatch,
+    ) -> Result<Box<dyn PartitionEvaluator>> {
+        let values = self
+            .expressions()
+            .iter()
+            .map(|e| e.evaluate(batch))
+            .map(|r| r.map(|v| v.into_array(batch.num_rows())))
+            .collect::<Result<Vec<_>>>()?;
+        Ok(Box::new(NthValueEvaluator {
+            kind: self.kind,
+            values,
+        }))
+    }
+}
+
+pub(crate) struct NthValueEvaluator {
+    kind: NthValueKind,
+    values: Vec<ArrayRef>,
+}
+
+impl PartitionEvaluator for NthValueEvaluator {
+    fn evaluate_partition(&self, partition: Range<usize>) -> Result<ArrayRef> {

Review comment:
       This interface makes sense (to pass in the range of rows), though it may make more sense to explicitly pass in `values: Vec<ArrayRef>` rather than assume whatever implements the Evaluator was constructed in a way they can be found

##########
File path: datafusion/src/physical_plan/window_functions.rs
##########
@@ -208,11 +210,57 @@ pub(super) fn signature_for_built_in(fun: &BuiltInWindowFunction) -> Signature {
     }
 }
 
+/// Partition evaluator
+pub(crate) trait PartitionEvaluator {
+    /// Whether the evaluator should be evaluated with rank
+    fn include_rank(&self) -> bool {
+        false
+    }
+
+    /// evaluate the partition evaluator against the partitions
+    fn evaluate(&self, partition_points: Vec<Range<usize>>) -> Result<Vec<ArrayRef>> {
+        partition_points
+            .into_iter()
+            .map(|partition| self.evaluate_partition(partition))
+            .collect()
+    }
+
+    /// evaluate the partition evaluator against the partitions with rank information
+    fn evaluate_with_rank(
+        &self,
+        partition_points: Vec<Range<usize>>,
+        sort_partition_points: Vec<Range<usize>>,
+    ) -> Result<Vec<ArrayRef>> {
+        partition_points
+            .into_iter()
+            .map(|partition| {
+                let ranks_in_partition =
+                    find_ranges_in_range(&partition, &sort_partition_points);
+                self.evaluate_partition_with_rank(partition, ranks_in_partition)
+            })
+            .collect()
+    }
+
+    /// evaluate the partition evaluator against the partition
+    fn evaluate_partition(&self, _partition: Range<usize>) -> Result<ArrayRef>;

Review comment:
       Another potential way to model this with a single evaluate function might be:
   
   ```suggestion
       fn evaluate_partition(&self, _partition: Range<usize>, _ranks_in_partition: Option<&[Range<usize>])) -> Result<ArrayRef>;
   ```
   
   Rather than having two separate functions with different signatures




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