You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@datafusion.apache.org by gi...@apache.org on 2026/04/22 00:44:03 UTC
(datafusion) 01/01: perf: Optimize approx count distinct using bitmaps instead of HLL for smaller int datatypes (#21453)
This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-21453-192ceb68db409952c4c9e3a74ba734cad6bf59ad
in repository https://gitbox.apache.org/repos/asf/datafusion.git
commit e5d91459aa84cf71fb547b89a08e88a4b443f43d
Author: Bhargava Vadlamani <11...@users.noreply.github.com>
AuthorDate: Tue Apr 21 17:43:39 2026 -0700
perf: Optimize approx count distinct using bitmaps instead of HLL for smaller int datatypes (#21453)
## Which issue does this PR close?
<!--
We generally require a GitHub issue to be filed for all bug fixes and
enhancements and this helps us generate change logs for our releases.
You can link an issue to this PR using the GitHub syntax. For example
`Closes #123` indicates that this PR will close issue #123.
-->
- Closes https://github.com/apache/datafusion/issues/1109
## Rationale for this change
<!--
Why are you proposing this change? If this is already explained clearly
in the issue then this section is not needed.
Explaining clearly why changes are proposed helps reviewers understand
your changes and offer better suggestions for fixes.
-->
## What changes are included in this PR?
<!--
There is no need to duplicate the description in the issue here but it
is sometimes worth providing a summary of the individual changes in this
PR.
-->
## Are these changes tested?
<!--
We typically require tests for all PRs in order to:
1. Prevent the code from being accidentally broken by subsequent changes
2. Serve as another way to document the expected behavior of the code
If tests are not included in your PR, please explain why (for example,
are they covered by existing tests)?
-->
## Are there any user-facing changes?
<!--
If there are user-facing changes then we may require documentation to be
updated before approving the PR.
-->
<!--
If there are any breaking changes to public APIs, please add the `api
change` label.
-->
---
.../functions-aggregate/src/approx_distinct.rs | 101 +++++++++++++++++----
1 file changed, 83 insertions(+), 18 deletions(-)
diff --git a/datafusion/functions-aggregate/src/approx_distinct.rs b/datafusion/functions-aggregate/src/approx_distinct.rs
index 40da98c3eb..cc42b6c22b 100644
--- a/datafusion/functions-aggregate/src/approx_distinct.rs
+++ b/datafusion/functions-aggregate/src/approx_distinct.rs
@@ -23,11 +23,10 @@ use arrow::array::{
GenericBinaryArray, GenericStringArray, OffsetSizeTrait, PrimitiveArray,
};
use arrow::datatypes::{
- ArrowPrimitiveType, Date32Type, Date64Type, FieldRef, Int8Type, Int16Type, Int32Type,
- Int64Type, Time32MillisecondType, Time32SecondType, Time64MicrosecondType,
- Time64NanosecondType, TimeUnit, TimestampMicrosecondType, TimestampMillisecondType,
- TimestampNanosecondType, TimestampSecondType, UInt8Type, UInt16Type, UInt32Type,
- UInt64Type,
+ ArrowPrimitiveType, Date32Type, Date64Type, FieldRef, Int32Type, Int64Type,
+ Time32MillisecondType, Time32SecondType, Time64MicrosecondType, Time64NanosecondType,
+ TimeUnit, TimestampMicrosecondType, TimestampMillisecondType,
+ TimestampNanosecondType, TimestampSecondType, UInt32Type, UInt64Type,
};
use arrow::{array::ArrayRef, datatypes::DataType, datatypes::Field};
use datafusion_common::ScalarValue;
@@ -40,6 +39,10 @@ use datafusion_expr::utils::format_state_name;
use datafusion_expr::{
Accumulator, AggregateUDFImpl, Documentation, Signature, Volatility,
};
+use datafusion_functions_aggregate_common::aggregate::count_distinct::{
+ Bitmap65536DistinctCountAccumulator, Bitmap65536DistinctCountAccumulatorI16,
+ BoolArray256DistinctCountAccumulator, BoolArray256DistinctCountAccumulatorI8,
+};
use datafusion_functions_aggregate_common::noop_accumulator::NoopAccumulator;
use datafusion_macros::user_doc;
use std::fmt::{Debug, Formatter};
@@ -84,6 +87,36 @@ impl<T: Hash + ?Sized> TryFrom<&ScalarValue> for HyperLogLog<T> {
}
}
+#[derive(Debug)]
+struct ApproxDistinctBitmapWrapper<A: Accumulator> {
+ inner: A,
+}
+
+impl<A: Accumulator> Accumulator for ApproxDistinctBitmapWrapper<A> {
+ fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
+ self.inner.update_batch(values)
+ }
+
+ fn evaluate(&mut self) -> Result<ScalarValue> {
+ match self.inner.evaluate()? {
+ ScalarValue::Int64(Some(v)) => Ok(ScalarValue::UInt64(Some(v as u64))),
+ other => internal_err!("unexpected: {other}"),
+ }
+ }
+
+ fn size(&self) -> usize {
+ self.inner.size()
+ }
+
+ fn state(&mut self) -> Result<Vec<ScalarValue>> {
+ self.inner.state()
+ }
+
+ fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
+ self.inner.merge_batch(states)
+ }
+}
+
#[derive(Debug)]
struct NumericHLLAccumulator<T>
where
@@ -302,6 +335,39 @@ impl ApproxDistinct {
}
}
+#[cold]
+fn get_small_int_approx_accumulator(
+ data_type: &DataType,
+) -> Result<Box<dyn Accumulator>> {
+ match data_type {
+ DataType::UInt8 => Ok(Box::new(ApproxDistinctBitmapWrapper {
+ inner: BoolArray256DistinctCountAccumulator::new(),
+ })),
+ DataType::Int8 => Ok(Box::new(ApproxDistinctBitmapWrapper {
+ inner: BoolArray256DistinctCountAccumulatorI8::new(),
+ })),
+ DataType::UInt16 => Ok(Box::new(ApproxDistinctBitmapWrapper {
+ inner: Bitmap65536DistinctCountAccumulator::new(),
+ })),
+ DataType::Int16 => Ok(Box::new(ApproxDistinctBitmapWrapper {
+ inner: Bitmap65536DistinctCountAccumulatorI16::new(),
+ })),
+ _ => internal_err!("unsupported small int type: {}", data_type),
+ }
+}
+
+#[cold]
+fn get_small_int_state_field(name: &str, data_type: &DataType) -> Result<Vec<FieldRef>> {
+ Ok(vec![
+ Field::new_list(
+ format_state_name(name, "approx_distinct"),
+ Field::new_list_field(data_type.clone(), true),
+ false,
+ )
+ .into(),
+ ])
+}
+
impl AggregateUDFImpl for ApproxDistinct {
fn name(&self) -> &str {
"approx_distinct"
@@ -316,24 +382,27 @@ impl AggregateUDFImpl for ApproxDistinct {
}
fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
- if args.input_fields[0].data_type().is_null() {
- Ok(vec![
+ let data_type = args.input_fields[0].data_type();
+ match data_type {
+ DataType::Null => Ok(vec![
Field::new(
format_state_name(args.name, self.name()),
DataType::Null,
true,
)
.into(),
- ])
- } else {
- Ok(vec![
+ ]),
+ DataType::UInt8 | DataType::Int8 | DataType::UInt16 | DataType::Int16 => {
+ get_small_int_state_field(args.name, data_type)
+ }
+ _ => Ok(vec![
Field::new(
format_state_name(args.name, "hll_registers"),
DataType::Binary,
false,
)
.into(),
- ])
+ ]),
}
}
@@ -341,15 +410,11 @@ impl AggregateUDFImpl for ApproxDistinct {
let data_type = acc_args.expr_fields[0].data_type();
let accumulator: Box<dyn Accumulator> = match data_type {
- // TODO u8, i8, u16, i16 shall really be done using bitmap, not HLL
- // TODO support for boolean (trivial case)
- // https://github.com/apache/datafusion/issues/1109
- DataType::UInt8 => Box::new(NumericHLLAccumulator::<UInt8Type>::new()),
- DataType::UInt16 => Box::new(NumericHLLAccumulator::<UInt16Type>::new()),
+ DataType::UInt8 | DataType::Int8 | DataType::UInt16 | DataType::Int16 => {
+ return get_small_int_approx_accumulator(data_type);
+ }
DataType::UInt32 => Box::new(NumericHLLAccumulator::<UInt32Type>::new()),
DataType::UInt64 => Box::new(NumericHLLAccumulator::<UInt64Type>::new()),
- DataType::Int8 => Box::new(NumericHLLAccumulator::<Int8Type>::new()),
- DataType::Int16 => Box::new(NumericHLLAccumulator::<Int16Type>::new()),
DataType::Int32 => Box::new(NumericHLLAccumulator::<Int32Type>::new()),
DataType::Int64 => Box::new(NumericHLLAccumulator::<Int64Type>::new()),
DataType::Date32 => Box::new(NumericHLLAccumulator::<Date32Type>::new()),
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org