Skip to content

Commit e5d9145

Browse files
authored
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 #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. -->
1 parent 192ceb6 commit e5d9145

1 file changed

Lines changed: 83 additions & 18 deletions

File tree

datafusion/functions-aggregate/src/approx_distinct.rs

Lines changed: 83 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,10 @@ use arrow::array::{
2323
GenericBinaryArray, GenericStringArray, OffsetSizeTrait, PrimitiveArray,
2424
};
2525
use arrow::datatypes::{
26-
ArrowPrimitiveType, Date32Type, Date64Type, FieldRef, Int8Type, Int16Type, Int32Type,
27-
Int64Type, Time32MillisecondType, Time32SecondType, Time64MicrosecondType,
28-
Time64NanosecondType, TimeUnit, TimestampMicrosecondType, TimestampMillisecondType,
29-
TimestampNanosecondType, TimestampSecondType, UInt8Type, UInt16Type, UInt32Type,
30-
UInt64Type,
26+
ArrowPrimitiveType, Date32Type, Date64Type, FieldRef, Int32Type, Int64Type,
27+
Time32MillisecondType, Time32SecondType, Time64MicrosecondType, Time64NanosecondType,
28+
TimeUnit, TimestampMicrosecondType, TimestampMillisecondType,
29+
TimestampNanosecondType, TimestampSecondType, UInt32Type, UInt64Type,
3130
};
3231
use arrow::{array::ArrayRef, datatypes::DataType, datatypes::Field};
3332
use datafusion_common::ScalarValue;
@@ -40,6 +39,10 @@ use datafusion_expr::utils::format_state_name;
4039
use datafusion_expr::{
4140
Accumulator, AggregateUDFImpl, Documentation, Signature, Volatility,
4241
};
42+
use datafusion_functions_aggregate_common::aggregate::count_distinct::{
43+
Bitmap65536DistinctCountAccumulator, Bitmap65536DistinctCountAccumulatorI16,
44+
BoolArray256DistinctCountAccumulator, BoolArray256DistinctCountAccumulatorI8,
45+
};
4346
use datafusion_functions_aggregate_common::noop_accumulator::NoopAccumulator;
4447
use datafusion_macros::user_doc;
4548
use std::fmt::{Debug, Formatter};
@@ -84,6 +87,36 @@ impl<T: Hash + ?Sized> TryFrom<&ScalarValue> for HyperLogLog<T> {
8487
}
8588
}
8689

90+
#[derive(Debug)]
91+
struct ApproxDistinctBitmapWrapper<A: Accumulator> {
92+
inner: A,
93+
}
94+
95+
impl<A: Accumulator> Accumulator for ApproxDistinctBitmapWrapper<A> {
96+
fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
97+
self.inner.update_batch(values)
98+
}
99+
100+
fn evaluate(&mut self) -> Result<ScalarValue> {
101+
match self.inner.evaluate()? {
102+
ScalarValue::Int64(Some(v)) => Ok(ScalarValue::UInt64(Some(v as u64))),
103+
other => internal_err!("unexpected: {other}"),
104+
}
105+
}
106+
107+
fn size(&self) -> usize {
108+
self.inner.size()
109+
}
110+
111+
fn state(&mut self) -> Result<Vec<ScalarValue>> {
112+
self.inner.state()
113+
}
114+
115+
fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
116+
self.inner.merge_batch(states)
117+
}
118+
}
119+
87120
#[derive(Debug)]
88121
struct NumericHLLAccumulator<T>
89122
where
@@ -302,6 +335,39 @@ impl ApproxDistinct {
302335
}
303336
}
304337

338+
#[cold]
339+
fn get_small_int_approx_accumulator(
340+
data_type: &DataType,
341+
) -> Result<Box<dyn Accumulator>> {
342+
match data_type {
343+
DataType::UInt8 => Ok(Box::new(ApproxDistinctBitmapWrapper {
344+
inner: BoolArray256DistinctCountAccumulator::new(),
345+
})),
346+
DataType::Int8 => Ok(Box::new(ApproxDistinctBitmapWrapper {
347+
inner: BoolArray256DistinctCountAccumulatorI8::new(),
348+
})),
349+
DataType::UInt16 => Ok(Box::new(ApproxDistinctBitmapWrapper {
350+
inner: Bitmap65536DistinctCountAccumulator::new(),
351+
})),
352+
DataType::Int16 => Ok(Box::new(ApproxDistinctBitmapWrapper {
353+
inner: Bitmap65536DistinctCountAccumulatorI16::new(),
354+
})),
355+
_ => internal_err!("unsupported small int type: {}", data_type),
356+
}
357+
}
358+
359+
#[cold]
360+
fn get_small_int_state_field(name: &str, data_type: &DataType) -> Result<Vec<FieldRef>> {
361+
Ok(vec![
362+
Field::new_list(
363+
format_state_name(name, "approx_distinct"),
364+
Field::new_list_field(data_type.clone(), true),
365+
false,
366+
)
367+
.into(),
368+
])
369+
}
370+
305371
impl AggregateUDFImpl for ApproxDistinct {
306372
fn name(&self) -> &str {
307373
"approx_distinct"
@@ -316,40 +382,39 @@ impl AggregateUDFImpl for ApproxDistinct {
316382
}
317383

318384
fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
319-
if args.input_fields[0].data_type().is_null() {
320-
Ok(vec![
385+
let data_type = args.input_fields[0].data_type();
386+
match data_type {
387+
DataType::Null => Ok(vec![
321388
Field::new(
322389
format_state_name(args.name, self.name()),
323390
DataType::Null,
324391
true,
325392
)
326393
.into(),
327-
])
328-
} else {
329-
Ok(vec![
394+
]),
395+
DataType::UInt8 | DataType::Int8 | DataType::UInt16 | DataType::Int16 => {
396+
get_small_int_state_field(args.name, data_type)
397+
}
398+
_ => Ok(vec![
330399
Field::new(
331400
format_state_name(args.name, "hll_registers"),
332401
DataType::Binary,
333402
false,
334403
)
335404
.into(),
336-
])
405+
]),
337406
}
338407
}
339408

340409
fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> {
341410
let data_type = acc_args.expr_fields[0].data_type();
342411

343412
let accumulator: Box<dyn Accumulator> = match data_type {
344-
// TODO u8, i8, u16, i16 shall really be done using bitmap, not HLL
345-
// TODO support for boolean (trivial case)
346-
// https://github.com/apache/datafusion/issues/1109
347-
DataType::UInt8 => Box::new(NumericHLLAccumulator::<UInt8Type>::new()),
348-
DataType::UInt16 => Box::new(NumericHLLAccumulator::<UInt16Type>::new()),
413+
DataType::UInt8 | DataType::Int8 | DataType::UInt16 | DataType::Int16 => {
414+
return get_small_int_approx_accumulator(data_type);
415+
}
349416
DataType::UInt32 => Box::new(NumericHLLAccumulator::<UInt32Type>::new()),
350417
DataType::UInt64 => Box::new(NumericHLLAccumulator::<UInt64Type>::new()),
351-
DataType::Int8 => Box::new(NumericHLLAccumulator::<Int8Type>::new()),
352-
DataType::Int16 => Box::new(NumericHLLAccumulator::<Int16Type>::new()),
353418
DataType::Int32 => Box::new(NumericHLLAccumulator::<Int32Type>::new()),
354419
DataType::Int64 => Box::new(NumericHLLAccumulator::<Int64Type>::new()),
355420
DataType::Date32 => Box::new(NumericHLLAccumulator::<Date32Type>::new()),

0 commit comments

Comments
 (0)