Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,13 @@

mod bytes;
mod dict;
mod groups;
mod native;

pub use bytes::BytesDistinctCountAccumulator;
pub use bytes::BytesViewDistinctCountAccumulator;
pub use dict::DictionaryCountAccumulator;
pub use groups::PrimitiveDistinctCountGroupsAccumulator;
pub use native::Bitmap65536DistinctCountAccumulator;
pub use native::Bitmap65536DistinctCountAccumulatorI16;
pub use native::BoolArray256DistinctCountAccumulator;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
// 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.

use arrow::array::{
ArrayRef, AsArray, BooleanArray, Int64Array, ListArray, PrimitiveArray,
};
use arrow::buffer::OffsetBuffer;
use arrow::datatypes::{ArrowPrimitiveType, Field};
use datafusion_common::HashSet;
use datafusion_common::hash_utils::RandomState;
use datafusion_expr_common::groups_accumulator::{EmitTo, GroupsAccumulator};
use std::hash::Hash;
use std::mem::size_of;
use std::sync::Arc;

use crate::aggregate::groups_accumulator::accumulate::accumulate;

pub struct PrimitiveDistinctCountGroupsAccumulator<T: ArrowPrimitiveType>
where
T::Native: Eq + Hash,
{
seen: HashSet<(usize, T::Native), RandomState>,
counts: Vec<i64>,
}

impl<T: ArrowPrimitiveType> PrimitiveDistinctCountGroupsAccumulator<T>
where
T::Native: Eq + Hash,
{
pub fn new() -> Self {
Self {
seen: HashSet::default(),
counts: Vec::new(),
}
}
}

impl<T: ArrowPrimitiveType> Default for PrimitiveDistinctCountGroupsAccumulator<T>
where
T::Native: Eq + Hash,
{
fn default() -> Self {
Self::new()
}
}

impl<T: ArrowPrimitiveType + Send + std::fmt::Debug> GroupsAccumulator
for PrimitiveDistinctCountGroupsAccumulator<T>
where
T::Native: Eq + Hash,
{
fn update_batch(
&mut self,
values: &[ArrayRef],
group_indices: &[usize],
opt_filter: Option<&BooleanArray>,
total_num_groups: usize,
) -> datafusion_common::Result<()> {
debug_assert_eq!(values.len(), 1);
self.counts.resize(total_num_groups, 0);
let arr = values[0].as_primitive::<T>();
accumulate(group_indices, arr, opt_filter, |group_idx, value| {
if self.seen.insert((group_idx, value)) {
self.counts[group_idx] += 1;
}
});
Ok(())
}

fn evaluate(&mut self, emit_to: EmitTo) -> datafusion_common::Result<ArrayRef> {
let counts = emit_to.take_needed(&mut self.counts);

match emit_to {
EmitTo::All => {
self.seen.clear();
}
EmitTo::First(n) => {
let mut remaining = HashSet::default();
for (group_idx, value) in self.seen.drain() {
if group_idx >= n {
remaining.insert((group_idx - n, value));
}
}
self.seen = remaining;
}
}

Ok(Arc::new(Int64Array::from(counts)))
}

fn state(&mut self, emit_to: EmitTo) -> datafusion_common::Result<Vec<ArrayRef>> {
let num_emitted = match emit_to {
EmitTo::All => self.counts.len(),
EmitTo::First(n) => n,
};

let mut group_values: Vec<Vec<T::Native>> = vec![Vec::new(); num_emitted];

if matches!(emit_to, EmitTo::All) {
for (group_idx, value) in self.seen.drain() {
group_values[group_idx].push(value);
}
self.counts.clear();
} else {
let mut remaining = HashSet::default();
for (group_idx, value) in self.seen.drain() {
if group_idx < num_emitted {
group_values[group_idx].push(value);
} else {
remaining.insert((group_idx - num_emitted, value));
}
}
self.seen = remaining;
let _ = emit_to.take_needed(&mut self.counts);
}

let mut offsets = vec![0i32];
let mut all_values = Vec::new();
for values in &group_values {
all_values.extend(values.iter().copied());
offsets.push(all_values.len() as i32);
}

let values_array = Arc::new(PrimitiveArray::<T>::from_iter_values(all_values));
let list_array = ListArray::new(
Arc::new(Field::new_list_field(T::DATA_TYPE, true)),
OffsetBuffer::new(offsets.into()),
values_array,
None,
);

Ok(vec![Arc::new(list_array)])
}

fn merge_batch(
&mut self,
values: &[ArrayRef],
group_indices: &[usize],
_opt_filter: Option<&BooleanArray>,
total_num_groups: usize,
) -> datafusion_common::Result<()> {
debug_assert_eq!(values.len(), 1);
self.counts.resize(total_num_groups, 0);
let list_array = values[0].as_list::<i32>();

for (row_idx, &group_idx) in group_indices.iter().enumerate() {
let inner = list_array.value(row_idx);
let inner_arr = inner.as_primitive::<T>();
for &value in inner_arr.values().iter() {
if self.seen.insert((group_idx, value)) {
self.counts[group_idx] += 1;
}
}
}

Ok(())
}

fn size(&self) -> usize {
size_of::<Self>()
+ self.seen.capacity() * (size_of::<(usize, T::Native)>() + size_of::<u64>())
+ self.counts.capacity() * size_of::<i64>()
}
}
132 changes: 129 additions & 3 deletions datafusion/functions-aggregate/benches/count_distinct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@
use std::sync::Arc;

