drusso commented on a change in pull request #8222:
URL: https://github.com/apache/arrow/pull/8222#discussion_r501684962



##########
File path: rust/datafusion/src/physical_plan/distinct_expressions.rs
##########
@@ -0,0 +1,203 @@
+// 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.
+
+//! Implementations for DISTINCT expressions, e.g. `COUNT(DISTINCT c)`
+
+use std::cell::RefCell;
+use std::convert::TryFrom;
+use std::fmt::Debug;
+use std::hash::Hash;
+use std::rc::Rc;
+use std::sync::Arc;
+
+use arrow::array::ArrayRef;
+use arrow::array::ListArray;
+use arrow::datatypes::{DataType, Field};
+
+use fnv::FnvHashSet;
+
+use crate::error::{ExecutionError, Result};
+use crate::physical_plan::group_scalar::GroupByScalar;
+use crate::physical_plan::{Accumulator, AggregateExpr, PhysicalExpr};
+use crate::scalar::ScalarValue;
+
+#[derive(Debug, PartialEq, Eq, Hash, Clone)]
+struct DistinctScalarValues(Vec<GroupByScalar>);
+
+fn format_state_name(name: &str, state_name: &str) -> String {
+    format!("{}[{}]", name, state_name)
+}
+
+/// Expression for a COUNT(DISTINCT) aggregation.
+#[derive(Debug)]
+pub struct DistinctCount {
+    /// Column name
+    name: String,
+    /// The DataType for the final count
+    data_type: DataType,
+    /// The DataType for each input argument
+    input_data_types: Vec<DataType>,
+    /// The input arguments
+    exprs: Vec<Arc<dyn PhysicalExpr>>,
+}
+
+impl DistinctCount {
+    /// Create a new COUNT(DISTINCT) aggregate function.
+    pub fn new(
+        input_data_types: Vec<DataType>,
+        exprs: Vec<Arc<dyn PhysicalExpr>>,
+        name: String,
+        data_type: DataType,
+    ) -> Self {
+        Self {
+            input_data_types,
+            exprs,
+            name,
+            data_type,
+        }
+    }
+}
+
+impl AggregateExpr for DistinctCount {
+    fn field(&self) -> Result<Field> {
+        Ok(Field::new(&self.name, self.data_type.clone(), false))
+    }
+
+    fn state_fields(&self) -> Result<Vec<Field>> {
+        Ok(self
+            .input_data_types
+            .iter()
+            .map(|data_type| {
+                Field::new(
+                    &format_state_name(&self.name, "count distinct"),
+                    DataType::List(Box::new(data_type.clone())),
+                    false,
+                )
+            })
+            .collect::<Vec<_>>())
+    }
+
+    fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+        self.exprs.clone()
+    }
+
+    fn create_accumulator(&self) -> Result<Rc<RefCell<dyn Accumulator>>> {
+        Ok(Rc::new(RefCell::new(DistinctCountAccumulator {
+            values: FnvHashSet::default(),
+            data_types: self.input_data_types.clone(),
+            count_data_type: self.data_type.clone(),
+        })))
+    }
+}
+
+#[derive(Debug)]
+struct DistinctCountAccumulator {
+    values: FnvHashSet<DistinctScalarValues>,
+    data_types: Vec<DataType>,
+    count_data_type: DataType,
+}
+
+impl Accumulator for DistinctCountAccumulator {
+    fn update_batch(&mut self, arrays: &Vec<ArrayRef>) -> Result<()> {

Review comment:
       I made the switch (see d61ec97). For now I think the DRY approach makes 
sense, and as a follow-up I can explore how the different options perform. I 
can use 
[benches/aggregate_query_sql.rs](https://github.com/apache/arrow/blob/master/rust/datafusion/benches/aggregate_query_sql.rs)
 as a starting point for the comparisons, if that makes sense?

##########
File path: rust/datafusion/src/test/mod.rs
##########
@@ -135,6 +135,13 @@ pub fn format_batch(batch: &RecordBatch) -> Vec<String> {
             }
             let array = batch.column(column_index);
             match array.data_type() {
+                DataType::Utf8 => s.push_str(
+                    array
+                        .as_any()
+                        .downcast_ref::<array::StringArray>()
+                        .unwrap()
+                        .value(row_index),
+                ),

Review comment:
       No problem! 
   
   This makes perfect sense, and I added the test (2d0999a). However, I also 
had to make the `count(distinct)` field nullable (4cdb951), otherwise I ran 
into an assertion error 
[here](https://github.com/apache/arrow/blob/2d0999ac7f1d01a4fe392add53720ceeb6b0b1f3/rust/datafusion/tests/sql.rs#L652)
 due to a mismatch of the field's nullability between the logical plan and 
physical plan. 
   
   The logical plan nullability is set 
[here](https://github.com/apache/arrow/blob/2d0999ac7f1d01a4fe392add53720ceeb6b0b1f3/rust/datafusion/src/logical_plan/mod.rs#L298),
 and is always nullable. All of the regular aggregate expressions mark their 
field as nullable, for example, 
[here](https://github.com/apache/arrow/blob/2d0999ac7f1d01a4fe392add53720ceeb6b0b1f3/rust/datafusion/src/physical_plan/expressions.rs#L846)
 for the regular `Count`. 
   
   I might be mistaken, but I think regular and distinct counts should be 
non-nullable? In any case, I went with making `count(distinct)` nullable for 
consistency with `count()`. Perhaps there's a follow-up here?
   
   

##########
File path: rust/datafusion/src/physical_plan/aggregates.rs
##########
@@ -124,14 +126,30 @@ pub fn create_aggregate_expr(
 
     let return_type = return_type(&fun, &arg_types)?;
 
-    Ok(match fun {
-        AggregateFunction::Count => {
+    Ok(match (fun, distinct) {
+        (AggregateFunction::Count, false) => {
             Arc::new(expressions::Count::new(arg, name, return_type))
         }
-        AggregateFunction::Sum => Arc::new(expressions::Sum::new(arg, name, 
return_type)),
-        AggregateFunction::Min => Arc::new(expressions::Min::new(arg, name, 
return_type)),
-        AggregateFunction::Max => Arc::new(expressions::Max::new(arg, name, 
return_type)),
-        AggregateFunction::Avg => Arc::new(expressions::Avg::new(arg, name, 
return_type)),
+        (AggregateFunction::Count, true) => {
+            Arc::new(distinct_expressions::DistinctCount::new(
+                arg_types,
+                args.clone(),
+                name,
+                return_type,
+            ))
+        }
+        (AggregateFunction::Sum, _) => {

Review comment:
       I made the change, see 7f073f7. 




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

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


Reply via email to