e-dard commented on a change in pull request #1841:
URL: https://github.com/apache/arrow-datafusion/pull/1841#discussion_r807807819
##########
File path: datafusion/Cargo.toml
##########
@@ -81,6 +81,8 @@ num-traits = { version = "0.2", optional = true }
pyo3 = { version = "0.15", optional = true }
tempfile = "3"
parking_lot = "0.12"
+#roaring = "0.8.1"
Review comment:
Cruft?
```suggestion
```
##########
File path: datafusion/src/physical_plan/expressions/bitmap_distinct.rs
##########
@@ -0,0 +1,233 @@
+// 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 std::any::Any;
+use std::borrow::Borrow;
+
+use std::fmt::Debug;
+use std::ops::BitOrAssign;
+use std::sync::Arc;
+
+use arrow::array::{
+ Array, ArrayRef, BinaryArray, Int16Array, Int32Array, Int8Array,
UInt16Array,
+ UInt32Array, UInt8Array,
+};
+use arrow::datatypes::{DataType, Field};
+use croaring::Bitmap;
+use log::info;
+
+use crate::error::{DataFusionError, Result};
+use crate::physical_plan::{Accumulator, AggregateExpr, PhysicalExpr};
+use crate::scalar::ScalarValue;
+
+use super::format_state_name;
+
+#[derive(Debug)]
+pub struct BitMapDistinct {
+ name: String,
+ input_data_type: DataType,
+ expr: Arc<dyn PhysicalExpr>,
+}
+
+impl BitMapDistinct {
+ /// Create a new bitmapDistinct aggregate function.
+ pub fn new(
+ expr: Arc<dyn PhysicalExpr>,
+ name: impl Into<String>,
+ input_data_type: DataType,
+ ) -> Self {
+ Self {
+ name: name.into(),
+ input_data_type,
+ expr,
+ }
+ }
+}
+
+impl AggregateExpr for BitMapDistinct {
+ /// Return a reference to Any that can be used for downcasting
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ /// the field of the final result of this aggregation.
+ fn field(&self) -> Result<Field> {
+ Ok(Field::new(&self.name, DataType::UInt64, false))
+ }
+
+ fn create_accumulator(&self) -> Result<Box<dyn Accumulator>> {
+ let accumulator: Box<dyn Accumulator> = match &self.input_data_type {
+ DataType::UInt8
+ | DataType::UInt16
+ | DataType::UInt32
+ | DataType::Int8
+ | DataType::Int16
+ | DataType::Int32 =>
Box::new(BitmapDistinctCountAccumulator::try_new()),
+ other => {
+ return Err(DataFusionError::NotImplemented(format!(
+ "Support for 'bitmap_distinct' for data type {} is not
implemented",
+ other
+ )))
+ }
+ };
+ Ok(accumulator)
+ }
+
+ fn state_fields(&self) -> Result<Vec<Field>> {
+ Ok(vec![Field::new(
+ &format_state_name(&self.name, "bitmap_registers"),
+ DataType::Binary,
+ false,
+ )])
+ }
+
+ fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ vec![self.expr.clone()]
+ }
+
+ fn name(&self) -> &str {
+ &self.name
+ }
+}
+
+#[derive(Debug)]
+struct BitmapDistinctCountAccumulator {
+ bitmap: croaring::bitmap::Bitmap,
+}
+
+impl BitmapDistinctCountAccumulator {
+ fn try_new() -> Self {
+ Self {
+ bitmap: croaring::bitmap::Bitmap::create(),
+ }
+ }
+}
+
+impl Accumulator for BitmapDistinctCountAccumulator {
+ //state() can be used by physical nodes to aggregate states together and
send them over the network/threads, to combine values.
+ fn state(&self) -> Result<Vec<ScalarValue>> {
+ //maybe run optimized
+ let buffer = self.bitmap.serialize();
+ Ok(vec![ScalarValue::Binary(Some(buffer))])
+ }
+
+ fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
+ let value = &values[0];
+ if value.is_empty() {
+ info!("BitmapDistinctCountAccumulator update_batch in empty
batch");
Review comment:
Does this need to be logged at `info` if it's not an error state?
##########
File path: datafusion/src/physical_plan/expressions/bitmap_distinct.rs
##########
@@ -0,0 +1,233 @@
+// 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 std::any::Any;
+use std::borrow::Borrow;
+
+use std::fmt::Debug;
+use std::ops::BitOrAssign;
+use std::sync::Arc;
+
+use arrow::array::{
+ Array, ArrayRef, BinaryArray, Int16Array, Int32Array, Int8Array,
UInt16Array,
+ UInt32Array, UInt8Array,
+};
+use arrow::datatypes::{DataType, Field};
+use croaring::Bitmap;
+use log::info;
+
+use crate::error::{DataFusionError, Result};
+use crate::physical_plan::{Accumulator, AggregateExpr, PhysicalExpr};
+use crate::scalar::ScalarValue;
+
+use super::format_state_name;
+
+#[derive(Debug)]
+pub struct BitMapDistinct {
+ name: String,
+ input_data_type: DataType,
+ expr: Arc<dyn PhysicalExpr>,
+}
+
+impl BitMapDistinct {
+ /// Create a new bitmapDistinct aggregate function.
+ pub fn new(
+ expr: Arc<dyn PhysicalExpr>,
+ name: impl Into<String>,
+ input_data_type: DataType,
+ ) -> Self {
+ Self {
+ name: name.into(),
+ input_data_type,
+ expr,
+ }
+ }
+}
+
+impl AggregateExpr for BitMapDistinct {
+ /// Return a reference to Any that can be used for downcasting
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ /// the field of the final result of this aggregation.
+ fn field(&self) -> Result<Field> {
+ Ok(Field::new(&self.name, DataType::UInt64, false))
+ }
+
+ fn create_accumulator(&self) -> Result<Box<dyn Accumulator>> {
+ let accumulator: Box<dyn Accumulator> = match &self.input_data_type {
+ DataType::UInt8
+ | DataType::UInt16
+ | DataType::UInt32
+ | DataType::Int8
+ | DataType::Int16
+ | DataType::Int32 =>
Box::new(BitmapDistinctCountAccumulator::try_new()),
+ other => {
+ return Err(DataFusionError::NotImplemented(format!(
+ "Support for 'bitmap_distinct' for data type {} is not
implemented",
+ other
+ )))
+ }
+ };
+ Ok(accumulator)
+ }
+
+ fn state_fields(&self) -> Result<Vec<Field>> {
+ Ok(vec![Field::new(
+ &format_state_name(&self.name, "bitmap_registers"),
+ DataType::Binary,
+ false,
+ )])
+ }
+
+ fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ vec![self.expr.clone()]
+ }
+
+ fn name(&self) -> &str {
+ &self.name
+ }
+}
+
+#[derive(Debug)]
+struct BitmapDistinctCountAccumulator {
+ bitmap: croaring::bitmap::Bitmap,
+}
+
+impl BitmapDistinctCountAccumulator {
+ fn try_new() -> Self {
+ Self {
+ bitmap: croaring::bitmap::Bitmap::create(),
+ }
+ }
+}
+
+impl Accumulator for BitmapDistinctCountAccumulator {
+ //state() can be used by physical nodes to aggregate states together and
send them over the network/threads, to combine values.
+ fn state(&self) -> Result<Vec<ScalarValue>> {
+ //maybe run optimized
+ let buffer = self.bitmap.serialize();
+ Ok(vec![ScalarValue::Binary(Some(buffer))])
+ }
+
+ fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
+ let value = &values[0];
+ if value.is_empty() {
+ info!("BitmapDistinctCountAccumulator update_batch in empty
batch");
+ return Ok(());
+ }
+ match value.data_type() {
+ DataType::Int8 => {
+ let array =
value.as_any().downcast_ref::<Int8Array>().unwrap();
+ self.bitmap.add_many(
+ &array
+ .values()
+ .iter()
+ .map(|&x| x as u32)
+ .collect::<Vec<u32>>(),
+ );
+ }
+ DataType::Int16 => {
+ let array =
value.as_any().downcast_ref::<Int16Array>().unwrap();
+ self.bitmap.add_many(
+ &array
+ .values()
+ .iter()
+ .map(|&x| x as u32)
+ .collect::<Vec<u32>>(),
+ );
+ }
+ DataType::Int32 => {
+ let array =
value.as_any().downcast_ref::<Int32Array>().unwrap();
+ self.bitmap.add_many(
+ &array
+ .values()
+ .iter()
+ .map(|&x| x as u32)
+ .collect::<Vec<u32>>(),
+ );
+ }
+ DataType::UInt8 => {
+ let array =
value.as_any().downcast_ref::<UInt8Array>().unwrap();
+ self.bitmap.add_many(
+ &array
+ .values()
+ .iter()
+ .map(|&x| x as u32)
+ .collect::<Vec<u32>>(),
+ );
+ }
+ DataType::UInt16 => {
+ let array =
value.as_any().downcast_ref::<UInt16Array>().unwrap();
+ self.bitmap.add_many(
+ &array
+ .values()
+ .iter()
+ .map(|&x| x as u32)
+ .collect::<Vec<u32>>(),
+ );
+ }
+ DataType::UInt32 => {
+ let array =
value.as_any().downcast_ref::<UInt32Array>().unwrap();
+ self.bitmap.add_many(array.values());
+ }
+ e => {
+ return Err(DataFusionError::Internal(format!(
+ "BITMAP_COUNT_DISTINCT is not expected to receive the type
{:?}",
+ e
+ )));
+ }
+ }
+ Ok(())
+ }
+
+ fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
+ assert_eq!(1, states.len(), "expect only 1 element in the states");
+ let binary_array =
states[0].as_any().downcast_ref::<BinaryArray>().unwrap();
+ let bitmaps = binary_array
+ .iter()
+ .map(|x| {
+ Bitmap::deserialize(x.expect(
+ "Impossibly got empty binary array from states in
bitmap_distinct",
+ ))
+ })
+ .collect::<Vec<Bitmap>>();
+ let bitmaps = &bitmaps.iter().map(|x|
x.borrow()).collect::<Vec<&Bitmap>>()[..];
+ //Do not use self.bitmap = xxx, because '=' has been wrote for
'BitAnd' !.
+ self.bitmap.bitor_assign(Bitmap::fast_or(bitmaps));
+ Ok(())
+ }
+
+ fn evaluate(&self) -> Result<ScalarValue> {
Review comment:
I assume this generally only gets called once per query? Only asking
because `cardinality` is quite an expensive call.
##########
File path: datafusion/src/physical_plan/expressions/bitmap_distinct.rs
##########
@@ -0,0 +1,233 @@
+// 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 std::any::Any;
+use std::borrow::Borrow;
+
+use std::fmt::Debug;
+use std::ops::BitOrAssign;
+use std::sync::Arc;
+
+use arrow::array::{
+ Array, ArrayRef, BinaryArray, Int16Array, Int32Array, Int8Array,
UInt16Array,
+ UInt32Array, UInt8Array,
+};
+use arrow::datatypes::{DataType, Field};
+use croaring::Bitmap;
+use log::info;
+
+use crate::error::{DataFusionError, Result};
+use crate::physical_plan::{Accumulator, AggregateExpr, PhysicalExpr};
+use crate::scalar::ScalarValue;
+
+use super::format_state_name;
+
+#[derive(Debug)]
+pub struct BitMapDistinct {
+ name: String,
+ input_data_type: DataType,
+ expr: Arc<dyn PhysicalExpr>,
+}
+
+impl BitMapDistinct {
+ /// Create a new bitmapDistinct aggregate function.
+ pub fn new(
+ expr: Arc<dyn PhysicalExpr>,
+ name: impl Into<String>,
+ input_data_type: DataType,
+ ) -> Self {
+ Self {
+ name: name.into(),
+ input_data_type,
+ expr,
+ }
+ }
+}
+
+impl AggregateExpr for BitMapDistinct {
+ /// Return a reference to Any that can be used for downcasting
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ /// the field of the final result of this aggregation.
+ fn field(&self) -> Result<Field> {
+ Ok(Field::new(&self.name, DataType::UInt64, false))
+ }
+
+ fn create_accumulator(&self) -> Result<Box<dyn Accumulator>> {
+ let accumulator: Box<dyn Accumulator> = match &self.input_data_type {
+ DataType::UInt8
+ | DataType::UInt16
+ | DataType::UInt32
+ | DataType::Int8
+ | DataType::Int16
+ | DataType::Int32 =>
Box::new(BitmapDistinctCountAccumulator::try_new()),
+ other => {
+ return Err(DataFusionError::NotImplemented(format!(
+ "Support for 'bitmap_distinct' for data type {} is not
implemented",
+ other
+ )))
+ }
+ };
+ Ok(accumulator)
+ }
+
+ fn state_fields(&self) -> Result<Vec<Field>> {
+ Ok(vec![Field::new(
+ &format_state_name(&self.name, "bitmap_registers"),
+ DataType::Binary,
+ false,
+ )])
+ }
+
+ fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ vec![self.expr.clone()]
+ }
+
+ fn name(&self) -> &str {
+ &self.name
+ }
+}
+
+#[derive(Debug)]
+struct BitmapDistinctCountAccumulator {
+ bitmap: croaring::bitmap::Bitmap,
+}
+
+impl BitmapDistinctCountAccumulator {
+ fn try_new() -> Self {
+ Self {
+ bitmap: croaring::bitmap::Bitmap::create(),
+ }
+ }
+}
+
+impl Accumulator for BitmapDistinctCountAccumulator {
+ //state() can be used by physical nodes to aggregate states together and
send them over the network/threads, to combine values.
+ fn state(&self) -> Result<Vec<ScalarValue>> {
+ //maybe run optimized
+ let buffer = self.bitmap.serialize();
+ Ok(vec![ScalarValue::Binary(Some(buffer))])
+ }
+
+ fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
+ let value = &values[0];
+ if value.is_empty() {
+ info!("BitmapDistinctCountAccumulator update_batch in empty
batch");
+ return Ok(());
+ }
+ match value.data_type() {
+ DataType::Int8 => {
+ let array =
value.as_any().downcast_ref::<Int8Array>().unwrap();
+ self.bitmap.add_many(
+ &array
+ .values()
+ .iter()
+ .map(|&x| x as u32)
+ .collect::<Vec<u32>>(),
+ );
+ }
+ DataType::Int16 => {
+ let array =
value.as_any().downcast_ref::<Int16Array>().unwrap();
+ self.bitmap.add_many(
+ &array
+ .values()
+ .iter()
+ .map(|&x| x as u32)
+ .collect::<Vec<u32>>(),
+ );
+ }
+ DataType::Int32 => {
+ let array =
value.as_any().downcast_ref::<Int32Array>().unwrap();
+ self.bitmap.add_many(
+ &array
+ .values()
+ .iter()
+ .map(|&x| x as u32)
+ .collect::<Vec<u32>>(),
+ );
+ }
+ DataType::UInt8 => {
+ let array =
value.as_any().downcast_ref::<UInt8Array>().unwrap();
+ self.bitmap.add_many(
+ &array
+ .values()
+ .iter()
+ .map(|&x| x as u32)
+ .collect::<Vec<u32>>(),
+ );
+ }
+ DataType::UInt16 => {
+ let array =
value.as_any().downcast_ref::<UInt16Array>().unwrap();
+ self.bitmap.add_many(
+ &array
+ .values()
+ .iter()
+ .map(|&x| x as u32)
+ .collect::<Vec<u32>>(),
+ );
+ }
+ DataType::UInt32 => {
+ let array =
value.as_any().downcast_ref::<UInt32Array>().unwrap();
+ self.bitmap.add_many(array.values());
+ }
+ e => {
+ return Err(DataFusionError::Internal(format!(
+ "BITMAP_COUNT_DISTINCT is not expected to receive the type
{:?}",
+ e
+ )));
+ }
+ }
+ Ok(())
+ }
+
+ fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
+ assert_eq!(1, states.len(), "expect only 1 element in the states");
Review comment:
You have the option to return an error here. Is that perhaps preferable
than a hard crash? Maybe higher up the call chain some more context could be
added to help debugging.
##########
File path: datafusion/src/physical_plan/expressions/bitmap_distinct.rs
##########
@@ -0,0 +1,233 @@
+// 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 std::any::Any;
+use std::borrow::Borrow;
+
+use std::fmt::Debug;
+use std::ops::BitOrAssign;
+use std::sync::Arc;
+
+use arrow::array::{
+ Array, ArrayRef, BinaryArray, Int16Array, Int32Array, Int8Array,
UInt16Array,
+ UInt32Array, UInt8Array,
+};
+use arrow::datatypes::{DataType, Field};
+use croaring::Bitmap;
+use log::info;
+
+use crate::error::{DataFusionError, Result};
+use crate::physical_plan::{Accumulator, AggregateExpr, PhysicalExpr};
+use crate::scalar::ScalarValue;
+
+use super::format_state_name;
+
+#[derive(Debug)]
+pub struct BitMapDistinct {
+ name: String,
+ input_data_type: DataType,
+ expr: Arc<dyn PhysicalExpr>,
+}
+
+impl BitMapDistinct {
+ /// Create a new bitmapDistinct aggregate function.
+ pub fn new(
+ expr: Arc<dyn PhysicalExpr>,
+ name: impl Into<String>,
+ input_data_type: DataType,
+ ) -> Self {
+ Self {
+ name: name.into(),
+ input_data_type,
+ expr,
+ }
+ }
+}
+
+impl AggregateExpr for BitMapDistinct {
+ /// Return a reference to Any that can be used for downcasting
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ /// the field of the final result of this aggregation.
+ fn field(&self) -> Result<Field> {
+ Ok(Field::new(&self.name, DataType::UInt64, false))
+ }
+
+ fn create_accumulator(&self) -> Result<Box<dyn Accumulator>> {
+ let accumulator: Box<dyn Accumulator> = match &self.input_data_type {
+ DataType::UInt8
+ | DataType::UInt16
+ | DataType::UInt32
+ | DataType::Int8
+ | DataType::Int16
+ | DataType::Int32 =>
Box::new(BitmapDistinctCountAccumulator::try_new()),
+ other => {
+ return Err(DataFusionError::NotImplemented(format!(
+ "Support for 'bitmap_distinct' for data type {} is not
implemented",
+ other
+ )))
+ }
+ };
+ Ok(accumulator)
+ }
+
+ fn state_fields(&self) -> Result<Vec<Field>> {
+ Ok(vec![Field::new(
+ &format_state_name(&self.name, "bitmap_registers"),
+ DataType::Binary,
+ false,
+ )])
+ }
+
+ fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ vec![self.expr.clone()]
+ }
+
+ fn name(&self) -> &str {
+ &self.name
+ }
+}
+
+#[derive(Debug)]
+struct BitmapDistinctCountAccumulator {
+ bitmap: croaring::bitmap::Bitmap,
+}
+
+impl BitmapDistinctCountAccumulator {
+ fn try_new() -> Self {
+ Self {
+ bitmap: croaring::bitmap::Bitmap::create(),
+ }
+ }
+}
+
+impl Accumulator for BitmapDistinctCountAccumulator {
+ //state() can be used by physical nodes to aggregate states together and
send them over the network/threads, to combine values.
+ fn state(&self) -> Result<Vec<ScalarValue>> {
+ //maybe run optimized
Review comment:
I think this is a bit of a tricky question because the bitmap only lives
for the duration of the query right? One of the main things that can be
optimised is to convert array containers into run containers (which use RLE
compression), so it seems likely that it depends on the contents of the input.
A benchmark with typical data might help answer this.
##########
File path: datafusion/src/physical_plan/expressions/bitmap_distinct.rs
##########
@@ -0,0 +1,233 @@
+// 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 std::any::Any;
+use std::borrow::Borrow;
+
+use std::fmt::Debug;
+use std::ops::BitOrAssign;
+use std::sync::Arc;
+
+use arrow::array::{
+ Array, ArrayRef, BinaryArray, Int16Array, Int32Array, Int8Array,
UInt16Array,
+ UInt32Array, UInt8Array,
+};
+use arrow::datatypes::{DataType, Field};
+use croaring::Bitmap;
+use log::info;
+
+use crate::error::{DataFusionError, Result};
+use crate::physical_plan::{Accumulator, AggregateExpr, PhysicalExpr};
+use crate::scalar::ScalarValue;
+
+use super::format_state_name;
+
+#[derive(Debug)]
+pub struct BitMapDistinct {
+ name: String,
+ input_data_type: DataType,
+ expr: Arc<dyn PhysicalExpr>,
+}
+
+impl BitMapDistinct {
+ /// Create a new bitmapDistinct aggregate function.
+ pub fn new(
+ expr: Arc<dyn PhysicalExpr>,
+ name: impl Into<String>,
+ input_data_type: DataType,
+ ) -> Self {
+ Self {
+ name: name.into(),
+ input_data_type,
+ expr,
+ }
+ }
+}
+
+impl AggregateExpr for BitMapDistinct {
+ /// Return a reference to Any that can be used for downcasting
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ /// the field of the final result of this aggregation.
+ fn field(&self) -> Result<Field> {
+ Ok(Field::new(&self.name, DataType::UInt64, false))
+ }
+
+ fn create_accumulator(&self) -> Result<Box<dyn Accumulator>> {
+ let accumulator: Box<dyn Accumulator> = match &self.input_data_type {
+ DataType::UInt8
+ | DataType::UInt16
+ | DataType::UInt32
+ | DataType::Int8
+ | DataType::Int16
+ | DataType::Int32 =>
Box::new(BitmapDistinctCountAccumulator::try_new()),
+ other => {
+ return Err(DataFusionError::NotImplemented(format!(
+ "Support for 'bitmap_distinct' for data type {} is not
implemented",
+ other
+ )))
+ }
+ };
+ Ok(accumulator)
+ }
+
+ fn state_fields(&self) -> Result<Vec<Field>> {
+ Ok(vec![Field::new(
+ &format_state_name(&self.name, "bitmap_registers"),
+ DataType::Binary,
+ false,
+ )])
+ }
+
+ fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ vec![self.expr.clone()]
+ }
+
+ fn name(&self) -> &str {
+ &self.name
+ }
+}
+
+#[derive(Debug)]
+struct BitmapDistinctCountAccumulator {
+ bitmap: croaring::bitmap::Bitmap,
+}
+
+impl BitmapDistinctCountAccumulator {
+ fn try_new() -> Self {
+ Self {
+ bitmap: croaring::bitmap::Bitmap::create(),
+ }
+ }
+}
+
+impl Accumulator for BitmapDistinctCountAccumulator {
+ //state() can be used by physical nodes to aggregate states together and
send them over the network/threads, to combine values.
+ fn state(&self) -> Result<Vec<ScalarValue>> {
+ //maybe run optimized
+ let buffer = self.bitmap.serialize();
+ Ok(vec![ScalarValue::Binary(Some(buffer))])
+ }
+
+ fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
+ let value = &values[0];
+ if value.is_empty() {
+ info!("BitmapDistinctCountAccumulator update_batch in empty
batch");
+ return Ok(());
+ }
+ match value.data_type() {
+ DataType::Int8 => {
+ let array =
value.as_any().downcast_ref::<Int8Array>().unwrap();
+ self.bitmap.add_many(
+ &array
+ .values()
+ .iter()
+ .map(|&x| x as u32)
+ .collect::<Vec<u32>>(),
+ );
+ }
+ DataType::Int16 => {
+ let array =
value.as_any().downcast_ref::<Int16Array>().unwrap();
+ self.bitmap.add_many(
+ &array
+ .values()
+ .iter()
+ .map(|&x| x as u32)
+ .collect::<Vec<u32>>(),
+ );
+ }
+ DataType::Int32 => {
+ let array =
value.as_any().downcast_ref::<Int32Array>().unwrap();
+ self.bitmap.add_many(
+ &array
+ .values()
+ .iter()
+ .map(|&x| x as u32)
+ .collect::<Vec<u32>>(),
+ );
+ }
+ DataType::UInt8 => {
+ let array =
value.as_any().downcast_ref::<UInt8Array>().unwrap();
+ self.bitmap.add_many(
+ &array
+ .values()
+ .iter()
+ .map(|&x| x as u32)
+ .collect::<Vec<u32>>(),
+ );
+ }
+ DataType::UInt16 => {
+ let array =
value.as_any().downcast_ref::<UInt16Array>().unwrap();
+ self.bitmap.add_many(
+ &array
+ .values()
+ .iter()
+ .map(|&x| x as u32)
+ .collect::<Vec<u32>>(),
+ );
+ }
+ DataType::UInt32 => {
+ let array =
value.as_any().downcast_ref::<UInt32Array>().unwrap();
+ self.bitmap.add_many(array.values());
+ }
+ e => {
+ return Err(DataFusionError::Internal(format!(
+ "BITMAP_COUNT_DISTINCT is not expected to receive the type
{:?}",
+ e
+ )));
+ }
+ }
+ Ok(())
+ }
+
+ fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
+ assert_eq!(1, states.len(), "expect only 1 element in the states");
+ let binary_array =
states[0].as_any().downcast_ref::<BinaryArray>().unwrap();
+ let bitmaps = binary_array
+ .iter()
+ .map(|x| {
+ Bitmap::deserialize(x.expect(
+ "Impossibly got empty binary array from states in
bitmap_distinct",
+ ))
+ })
+ .collect::<Vec<Bitmap>>();
+ let bitmaps = &bitmaps.iter().map(|x|
x.borrow()).collect::<Vec<&Bitmap>>()[..];
+ //Do not use self.bitmap = xxx, because '=' has been wrote for
'BitAnd' !.
+ self.bitmap.bitor_assign(Bitmap::fast_or(bitmaps));
+ Ok(())
Review comment:
I might be way off here (sorry if so), but when I look at this I wonder
if you can simplify it to this:
```suggestion
for data in binary_array.iter().flatten() {
self.bitmap.or_inplace(&Bitmap::deserialize(data));
}
Ok(())
```
--
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]