use arrow::array::{
ArrayRef, Int8Array, Int16Array, Int64Array, UInt8Array, UInt16Array,
Array, ArrayRef, Int8Array, Int16Array, Int64Array, UInt8Array, UInt16Array,
};
use arrow::datatypes::{DataType, Field, Schema};
use criterion::{Criterion, criterion_group, criterion_main};
use datafusion_expr::function::AccumulatorArgs;
use datafusion_expr::{Accumulator, AggregateUDFImpl};
use datafusion_expr::{Accumulator, AggregateUDFImpl, EmitTo};
use datafusion_functions_aggregate::count::Count;
use datafusion_physical_expr::expressions::col;
use rand::rngs::StdRng;
Expand Down Expand Up @@ -87,6 +87,30 @@ fn create_i16_array(n_distinct: usize) -> Int16Array {
.collect()
}

fn prepare_args(data_type: DataType) -> (Arc<Schema>, AccumulatorArgs<'static>) {
let schema = Arc::new(Schema::new(vec![Field::new("f", data_type, true)]));
let schema_leaked: &'static Schema = Box::leak(Box::new((*schema).clone()));
let expr = col("f", schema_leaked).unwrap();
let expr_leaked: &'static _ = Box::leak(Box::new(expr));
let return_field: Arc<Field> = Field::new("f", DataType::Int64, true).into();
let return_field_leaked: &'static _ = Box::leak(Box::new(return_field.clone()));
let expr_field = expr_leaked.return_field(schema_leaked).unwrap();
let expr_field_leaked: &'static _ = Box::leak(Box::new(expr_field));

let accumulator_args = AccumulatorArgs {
return_field: return_field_leaked.clone(),
schema: schema_leaked,
expr_fields: std::slice::from_ref(expr_field_leaked),
ignore_nulls: false,
order_bys: &[],
is_reversed: false,
name: "count(distinct f)",
is_distinct: true,
exprs: std::slice::from_ref(expr_leaked),
};
(schema, accumulator_args)
}

fn count_distinct_benchmark(c: &mut Criterion) {
for pct in [80, 99] {
let n_distinct = BATCH_SIZE * pct / 100;
Expand Down Expand Up @@ -150,5 +174,107 @@ fn count_distinct_benchmark(c: &mut Criterion) {
});
}

criterion_group!(benches, count_distinct_benchmark);
/// Create group indices with uniform distribution
fn create_uniform_groups(num_groups: usize) -> Vec<usize> {
let mut rng = StdRng::seed_from_u64(42);
(0..BATCH_SIZE)
.map(|_| rng.random_range(0..num_groups))
.collect()
}

/// Create group indices with skewed distribution (80% in 20% of groups)
fn create_skewed_groups(num_groups: usize) -> Vec<usize> {
let mut rng = StdRng::seed_from_u64(42);
let hot_groups = (num_groups / 5).max(1);
(0..BATCH_SIZE)
.map(|_| {
if rng.random_range(0..100) < 80 {
rng.random_range(0..hot_groups)
} else {
rng.random_range(0..num_groups)
}
})
.collect()
}

fn count_distinct_groups_benchmark(c: &mut Criterion) {
let count_fn = Count::new();

let group_counts = [100, 1000, 10000];
let cardinalities = [("low", 20), ("mid", 80), ("high", 99)];
let distributions = ["uniform", "skewed"];

for num_groups in group_counts {
for (card_name, distinct_pct) in cardinalities {
for dist in distributions {
let name = format!("g{num_groups}_{card_name}_{dist}");
let n_distinct = BATCH_SIZE * distinct_pct / 100;
let values = Arc::new(create_i64_array(n_distinct)) as ArrayRef;
let group_indices = if dist == "uniform" {
create_uniform_groups(num_groups)
} else {
create_skewed_groups(num_groups)
};

let (_schema, args) = prepare_args(DataType::Int64);

if count_fn.groups_accumulator_supported(args.clone()) {
c.bench_function(&format!("count_distinct_groups {name}"), |b| {
b.iter(|| {
let mut acc =
count_fn.create_groups_accumulator(args.clone()).unwrap();
acc.update_batch(
std::slice::from_ref(&values),
&group_indices,
None,
num_groups,
)
.unwrap();
acc.evaluate(EmitTo::All).unwrap()
})
});
} else {
let arr = values.as_any().downcast_ref::<Int64Array>().unwrap();
let mut group_rows: Vec<Vec<i64>> = vec![Vec::new(); num_groups];
for (idx, &group_idx) in group_indices.iter().enumerate() {
if arr.is_valid(idx) {
group_rows[group_idx].push(arr.value(idx));
}
}
let group_arrays: Vec<ArrayRef> = group_rows
.iter()
.map(|rows| Arc::new(Int64Array::from(rows.clone())) as ArrayRef)
.collect();

c.bench_function(&format!("count_distinct_groups {name}"), |b| {
b.iter(|| {
let mut accumulators: Vec<_> = (0..num_groups)
.map(|_| prepare_accumulator(DataType::Int64))
.collect();

for (group_idx, batch) in group_arrays.iter().enumerate() {
if !batch.is_empty() {
accumulators[group_idx]
.update_batch(std::slice::from_ref(batch))
.unwrap();
}
}

let _results: Vec<_> = accumulators
.iter_mut()
.map(|acc| acc.evaluate().unwrap())
.collect();
})
});
}
}
}
}
}

criterion_group!(
benches,
count_distinct_benchmark,
count_distinct_groups_benchmark
);
criterion_main!(benches);
Loading
Loading