[GitHub] [arrow] drusso commented on a change in pull request #8222: ARROW-10043: [Rust][DataFusion] Implement COUNT(DISTINCT col)

2020-11-06 Thread GitBox


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);
+
+fn format_state_name(name: , state_name: ) -> 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,
+/// The input arguments
+exprs: Vec>,
+}
+
+impl DistinctCount {
+/// Create a new COUNT(DISTINCT) aggregate function.
+pub fn new(
+input_data_types: Vec,
+exprs: Vec>,
+name: String,
+data_type: DataType,
+) -> Self {
+Self {
+input_data_types,
+exprs,
+name,
+data_type,
+}
+}
+}
+
+impl AggregateExpr for DistinctCount {
+fn field() -> Result {
+Ok(Field::new(, self.data_type.clone(), false))
+}
+
+fn state_fields() -> Result> {
+Ok(self
+.input_data_types
+.iter()
+.map(|data_type| {
+Field::new(
+_state_name(, "count distinct"),
+DataType::List(Box::new(data_type.clone())),
+false,
+)
+})
+.collect::>())
+}
+
+fn expressions() -> Vec> {
+self.exprs.clone()
+}
+
+fn create_accumulator() -> Result>> {
+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,
+data_types: Vec,
+count_data_type: DataType,
+}
+
+impl Accumulator for DistinctCountAccumulator {
+fn update_batch( self, arrays: ) -> 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( self, states: ) -> Result<()> {
   -if states.len() == 0 {
   -return Ok(());
   -}
   +self.update(states)
   +}

   -let col_values = states
   +fn merge_batch( self, states: ) -> Result<()> {
   +let list_arrays = states
.iter()
   -.map(|state| match state {
   -ScalarValue::List(Some(values), _) => Ok(values),
   -_ => Err(DataFusionError::Internal(
   -"Unexpected accumulator state".to_string(),
   -)),

[GitHub] [arrow] drusso commented on a change in pull request #8222: ARROW-10043: [Rust][DataFusion] Implement COUNT(DISTINCT col)

2020-10-09 Thread GitBox


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);
+
+fn format_state_name(name: , state_name: ) -> 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,
+/// The input arguments
+exprs: Vec>,
+}
+
+impl DistinctCount {
+/// Create a new COUNT(DISTINCT) aggregate function.
+pub fn new(
+input_data_types: Vec,
+exprs: Vec>,
+name: String,
+data_type: DataType,
+) -> Self {
+Self {
+input_data_types,
+exprs,
+name,
+data_type,
+}
+}
+}
+
+impl AggregateExpr for DistinctCount {
+fn field() -> Result {
+Ok(Field::new(, self.data_type.clone(), false))
+}
+
+fn state_fields() -> Result> {
+Ok(self
+.input_data_types
+.iter()
+.map(|data_type| {
+Field::new(
+_state_name(, "count distinct"),
+DataType::List(Box::new(data_type.clone())),
+false,
+)
+})
+.collect::>())
+}
+
+fn expressions() -> Vec> {
+self.exprs.clone()
+}
+
+fn create_accumulator() -> Result>> {
+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,
+data_types: Vec,
+count_data_type: DataType,
+}
+
+impl Accumulator for DistinctCountAccumulator {
+fn update_batch( self, arrays: ) -> 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: ) -> Vec {
 }
 let array = batch.column(column_index);
 match array.data_type() {
+DataType::Utf8 => s.push_str(
+array
+.as_any()
+.downcast_ref::()
+.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 

[GitHub] [arrow] drusso commented on a change in pull request #8222: ARROW-10043: [Rust][DataFusion] Implement COUNT(DISTINCT col)

2020-10-08 Thread GitBox


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



##
File path: rust/datafusion/src/physical_plan/aggregates.rs
##
@@ -124,14 +126,30 @@ pub fn create_aggregate_expr(
 
 let return_type = return_type(, _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




[GitHub] [arrow] drusso commented on a change in pull request #8222: ARROW-10043: [Rust][DataFusion] Implement COUNT(DISTINCT col)

2020-10-08 Thread GitBox


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



##
File path: rust/datafusion/src/test/mod.rs
##
@@ -135,6 +135,13 @@ pub fn format_batch(batch: ) -> Vec {
 }
 let array = batch.column(column_index);
 match array.data_type() {
+DataType::Utf8 => s.push_str(
+array
+.as_any()
+.downcast_ref::()
+.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?
   
   





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




[GitHub] [arrow] drusso commented on a change in pull request #8222: ARROW-10043: [Rust][DataFusion] Implement COUNT(DISTINCT col)

2020-10-08 Thread GitBox


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);
+
+fn format_state_name(name: , state_name: ) -> 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,
+/// The input arguments
+exprs: Vec>,
+}
+
+impl DistinctCount {
+/// Create a new COUNT(DISTINCT) aggregate function.
+pub fn new(
+input_data_types: Vec,
+exprs: Vec>,
+name: String,
+data_type: DataType,
+) -> Self {
+Self {
+input_data_types,
+exprs,
+name,
+data_type,
+}
+}
+}
+
+impl AggregateExpr for DistinctCount {
+fn field() -> Result {
+Ok(Field::new(, self.data_type.clone(), false))
+}
+
+fn state_fields() -> Result> {
+Ok(self
+.input_data_types
+.iter()
+.map(|data_type| {
+Field::new(
+_state_name(, "count distinct"),
+DataType::List(Box::new(data_type.clone())),
+false,
+)
+})
+.collect::>())
+}
+
+fn expressions() -> Vec> {
+self.exprs.clone()
+}
+
+fn create_accumulator() -> Result>> {
+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,
+data_types: Vec,
+count_data_type: DataType,
+}
+
+impl Accumulator for DistinctCountAccumulator {
+fn update_batch( self, arrays: ) -> 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?





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




[GitHub] [arrow] drusso commented on a change in pull request #8222: ARROW-10043: [Rust][DataFusion] Implement COUNT(DISTINCT col)

2020-10-07 Thread GitBox


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



##
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);
+
+fn format_state_name(name: , state_name: ) -> 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,
+/// The input arguments
+exprs: Vec>,
+}
+
+impl DistinctCount {
+/// Create a new COUNT(DISTINCT) aggregate function.
+pub fn new(
+input_data_types: Vec,
+exprs: Vec>,
+name: String,
+data_type: DataType,
+) -> Self {
+Self {
+input_data_types,
+exprs,
+name,
+data_type,
+}
+}
+}
+
+impl AggregateExpr for DistinctCount {
+fn field() -> Result {
+Ok(Field::new(, self.data_type.clone(), false))
+}
+
+fn state_fields() -> Result> {
+Ok(self
+.input_data_types
+.iter()
+.map(|data_type| {
+Field::new(
+_state_name(, "count distinct"),
+DataType::List(Box::new(data_type.clone())),
+false,
+)
+})
+.collect::>())
+}
+
+fn expressions() -> Vec> {
+self.exprs.clone()
+}
+
+fn create_accumulator() -> Result>> {
+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,
+data_types: Vec,
+count_data_type: DataType,
+}
+
+impl Accumulator for DistinctCountAccumulator {
+fn update_batch( self, arrays: ) -> Result<()> {

Review comment:
   The `update_batch()` were actually equivalent, removed it. See 3c87e89.
   
   There's also a way to remove the specialized `merge_batch()` implementation 
if `merge()` is implemented as:
   
   ```rust
   fn merge( self, states: ) -> Result<()> {
   if states.len() == 0 {
   return Ok(());
   }
   
   let col_values = states
   .iter()
   .map(|state| match state {
   ScalarValue::List(Some(values), _) => Ok(values),
   _ => Err(ExecutionError::InternalError(
   "Unexpected accumulator state".to_string(),
   )),
   })
   .collect::>>()?;
   
   (0..col_values[0].len())
   .map(|row_index| {
   let row_values = col_values
   .iter()
   .map(|col| col[row_index].clone())
   .collect::>();
   self.update(_values)
   })
   .collect::>()
   }
   ```
   
   I think that works out well. I don't have any preference one way or the 
other, should I make the swap? 





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

[GitHub] [arrow] drusso commented on a change in pull request #8222: ARROW-10043: [Rust][DataFusion] Implement COUNT(DISTINCT col)

2020-10-07 Thread GitBox


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



##
File path: rust/datafusion/src/physical_plan/group_scalar.rs
##
@@ -0,0 +1,133 @@
+// 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 scalars used to construct groups, ex. in GROUP BY clauses.
+
+use std::convert::{From, TryFrom};
+
+use crate::error::{ExecutionError, Result};
+use crate::scalar::ScalarValue;
+
+/// Enumeration of types that can be used in a GROUP BY expression (all 
primitives except
+/// for floating point numerics)
+#[derive(Debug, PartialEq, Eq, Hash, Clone)]
+pub(crate) enum GroupByScalar {
+UInt8(u8),
+UInt16(u16),
+UInt32(u32),
+UInt64(u64),
+Int8(i8),
+Int16(i16),
+Int32(i32),
+Int64(i64),
+Utf8(String),
+}
+
+impl TryFrom<> for GroupByScalar {
+type Error = ExecutionError;
+
+fn try_from(scalar_value: ) -> Result {
+Ok(match scalar_value {
+ScalarValue::Int8(Some(v)) => GroupByScalar::Int8(*v),
+ScalarValue::Int16(Some(v)) => GroupByScalar::Int16(*v),
+ScalarValue::Int32(Some(v)) => GroupByScalar::Int32(*v),
+ScalarValue::Int64(Some(v)) => GroupByScalar::Int64(*v),
+ScalarValue::UInt8(Some(v)) => GroupByScalar::UInt8(*v),
+ScalarValue::UInt16(Some(v)) => GroupByScalar::UInt16(*v),
+ScalarValue::UInt32(Some(v)) => GroupByScalar::UInt32(*v),
+ScalarValue::UInt64(Some(v)) => GroupByScalar::UInt64(*v),
+ScalarValue::Utf8(Some(v)) => GroupByScalar::Utf8(v.clone()),
+ScalarValue::Int8(None)
+| ScalarValue::Int16(None)
+| ScalarValue::Int32(None)
+| ScalarValue::Int64(None)
+| ScalarValue::UInt8(None)
+| ScalarValue::UInt16(None)
+| ScalarValue::UInt32(None)
+| ScalarValue::UInt64(None)
+| ScalarValue::Utf8(None) => {
+return Err(ExecutionError::InternalError(format!(
+"Cannot convert a ScalarValue holding NULL ({:?})",
+scalar_value
+)));
+}
+v => {
+return Err(ExecutionError::InternalError(format!(
+"Cannot convert a ScalarValue with associated DataType 
{:?}",
+v.get_datatype()
+)))
+}
+})
+}
+}
+
+impl From<> for ScalarValue {
+fn from(group_by_scalar: ) -> Self {
+match group_by_scalar {
+GroupByScalar::Int8(v) => ScalarValue::Int8(Some(*v)),
+GroupByScalar::Int16(v) => ScalarValue::Int16(Some(*v)),
+GroupByScalar::Int32(v) => ScalarValue::Int32(Some(*v)),
+GroupByScalar::Int64(v) => ScalarValue::Int64(Some(*v)),
+GroupByScalar::UInt8(v) => ScalarValue::UInt8(Some(*v)),
+GroupByScalar::UInt16(v) => ScalarValue::UInt16(Some(*v)),
+GroupByScalar::UInt32(v) => ScalarValue::UInt32(Some(*v)),
+GroupByScalar::UInt64(v) => ScalarValue::UInt64(Some(*v)),
+GroupByScalar::Utf8(v) => ScalarValue::Utf8(Some(v.clone())),
+}
+}
+}
+
+mod tests {
+use super::*;

Review comment:
   These are flagged as unused imports, will fix. 





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




[GitHub] [arrow] drusso commented on a change in pull request #8222: ARROW-10043: [Rust][DataFusion] Implement COUNT(DISTINCT col)

2020-10-07 Thread GitBox


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



##
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);
+
+fn format_state_name(name: , state_name: ) -> 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,
+/// The input arguments
+exprs: Vec>,
+}
+
+impl DistinctCount {
+/// Create a new COUNT(DISTINCT) aggregate function.
+pub fn new(
+input_data_types: Vec,
+exprs: Vec>,
+name: String,
+data_type: DataType,
+) -> Self {
+Self {
+input_data_types,
+exprs,
+name,
+data_type,
+}
+}
+}
+
+impl AggregateExpr for DistinctCount {
+fn field() -> Result {
+Ok(Field::new(, self.data_type.clone(), false))
+}
+
+fn state_fields() -> Result> {
+Ok(self
+.input_data_types
+.iter()
+.map(|data_type| {
+Field::new(
+_state_name(, "count distinct"),
+DataType::List(Box::new(data_type.clone())),
+false,
+)
+})
+.collect::>())
+}
+
+fn expressions() -> Vec> {
+self.exprs.clone()
+}
+
+fn create_accumulator() -> Result>> {
+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,
+data_types: Vec,
+count_data_type: DataType,
+}
+
+impl Accumulator for DistinctCountAccumulator {
+fn update_batch( self, arrays: ) -> Result<()> {
+for row in 0..arrays[0].len() {
+let row_values = arrays
+.iter()
+.map(|array| ScalarValue::try_from_array(array, row))
+.collect::>>()?;
+
+self.update(_values)?;
+}
+
+Ok(())
+}
+
+fn update( self, values: ) -> Result<()> {
+// If a row has a NULL, it is not included in the final count.
+if !values.iter().any(|v| v.is_null()) {
+self.values.insert(DistinctScalarValues(
+values
+.iter()
+.map(GroupByScalar::try_from)
+.collect::>>()?,
+));
+}
+
+Ok(())
+}
+
+fn merge( self, states: ) -> Result<()> {
+self.update(states)
+}
+
+fn merge_batch( self, states: ) -> Result<()> {
+let list_arrays = states
+.iter()
+.map(|state_array| {
+state_array.as_any().downcast_ref::().ok_or(
+ExecutionError::InternalError(
+"Failed to downcast ListArray".to_string(),
+),
+)
+})
+.collect::>>()?;
+
+let values_arrays = list_arrays
+.iter()
+.map(|list_array| list_array.values())
+.collect::>();
+
+self.update_batch(_arrays)
+}
+
+fn state() -> 

[GitHub] [arrow] drusso commented on a change in pull request #8222: ARROW-10043: [Rust][DataFusion] Implement COUNT(DISTINCT col)

2020-10-07 Thread GitBox


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



##
File path: rust/datafusion/src/physical_plan/aggregates.rs
##
@@ -124,14 +126,30 @@ pub fn create_aggregate_expr(
 
 let return_type = return_type(, _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:
   Sounds good, and I will do the same for `Avg`. I will leave `Min` and 
`Max` as `_` since the `distinct` flag shouldn't have any effect on these 
aggregations.
   
   The only change in behaviour to highlight would be that existing queries 
that happen to include a `sum(distinct)` or `avg(distinct)` would start to 
fail, rather than be handled implicitly as a plain `sum()` or `avg()`, but I 
believe this would be a non-issue. 





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




[GitHub] [arrow] drusso commented on a change in pull request #8222: ARROW-10043: [Rust][DataFusion] Implement COUNT(DISTINCT col)

2020-10-07 Thread GitBox


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



##
File path: rust/datafusion/src/physical_plan/group_scalar.rs
##
@@ -0,0 +1,77 @@
+// 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 scalars used to construct groups, ex. in GROUP BY clauses.
+
+use std::convert::{From, TryFrom};
+
+use crate::error::{ExecutionError, Result};
+use crate::scalar::ScalarValue;
+
+/// Enumeration of types that can be used in a GROUP BY expression (all 
primitives except
+/// for floating point numerics)
+#[derive(Debug, PartialEq, Eq, Hash, Clone)]
+pub(crate) enum GroupByScalar {
+UInt8(u8),
+UInt16(u16),
+UInt32(u32),
+UInt64(u64),
+Int8(i8),
+Int16(i16),
+Int32(i32),
+Int64(i64),
+Utf8(String),
+}
+
+impl TryFrom<> for GroupByScalar {
+type Error = ExecutionError;
+
+fn try_from(scalar_value: ) -> Result {
+Ok(match scalar_value {
+ScalarValue::Int8(Some(v)) => GroupByScalar::Int8(*v),
+ScalarValue::Int16(Some(v)) => GroupByScalar::Int16(*v),
+ScalarValue::Int32(Some(v)) => GroupByScalar::Int32(*v),
+ScalarValue::Int64(Some(v)) => GroupByScalar::Int64(*v),
+ScalarValue::UInt8(Some(v)) => GroupByScalar::UInt8(*v),
+ScalarValue::UInt16(Some(v)) => GroupByScalar::UInt16(*v),
+ScalarValue::UInt32(Some(v)) => GroupByScalar::UInt32(*v),
+ScalarValue::UInt64(Some(v)) => GroupByScalar::UInt64(*v),
+ScalarValue::Utf8(Some(v)) => GroupByScalar::Utf8(v.clone()),
+_ => {
+return Err(ExecutionError::InternalError(
+"Cannot convert ScalarValue to GroupByScalar".to_string(),

Review comment:
   See 0b45657. I also improved the error messages a bit when the 
conversion is attempted with a `ScalarValue` holding `None`. 





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




[GitHub] [arrow] drusso commented on a change in pull request #8222: ARROW-10043: [Rust][DataFusion] Implement COUNT(DISTINCT col)

2020-10-07 Thread GitBox


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



##
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);
+
+fn format_state_name(name: , state_name: ) -> 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,
+/// The input arguments
+exprs: Vec>,
+}
+
+impl DistinctCount {
+/// Create a new COUNT(DISTINCT) aggregate function.
+pub fn new(
+input_data_types: Vec,
+exprs: Vec>,
+name: String,
+data_type: DataType,
+) -> Self {
+Self {
+input_data_types,
+exprs,
+name,
+data_type,
+}
+}
+}
+
+impl AggregateExpr for DistinctCount {
+fn field() -> Result {
+Ok(Field::new(, self.data_type.clone(), false))
+}
+
+fn state_fields() -> Result> {
+Ok(self
+.input_data_types
+.iter()
+.map(|data_type| {
+Field::new(
+_state_name(, "count distinct"),
+DataType::List(Box::new(data_type.clone())),
+false,
+)
+})
+.collect::>())
+}
+
+fn expressions() -> Vec> {
+self.exprs.clone()
+}
+
+fn create_accumulator() -> Result>> {
+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,
+data_types: Vec,
+count_data_type: DataType,
+}
+
+impl Accumulator for DistinctCountAccumulator {
+fn update_batch( self, arrays: ) -> Result<()> {
+for row in 0..arrays[0].len() {
+let row_values = arrays
+.iter()
+.map(|array| ScalarValue::try_from_array(array, row))
+.collect::>>()?;
+
+self.update(_values)?;
+}
+
+Ok(())
+}
+
+fn update( self, values: ) -> Result<()> {
+// If a row has a NULL, it is not included in the final count.
+if !values.iter().any(|v| v.is_null()) {
+self.values.insert(DistinctScalarValues(
+values
+.iter()
+.map(GroupByScalar::try_from)
+.collect::>>()?,
+));
+}
+
+Ok(())
+}
+
+fn merge( self, states: ) -> Result<()> {
+self.update(states)
+}
+
+fn merge_batch( self, states: ) -> Result<()> {
+let list_arrays = states
+.iter()
+.map(|state_array| {
+state_array.as_any().downcast_ref::().ok_or(
+ExecutionError::InternalError(
+"Failed to downcast ListArray".to_string(),
+),
+)
+})
+.collect::>>()?;
+
+let values_arrays = list_arrays
+.iter()
+.map(|list_array| list_array.values())
+.collect::>();
+
+self.update_batch(_arrays)
+}
+
+fn state() -> 

[GitHub] [arrow] drusso commented on a change in pull request #8222: ARROW-10043: [Rust][DataFusion] Implement COUNT(DISTINCT col)

2020-09-22 Thread GitBox


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



##
File path: rust/datafusion/src/physical_plan/distinct_expressions.rs
##
@@ -0,0 +1,303 @@
+// 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::fmt::Debug;
+use std::hash::Hash;
+use std::rc::Rc;
+use std::sync::Arc;
+
+use arrow::array::ArrayRef;
+use arrow::array::{
+Int16Array, Int32Array, Int64Array, Int8Array, PrimitiveArrayOps, 
UInt16Array,
+UInt32Array, UInt64Array, UInt8Array,
+};
+use arrow::datatypes::{DataType, Schema};
+use arrow::record_batch::RecordBatch;
+
+use fnv::FnvHashSet;
+
+use crate::error::{ExecutionError, Result};
+use crate::logical_plan::ScalarValue;
+use crate::physical_plan::expressions::Column;
+use crate::physical_plan::hash_aggregate::AggregateMode;
+use crate::physical_plan::{Accumulator, AggregateExpr, PhysicalExpr};
+
+/// Enumeration of types that can be accumulated into a distinct set of values.
+#[derive(Debug, PartialEq, Eq, Hash, Clone)]
+enum DistinctScalarValue {

Review comment:
   These are used as the values in the iterator's `HashSet`, and 
unfortunately it's not possible to derive `Hash` for `ScalarValue` since it 
nests `f32` and `f64`. 
   
   As you suggested, `GroupByScalar` is a good candidate here. (I assumed you 
meant `GroupByScalar` rather than `GroupByKey`?)

##
File path: rust/datafusion/src/physical_plan/distinct_expressions.rs
##
@@ -0,0 +1,303 @@
+// 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::fmt::Debug;
+use std::hash::Hash;
+use std::rc::Rc;
+use std::sync::Arc;
+
+use arrow::array::ArrayRef;
+use arrow::array::{
+Int16Array, Int32Array, Int64Array, Int8Array, PrimitiveArrayOps, 
UInt16Array,
+UInt32Array, UInt64Array, UInt8Array,
+};
+use arrow::datatypes::{DataType, Schema};
+use arrow::record_batch::RecordBatch;
+
+use fnv::FnvHashSet;
+
+use crate::error::{ExecutionError, Result};
+use crate::logical_plan::ScalarValue;
+use crate::physical_plan::expressions::Column;
+use crate::physical_plan::hash_aggregate::AggregateMode;
+use crate::physical_plan::{Accumulator, AggregateExpr, PhysicalExpr};
+
+/// Enumeration of types that can be accumulated into a distinct set of values.
+#[derive(Debug, PartialEq, Eq, Hash, Clone)]
+enum DistinctScalarValue {
+Int8(i8),
+Int16(i16),
+Int32(i32),
+Int64(i64),
+UInt8(u8),
+UInt16(u16),
+UInt32(u32),
+UInt64(u64),
+}
+
+/// For a given expression, maps its Arrow DataType into a LargeList of the
+/// same DataType.
+fn list_of(expr: Arc, input_schema: ) -> 
Result {
+let value_data_type = expr.data_type(input_schema)?;
+
+match value_data_type {
+DataType::Int8
+| DataType::Int16
+| DataType::Int32
+| DataType::Int64
+| DataType::UInt8
+| DataType::UInt16
+| DataType::UInt32
+| DataType::UInt64 => 
Ok(DataType::LargeList(Box::new(value_data_type))),
+_ => Err(ExecutionError::NotImplemented(
+"Unsupported column data type for DISTINCT".to_string(),
+)),
+}
+}
+
+fn accumulate_scalar(
+accum:  FnvHashSet,
+value: Option,
+) -> Result<()> {
+let accum_value = match 

[GitHub] [arrow] drusso commented on a change in pull request #8222: ARROW-10043: [Rust][DataFusion] Implement COUNT(DISTINCT col)

2020-09-22 Thread GitBox


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



##
File path: rust/datafusion/src/physical_plan/distinct_expressions.rs
##
@@ -0,0 +1,303 @@
+// 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::fmt::Debug;
+use std::hash::Hash;
+use std::rc::Rc;
+use std::sync::Arc;
+
+use arrow::array::ArrayRef;
+use arrow::array::{
+Int16Array, Int32Array, Int64Array, Int8Array, PrimitiveArrayOps, 
UInt16Array,
+UInt32Array, UInt64Array, UInt8Array,
+};
+use arrow::datatypes::{DataType, Schema};
+use arrow::record_batch::RecordBatch;
+
+use fnv::FnvHashSet;
+
+use crate::error::{ExecutionError, Result};
+use crate::logical_plan::ScalarValue;
+use crate::physical_plan::expressions::Column;
+use crate::physical_plan::hash_aggregate::AggregateMode;
+use crate::physical_plan::{Accumulator, AggregateExpr, PhysicalExpr};
+
+/// Enumeration of types that can be accumulated into a distinct set of values.
+#[derive(Debug, PartialEq, Eq, Hash, Clone)]
+enum DistinctScalarValue {
+Int8(i8),
+Int16(i16),
+Int32(i32),
+Int64(i64),
+UInt8(u8),
+UInt16(u16),
+UInt32(u32),
+UInt64(u64),
+}
+
+/// For a given expression, maps its Arrow DataType into a LargeList of the
+/// same DataType.
+fn list_of(expr: Arc, input_schema: ) -> 
Result {
+let value_data_type = expr.data_type(input_schema)?;
+
+match value_data_type {
+DataType::Int8
+| DataType::Int16
+| DataType::Int32
+| DataType::Int64
+| DataType::UInt8
+| DataType::UInt16
+| DataType::UInt32
+| DataType::UInt64 => 
Ok(DataType::LargeList(Box::new(value_data_type))),
+_ => Err(ExecutionError::NotImplemented(
+"Unsupported column data type for DISTINCT".to_string(),
+)),
+}
+}
+
+fn accumulate_scalar(
+accum:  FnvHashSet,
+value: Option,
+) -> Result<()> {
+let accum_value = match value {
+Some(ScalarValue::Int8(v)) => Some(DistinctScalarValue::Int8(v)),
+Some(ScalarValue::Int16(v)) => Some(DistinctScalarValue::Int16(v)),
+Some(ScalarValue::Int32(v)) => Some(DistinctScalarValue::Int32(v)),
+Some(ScalarValue::Int64(v)) => Some(DistinctScalarValue::Int64(v)),
+Some(ScalarValue::UInt8(v)) => Some(DistinctScalarValue::UInt8(v)),
+Some(ScalarValue::UInt16(v)) => Some(DistinctScalarValue::UInt16(v)),
+Some(ScalarValue::UInt32(v)) => Some(DistinctScalarValue::UInt32(v)),
+Some(ScalarValue::UInt64(v)) => Some(DistinctScalarValue::UInt64(v)),
+Some(ScalarValue::Null) => None,
+_ => {
+return Err(ExecutionError::NotImplemented(
+"Unsupported scalar value for DISTINCT 
accumulator".to_string(),
+))
+}
+};
+
+match accum_value {
+Some(v) => {
+accum.insert(v);
+}
+None => {}
+}
+
+Ok(())
+}
+
+macro_rules! accum_batch {
+($ARRAY_TY:ident, $DISTINCT_SCALAR_TY: path, $ARRAY: expr, $ACCUM: expr) 
=> {{
+let array = $ARRAY.as_any().downcast_ref::<$ARRAY_TY>().ok_or_else(|| {
+ExecutionError::ExecutionError("Error downcasting 
array".to_string())
+})?;
+
+for i in 0..array.len() {
+$ACCUM.insert($DISTINCT_SCALAR_TY(array.value(i)));
+}
+
+Ok(())
+}};
+}
+
+#[derive(Debug)]
+struct DistinctValuesAccumulator {
+values: FnvHashSet,
+}
+
+impl Accumulator for DistinctValuesAccumulator {
+fn accumulate_scalar( self, value: Option) -> Result<()> {
+accumulate_scalar( self.values, value)
+}
+
+fn accumulate_batch( self, _array: ) -> Result<()> {
+Err(ExecutionError::NotImplemented(

Review comment:
   Certainly. This path isn't reachable in the scenarios this PR addresses, 
but I think this will be relevant to `SELECT COUNT(DISTINCT col)` queries that 
do not include a `GROUP BY`. 
   
   
   





This is an automated message from the Apache Git Service.
To 

[GitHub] [arrow] drusso commented on a change in pull request #8222: ARROW-10043: [Rust][DataFusion] Implement COUNT(DISTINCT col)

2020-09-22 Thread GitBox


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



##
File path: rust/datafusion/src/physical_plan/distinct_expressions.rs
##
@@ -0,0 +1,303 @@
+// 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::fmt::Debug;
+use std::hash::Hash;
+use std::rc::Rc;
+use std::sync::Arc;
+
+use arrow::array::ArrayRef;
+use arrow::array::{
+Int16Array, Int32Array, Int64Array, Int8Array, PrimitiveArrayOps, 
UInt16Array,
+UInt32Array, UInt64Array, UInt8Array,
+};
+use arrow::datatypes::{DataType, Schema};
+use arrow::record_batch::RecordBatch;
+
+use fnv::FnvHashSet;
+
+use crate::error::{ExecutionError, Result};
+use crate::logical_plan::ScalarValue;
+use crate::physical_plan::expressions::Column;
+use crate::physical_plan::hash_aggregate::AggregateMode;
+use crate::physical_plan::{Accumulator, AggregateExpr, PhysicalExpr};
+
+/// Enumeration of types that can be accumulated into a distinct set of values.
+#[derive(Debug, PartialEq, Eq, Hash, Clone)]
+enum DistinctScalarValue {
+Int8(i8),
+Int16(i16),
+Int32(i32),
+Int64(i64),
+UInt8(u8),
+UInt16(u16),
+UInt32(u32),
+UInt64(u64),
+}
+
+/// For a given expression, maps its Arrow DataType into a LargeList of the
+/// same DataType.
+fn list_of(expr: Arc, input_schema: ) -> 
Result {
+let value_data_type = expr.data_type(input_schema)?;
+
+match value_data_type {
+DataType::Int8
+| DataType::Int16
+| DataType::Int32
+| DataType::Int64
+| DataType::UInt8
+| DataType::UInt16
+| DataType::UInt32
+| DataType::UInt64 => 
Ok(DataType::LargeList(Box::new(value_data_type))),
+_ => Err(ExecutionError::NotImplemented(
+"Unsupported column data type for DISTINCT".to_string(),
+)),
+}
+}
+
+fn accumulate_scalar(
+accum:  FnvHashSet,
+value: Option,
+) -> Result<()> {
+let accum_value = match value {
+Some(ScalarValue::Int8(v)) => Some(DistinctScalarValue::Int8(v)),
+Some(ScalarValue::Int16(v)) => Some(DistinctScalarValue::Int16(v)),
+Some(ScalarValue::Int32(v)) => Some(DistinctScalarValue::Int32(v)),
+Some(ScalarValue::Int64(v)) => Some(DistinctScalarValue::Int64(v)),
+Some(ScalarValue::UInt8(v)) => Some(DistinctScalarValue::UInt8(v)),
+Some(ScalarValue::UInt16(v)) => Some(DistinctScalarValue::UInt16(v)),
+Some(ScalarValue::UInt32(v)) => Some(DistinctScalarValue::UInt32(v)),
+Some(ScalarValue::UInt64(v)) => Some(DistinctScalarValue::UInt64(v)),
+Some(ScalarValue::Null) => None,
+_ => {
+return Err(ExecutionError::NotImplemented(
+"Unsupported scalar value for DISTINCT 
accumulator".to_string(),
+))
+}
+};
+
+match accum_value {
+Some(v) => {
+accum.insert(v);
+}
+None => {}
+}
+
+Ok(())
+}
+
+macro_rules! accum_batch {
+($ARRAY_TY:ident, $DISTINCT_SCALAR_TY: path, $ARRAY: expr, $ACCUM: expr) 
=> {{
+let array = $ARRAY.as_any().downcast_ref::<$ARRAY_TY>().ok_or_else(|| {
+ExecutionError::ExecutionError("Error downcasting 
array".to_string())
+})?;
+
+for i in 0..array.len() {
+$ACCUM.insert($DISTINCT_SCALAR_TY(array.value(i)));
+}
+
+Ok(())
+}};
+}
+
+#[derive(Debug)]
+struct DistinctValuesAccumulator {
+values: FnvHashSet,
+}
+
+impl Accumulator for DistinctValuesAccumulator {
+fn accumulate_scalar( self, value: Option) -> Result<()> {
+accumulate_scalar( self.values, value)
+}
+
+fn accumulate_batch( self, _array: ) -> Result<()> {
+Err(ExecutionError::NotImplemented(

Review comment:
   Certainly. This path isn't reachable in the scenarios this PR addresses, 
but I think this will be relevant to `SELECT COUNT(DISTINCT col)` queries that 
does not include a `GROUP BY`. 
   
   
   

##
File path: rust/datafusion/src/physical_plan/distinct_expressions.rs
##
@@ -0,0 +1,303 @@
+// Licensed to 

[GitHub] [arrow] drusso commented on a change in pull request #8222: ARROW-10043: [Rust][DataFusion] Implement COUNT(DISTINCT col)

2020-09-22 Thread GitBox


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



##
File path: rust/datafusion/src/physical_plan/distinct_expressions.rs
##
@@ -0,0 +1,303 @@
+// 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::fmt::Debug;
+use std::hash::Hash;
+use std::rc::Rc;
+use std::sync::Arc;
+
+use arrow::array::ArrayRef;
+use arrow::array::{
+Int16Array, Int32Array, Int64Array, Int8Array, PrimitiveArrayOps, 
UInt16Array,
+UInt32Array, UInt64Array, UInt8Array,
+};
+use arrow::datatypes::{DataType, Schema};
+use arrow::record_batch::RecordBatch;
+
+use fnv::FnvHashSet;
+
+use crate::error::{ExecutionError, Result};
+use crate::logical_plan::ScalarValue;
+use crate::physical_plan::expressions::Column;
+use crate::physical_plan::hash_aggregate::AggregateMode;
+use crate::physical_plan::{Accumulator, AggregateExpr, PhysicalExpr};
+
+/// Enumeration of types that can be accumulated into a distinct set of values.
+#[derive(Debug, PartialEq, Eq, Hash, Clone)]
+enum DistinctScalarValue {

Review comment:
   These are used as the values in the iterator's `HashSet`, and 
unfortunately it's not possible to derive `Hash` for `ScalarValue` since it 
nests `f32` and `f64`. 
   
   As you suggested, `GroupByScalar` is a good candidate here. (I assumed you 
meant `GroupByScalar` rather than `GroupByKey`?)





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




[GitHub] [arrow] drusso commented on a change in pull request #8222: ARROW-10043: [Rust][DataFusion] Implement COUNT(DISTINCT col)

2020-09-22 Thread GitBox


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



##
File path: rust/datafusion/src/physical_plan/distinct_expressions.rs
##
@@ -0,0 +1,303 @@
+// 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::fmt::Debug;
+use std::hash::Hash;
+use std::rc::Rc;
+use std::sync::Arc;
+
+use arrow::array::ArrayRef;
+use arrow::array::{
+Int16Array, Int32Array, Int64Array, Int8Array, PrimitiveArrayOps, 
UInt16Array,
+UInt32Array, UInt64Array, UInt8Array,
+};
+use arrow::datatypes::{DataType, Schema};
+use arrow::record_batch::RecordBatch;
+
+use fnv::FnvHashSet;
+
+use crate::error::{ExecutionError, Result};
+use crate::logical_plan::ScalarValue;
+use crate::physical_plan::expressions::Column;
+use crate::physical_plan::hash_aggregate::AggregateMode;
+use crate::physical_plan::{Accumulator, AggregateExpr, PhysicalExpr};
+
+/// Enumeration of types that can be accumulated into a distinct set of values.
+#[derive(Debug, PartialEq, Eq, Hash, Clone)]
+enum DistinctScalarValue {
+Int8(i8),
+Int16(i16),
+Int32(i32),
+Int64(i64),
+UInt8(u8),
+UInt16(u16),
+UInt32(u32),
+UInt64(u64),
+}
+
+/// For a given expression, maps its Arrow DataType into a LargeList of the
+/// same DataType.
+fn list_of(expr: Arc, input_schema: ) -> 
Result {
+let value_data_type = expr.data_type(input_schema)?;
+
+match value_data_type {
+DataType::Int8
+| DataType::Int16
+| DataType::Int32
+| DataType::Int64
+| DataType::UInt8
+| DataType::UInt16
+| DataType::UInt32
+| DataType::UInt64 => 
Ok(DataType::LargeList(Box::new(value_data_type))),
+_ => Err(ExecutionError::NotImplemented(
+"Unsupported column data type for DISTINCT".to_string(),
+)),
+}
+}
+
+fn accumulate_scalar(
+accum:  FnvHashSet,
+value: Option,
+) -> Result<()> {
+let accum_value = match value {
+Some(ScalarValue::Int8(v)) => Some(DistinctScalarValue::Int8(v)),
+Some(ScalarValue::Int16(v)) => Some(DistinctScalarValue::Int16(v)),
+Some(ScalarValue::Int32(v)) => Some(DistinctScalarValue::Int32(v)),
+Some(ScalarValue::Int64(v)) => Some(DistinctScalarValue::Int64(v)),
+Some(ScalarValue::UInt8(v)) => Some(DistinctScalarValue::UInt8(v)),
+Some(ScalarValue::UInt16(v)) => Some(DistinctScalarValue::UInt16(v)),
+Some(ScalarValue::UInt32(v)) => Some(DistinctScalarValue::UInt32(v)),
+Some(ScalarValue::UInt64(v)) => Some(DistinctScalarValue::UInt64(v)),
+Some(ScalarValue::Null) => None,
+_ => {
+return Err(ExecutionError::NotImplemented(
+"Unsupported scalar value for DISTINCT 
accumulator".to_string(),
+))
+}
+};
+
+match accum_value {
+Some(v) => {
+accum.insert(v);
+}
+None => {}
+}
+
+Ok(())
+}
+
+macro_rules! accum_batch {
+($ARRAY_TY:ident, $DISTINCT_SCALAR_TY: path, $ARRAY: expr, $ACCUM: expr) 
=> {{
+let array = $ARRAY.as_any().downcast_ref::<$ARRAY_TY>().ok_or_else(|| {
+ExecutionError::ExecutionError("Error downcasting 
array".to_string())
+})?;
+
+for i in 0..array.len() {
+$ACCUM.insert($DISTINCT_SCALAR_TY(array.value(i)));
+}
+
+Ok(())
+}};
+}
+
+#[derive(Debug)]
+struct DistinctValuesAccumulator {
+values: FnvHashSet,

Review comment:
   Good suggestion. A couple of questions:
   
   - Would this generalize to (or be easily adapted for) non-integers, like 
floats or strings?
   - Is there DataFusion tooling for benchmarking different implementations?
   
   Given that, perhaps this is an optimization we can explore at a later time? 

##
File path: rust/datafusion/src/physical_plan/hash_aggregate.rs
##
@@ -374,6 +380,18 @@ impl RecordBatchReader for GroupedHashAggregateIterator {
 col,
 accums
 ),
+DataType::LargeList(_) => {
+