drusso commented on a change in pull request #8222: URL: https://github.com/apache/arrow/pull/8222#discussion_r518991852
########## 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: Regarding the impact of d61ec97: I used the benchmarks in #8606 to compare 57893b415 vs. 57893b415+the following patch, and there was indeed no noticeable difference in the implementations 👍 ``` diff --git a/rust/datafusion/src/physical_plan/distinct_expressions.rs b/rust/datafusion/src/physical_plan/distinct_expressions.rs index c2183ca3b..d7745b0fa 100644 --- a/rust/datafusion/src/physical_plan/distinct_expressions.rs +++ b/rust/datafusion/src/physical_plan/distinct_expressions.rs @@ -23,6 +23,7 @@ use std::hash::Hash; use std::sync::Arc; use arrow::datatypes::{DataType, Field}; +use arrow::array::{ArrayRef, ListArray}; use fnv::FnvHashSet; @@ -123,29 +124,27 @@ impl Accumulator for DistinctCountAccumulator { } fn merge(&mut self, states: &Vec<ScalarValue>) -> Result<()> { - if states.len() == 0 { - return Ok(()); - } + self.update(states) + } - let col_values = states + fn merge_batch(&mut self, states: &Vec<ArrayRef>) -> Result<()> { + let list_arrays = states .iter() - .map(|state| match state { - ScalarValue::List(Some(values), _) => Ok(values), - _ => Err(DataFusionError::Internal( - "Unexpected accumulator state".to_string(), - )), + .map(|state_array| { + state_array.as_any().downcast_ref::<ListArray>().ok_or( + DataFusionError::Internal( + "Failed to downcast ListArray".to_string(), + ), + ) }) .collect::<Result<Vec<_>>>()?; - (0..col_values[0].len()) - .map(|row_index| { - let row_values = col_values - .iter() - .map(|col| col[row_index].clone()) - .collect::<Vec<_>>(); - self.update(&row_values) - }) - .collect::<Result<_>>() + let values_arrays = list_arrays + .iter() + .map(|list_array| list_array.values()) + .collect::<Vec<_>>(); + + self.update_batch(&values_arrays) } fn state(&self) -> Result<Vec<ScalarValue>> { ``` ---------------------------------------------------------------- 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: [email protected]
