andygrove commented on code in PR #3009:
URL: https://github.com/apache/arrow-datafusion/pull/3009#discussion_r937173972


##########
datafusion/physical-expr/src/aggregate/median.rs:
##########
@@ -0,0 +1,260 @@
+// 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.
+
+//! # Median
+
+use crate::expressions::format_state_name;
+use crate::{AggregateExpr, PhysicalExpr};
+use arrow::array::{
+    Array, ArrayRef, Float32Array, Float64Array, Int16Array, Int32Array, 
Int64Array,
+    Int8Array, PrimitiveArray, PrimitiveBuilder, UInt16Array, UInt32Array, 
UInt64Array,
+    UInt8Array,
+};
+use arrow::compute::sort;
+use arrow::datatypes::{ArrowPrimitiveType, DataType, Field};
+use datafusion_common::{DataFusionError, Result, ScalarValue};
+use datafusion_expr::{Accumulator, AggregateState};
+use std::any::Any;
+use std::sync::Arc;
+
+/// MEDIAN aggregate expression. This uses a lot of memory because all values 
need to be
+/// stored in memory before a result can be computed. If an approximation is 
sufficient
+/// then APPROX_MEDIAN provides a much more efficient solution.
+#[derive(Debug)]
+pub struct Median {
+    name: String,
+    expr: Arc<dyn PhysicalExpr>,
+    data_type: DataType,
+}
+
+impl Median {
+    /// Create a new MEDIAN aggregate function
+    pub fn new(
+        expr: Arc<dyn PhysicalExpr>,
+        name: impl Into<String>,
+        data_type: DataType,
+    ) -> Self {
+        Self {
+            name: name.into(),
+            expr,
+            data_type,
+        }
+    }
+}
+
+impl AggregateExpr for Median {
+    /// Return a reference to Any that can be used for downcasting
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn field(&self) -> Result<Field> {
+        Ok(Field::new(&self.name, self.data_type.clone(), true))
+    }
+
+    fn create_accumulator(&self) -> Result<Box<dyn Accumulator>> {
+        Ok(Box::new(MedianAccumulator {
+            data_type: self.data_type.clone(),
+            all_values: vec![],
+        }))
+    }
+
+    fn state_fields(&self) -> Result<Vec<Field>> {
+        Ok(vec![Field::new(
+            &format_state_name(&self.name, "median"),
+            self.data_type.clone(),
+            true,
+        )])
+    }
+
+    fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+        vec![self.expr.clone()]
+    }
+
+    fn name(&self) -> &str {
+        &self.name
+    }
+}
+
+#[derive(Debug)]
+struct MedianAccumulator {
+    data_type: DataType,
+    all_values: Vec<ArrayRef>,
+}
+
+macro_rules! median {
+    ($SELF:ident, $TY:ty, $SCALAR_TY:ident, $TWO:expr) => {{
+        let combined = combine_arrays::<$TY>($SELF.all_values.as_slice())?;
+        if combined.is_empty() {
+            return Ok(ScalarValue::Null);
+        }
+        let sorted = sort(&combined, None)?;
+        let array = sorted
+            .as_any()
+            .downcast_ref::<PrimitiveArray<$TY>>()
+            .ok_or(DataFusionError::Internal(
+                "median! macro failed to cast array to expected 
type".to_string(),
+            ))?;
+        let len = sorted.len();
+        let mid = len / 2;
+        if len % 2 == 0 {
+            Ok(ScalarValue::$SCALAR_TY(Some(
+                (array.value(mid - 1) + array.value(mid)) / $TWO,
+            )))
+        } else {
+            Ok(ScalarValue::$SCALAR_TY(Some(array.value(mid))))
+        }
+    }};
+}
+
+impl Accumulator for MedianAccumulator {
+    fn state(&self) -> Result<Vec<AggregateState>> {
+        let mut vec: Vec<AggregateState> = self
+            .all_values
+            .iter()
+            .map(|v| AggregateState::Array(v.clone()))
+            .collect();
+        if vec.is_empty() {
+            match self.data_type {

Review Comment:
   These arrays have length 0.  I just pushed a refactor to clean this up and 
make it more obvious.



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

Reply via email to