Skip to main content

datafusion_functions_aggregate_common/aggregate/count_distinct/
native.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Specialized implementation of `COUNT DISTINCT` for "Native" arrays such as
6//! [`Int64Array`] and [`Float64Array`]
7//!
8//! [`Int64Array`]: arrow::array::Int64Array
9//! [`Float64Array`]: arrow::array::Float64Array
10use std::collections::HashSet;
11use std::fmt::Debug;
12use std::hash::Hash;
13use std::mem::size_of_val;
14use std::sync::Arc;
15
16use arrow::array::Array;
17use arrow::array::ArrayRef;
18use arrow::array::BooleanArray;
19use arrow::array::PrimitiveArray;
20use arrow::array::types::ArrowPrimitiveType;
21use arrow::datatypes::DataType;
22use datafusion_common::hash_utils::RandomState;
23
24use datafusion_common::ScalarValue;
25use datafusion_common::cast::{as_boolean_array, as_list_array, as_primitive_array};
26use datafusion_common::utils::SingleRowListArrayBuilder;
27use datafusion_common::utils::memory::estimate_memory_size;
28use datafusion_expr_common::accumulator::Accumulator;
29
30use crate::utils::GenericDistinctBuffer;
31
32#[derive(Debug)]
33pub struct PrimitiveDistinctCountAccumulator<T>
34where
35    T: ArrowPrimitiveType + Send,
36    T::Native: Eq + Hash,
37{
38    values: HashSet<T::Native, RandomState>,
39    data_type: DataType,
40}
41
42impl<T> PrimitiveDistinctCountAccumulator<T>
43where
44    T: ArrowPrimitiveType + Send,
45    T::Native: Eq + Hash,
46{
47    pub fn new(data_type: &DataType) -> Self {
48        Self {
49            values: HashSet::default(),
50            data_type: data_type.clone(),
51        }
52    }
53}
54
55impl<T> Accumulator for PrimitiveDistinctCountAccumulator<T>
56where
57    T: ArrowPrimitiveType + Send + Debug,
58    T::Native: Eq + Hash,
59{
60    fn state(&mut self) -> datafusion_common::Result<Vec<ScalarValue>> {
61        let arr = Arc::new(
62            PrimitiveArray::<T>::from_iter_values(self.values.iter().copied())
63                .with_data_type(self.data_type.clone()),
64        );
65        Ok(vec![
66            SingleRowListArrayBuilder::new(arr).build_list_scalar(),
67        ])
68    }
69
70    #[inline(never)]
71    fn update_batch(&mut self, values: &[ArrayRef]) -> datafusion_common::Result<()> {
72        if values.is_empty() {
73            return Ok(());
74        }
75
76        let arr = as_primitive_array::<T>(&values[0])?;
77        if arr.null_count() == 0 {
78            // Fast path: no nulls, so skip the per-element validity check and
79            // insert directly from the values buffer (mirrors `merge_batch`).
80            self.values.extend(arr.values().iter().copied());
81        } else {
82            arr.iter().flatten().for_each(|value| {
83                self.values.insert(value);
84            });
85        }
86
87        Ok(())
88    }
89
90    fn merge_batch(&mut self, states: &[ArrayRef]) -> datafusion_common::Result<()> {
91        if states.is_empty() {
92            return Ok(());
93        }
94        assert_eq!(
95            states.len(),
96            1,
97            "count_distinct states must be single array"
98        );
99
100        let arr = as_list_array(&states[0])?;
101        arr.iter().try_for_each(|maybe_list| {
102            if let Some(list) = maybe_list {
103                let list = as_primitive_array::<T>(&list)?;
104                self.values.extend(list.values())
105            }
106            Ok(())
107        })
108    }
109
110    fn evaluate(&mut self) -> datafusion_common::Result<ScalarValue> {
111        Ok(ScalarValue::Int64(Some(self.values.len() as i64)))
112    }
113
114    fn size(&self) -> usize {
115        let num_elements = self.values.len();
116        let fixed_size = size_of_val(self) + size_of_val(&self.values);
117
118        estimate_memory_size::<T::Native>(num_elements, fixed_size).unwrap()
119    }
120}
121
122#[derive(Debug)]
123pub struct FloatDistinctCountAccumulator<T: ArrowPrimitiveType> {
124    values: GenericDistinctBuffer<T>,
125}
126
127impl<T: ArrowPrimitiveType> FloatDistinctCountAccumulator<T> {
128    pub fn new() -> Self {
129        Self {
130            values: GenericDistinctBuffer::new(T::DATA_TYPE),
131        }
132    }
133}
134
135impl<T: ArrowPrimitiveType> Default for FloatDistinctCountAccumulator<T> {
136    fn default() -> Self {
137        Self::new()
138    }
139}
140
141impl<T: ArrowPrimitiveType + Debug> Accumulator for FloatDistinctCountAccumulator<T> {
142    fn state(&mut self) -> datafusion_common::Result<Vec<ScalarValue>> {
143        self.values.state()
144    }
145
146    #[inline(never)]
147    fn update_batch(&mut self, values: &[ArrayRef]) -> datafusion_common::Result<()> {
148        self.values.update_batch(values)
149    }
150
151    fn merge_batch(&mut self, states: &[ArrayRef]) -> datafusion_common::Result<()> {
152        self.values.merge_batch(states)
153    }
154
155    fn evaluate(&mut self) -> datafusion_common::Result<ScalarValue> {
156        Ok(ScalarValue::Int64(Some(self.values.values.len() as i64)))
157    }
158
159    fn size(&self) -> usize {
160        size_of_val(self) + self.values.size()
161    }
162}
163
164/// Optimized COUNT DISTINCT accumulator for u8 using a bool array.
165/// Uses 256 bytes to track all possible u8 values.
166#[derive(Debug)]
167pub struct BoolArray256DistinctCountAccumulator {
168    seen: [bool; 256],
169}
170
171impl BoolArray256DistinctCountAccumulator {
172    pub fn new() -> Self {
173        Self { seen: [false; 256] }
174    }
175
176    #[inline]
177    fn count(&self) -> i64 {
178        self.seen.iter().filter(|&&b| b).count() as i64
179    }
180}
181
182impl Default for BoolArray256DistinctCountAccumulator {
183    fn default() -> Self {
184        Self::new()
185    }
186}
187
188impl Accumulator for BoolArray256DistinctCountAccumulator {
189    #[inline(never)]
190    fn update_batch(&mut self, values: &[ArrayRef]) -> datafusion_common::Result<()> {
191        if values.is_empty() {
192            return Ok(());
193        }
194
195        let arr = as_primitive_array::<arrow::datatypes::UInt8Type>(&values[0])?;
196        for value in arr.iter().flatten() {
197            self.seen[value as usize] = true;
198        }
199        Ok(())
200    }
201
202    fn merge_batch(&mut self, states: &[ArrayRef]) -> datafusion_common::Result<()> {
203        if states.is_empty() {
204            return Ok(());
205        }
206
207        let arr = as_list_array(&states[0])?;
208        arr.iter().try_for_each(|maybe_list| {
209            if let Some(list) = maybe_list {
210                let list = as_primitive_array::<arrow::datatypes::UInt8Type>(&list)?;
211                for value in list.values().iter() {
212                    self.seen[*value as usize] = true;
213                }
214            }
215            Ok(())
216        })
217    }
218
219    fn state(&mut self) -> datafusion_common::Result<Vec<ScalarValue>> {
220        let values: Vec<u8> = self
221            .seen
222            .iter()
223            .enumerate()
224            .filter_map(|(idx, &seen)| if seen { Some(idx as u8) } else { None })
225            .collect();
226
227        let arr = Arc::new(
228            PrimitiveArray::<arrow::datatypes::UInt8Type>::from_iter_values(values),
229        );
230        Ok(vec![
231            SingleRowListArrayBuilder::new(arr).build_list_scalar(),
232        ])
233    }
234
235    fn evaluate(&mut self) -> datafusion_common::Result<ScalarValue> {
236        Ok(ScalarValue::Int64(Some(self.count())))
237    }
238
239    fn size(&self) -> usize {
240        size_of_val(self) + 256
241    }
242}
243
244/// Optimized COUNT DISTINCT accumulator for i8 using a bool array.
245/// Uses 256 bytes to track all possible i8 values (mapped to 0..255).
246#[derive(Debug)]
247pub struct BoolArray256DistinctCountAccumulatorI8 {
248    seen: [bool; 256],
249}
250
251impl BoolArray256DistinctCountAccumulatorI8 {
252    pub fn new() -> Self {
253        Self { seen: [false; 256] }
254    }
255
256    #[inline]
257    fn count(&self) -> i64 {
258        self.seen.iter().filter(|&&b| b).count() as i64
259    }
260}
261
262impl Default for BoolArray256DistinctCountAccumulatorI8 {
263    fn default() -> Self {
264        Self::new()
265    }
266}
267
268impl Accumulator for BoolArray256DistinctCountAccumulatorI8 {
269    #[inline(never)]
270    fn update_batch(&mut self, values: &[ArrayRef]) -> datafusion_common::Result<()> {
271        if values.is_empty() {
272            return Ok(());
273        }
274
275        let arr = as_primitive_array::<arrow::datatypes::Int8Type>(&values[0])?;
276        for value in arr.iter().flatten() {
277            self.seen[value as u8 as usize] = true;
278        }
279        Ok(())
280    }
281
282    fn merge_batch(&mut self, states: &[ArrayRef]) -> datafusion_common::Result<()> {
283        if states.is_empty() {
284            return Ok(());
285        }
286
287        let arr = as_list_array(&states[0])?;
288        arr.iter().try_for_each(|maybe_list| {
289            if let Some(list) = maybe_list {
290                let list = as_primitive_array::<arrow::datatypes::Int8Type>(&list)?;
291                for value in list.values().iter() {
292                    self.seen[*value as u8 as usize] = true;
293                }
294            }
295            Ok(())
296        })
297    }
298
299    fn state(&mut self) -> datafusion_common::Result<Vec<ScalarValue>> {
300        let values: Vec<i8> = self
301            .seen
302            .iter()
303            .enumerate()
304            .filter_map(
305                |(idx, &seen)| {
306                    if seen { Some(idx as u8 as i8) } else { None }
307                },
308            )
309            .collect();
310
311        let arr = Arc::new(
312            PrimitiveArray::<arrow::datatypes::Int8Type>::from_iter_values(values),
313        );
314        Ok(vec![
315            SingleRowListArrayBuilder::new(arr).build_list_scalar(),
316        ])
317    }
318
319    fn evaluate(&mut self) -> datafusion_common::Result<ScalarValue> {
320        Ok(ScalarValue::Int64(Some(self.count())))
321    }
322
323    fn size(&self) -> usize {
324        size_of_val(self) + 256
325    }
326}
327
328/// Optimized COUNT DISTINCT accumulator for u16 using a 65536-bit bitmap.
329/// Uses 8KB (1024 x u64) to track all possible u16 values.
330#[derive(Debug)]
331pub struct Bitmap65536DistinctCountAccumulator {
332    bitmap: Box<[u64; 1024]>,
333}
334
335impl Bitmap65536DistinctCountAccumulator {
336    pub fn new() -> Self {
337        Self {
338            bitmap: Box::new([0; 1024]),
339        }
340    }
341
342    #[inline]
343    fn set_bit(&mut self, value: u16) {
344        let word = (value / 64) as usize;
345        let bit = value % 64;
346        self.bitmap[word] |= 1u64 << bit;
347    }
348
349    #[inline]
350    fn count(&self) -> i64 {
351        self.bitmap.iter().map(|w| w.count_ones() as i64).sum()
352    }
353}
354
355impl Default for Bitmap65536DistinctCountAccumulator {
356    fn default() -> Self {
357        Self::new()
358    }
359}
360
361impl Accumulator for Bitmap65536DistinctCountAccumulator {
362    #[inline(never)]
363    fn update_batch(&mut self, values: &[ArrayRef]) -> datafusion_common::Result<()> {
364        if values.is_empty() {
365            return Ok(());
366        }
367
368        let arr = as_primitive_array::<arrow::datatypes::UInt16Type>(&values[0])?;
369        for value in arr.iter().flatten() {
370            self.set_bit(value);
371        }
372        Ok(())
373    }
374
375    fn merge_batch(&mut self, states: &[ArrayRef]) -> datafusion_common::Result<()> {
376        if states.is_empty() {
377            return Ok(());
378        }
379
380        let arr = as_list_array(&states[0])?;
381        arr.iter().try_for_each(|maybe_list| {
382            if let Some(list) = maybe_list {
383                let list = as_primitive_array::<arrow::datatypes::UInt16Type>(&list)?;
384                for value in list.values().iter() {
385                    self.set_bit(*value);
386                }
387            }
388            Ok(())
389        })
390    }
391
392    fn state(&mut self) -> datafusion_common::Result<Vec<ScalarValue>> {
393        let mut values = Vec::new();
394        for (word_idx, &word) in self.bitmap.iter().enumerate() {
395            if word != 0 {
396                for bit in 0..64 {
397                    if (word & (1u64 << bit)) != 0 {
398                        values.push((word_idx as u16) * 64 + bit);
399                    }
400                }
401            }
402        }
403
404        let arr = Arc::new(
405            PrimitiveArray::<arrow::datatypes::UInt16Type>::from_iter_values(values),
406        );
407        Ok(vec![
408            SingleRowListArrayBuilder::new(arr).build_list_scalar(),
409        ])
410    }
411
412    fn evaluate(&mut self) -> datafusion_common::Result<ScalarValue> {
413        Ok(ScalarValue::Int64(Some(self.count())))
414    }
415
416    fn size(&self) -> usize {
417        size_of_val(self) + 8192
418    }
419}
420
421/// Optimized COUNT DISTINCT accumulator for i16 using a 65536-bit bitmap.
422/// Uses 8KB (1024 x u64) to track all possible i16 values (mapped to 0..65535).
423#[derive(Debug)]
424pub struct Bitmap65536DistinctCountAccumulatorI16 {
425    bitmap: Box<[u64; 1024]>,
426}
427
428impl Bitmap65536DistinctCountAccumulatorI16 {
429    pub fn new() -> Self {
430        Self {
431            bitmap: Box::new([0; 1024]),
432        }
433    }
434
435    #[inline]
436    fn set_bit(&mut self, value: i16) {
437        let idx = value as u16;
438        let word = (idx / 64) as usize;
439        let bit = idx % 64;
440        self.bitmap[word] |= 1u64 << bit;
441    }
442
443    #[inline]
444    fn count(&self) -> i64 {
445        self.bitmap.iter().map(|w| w.count_ones() as i64).sum()
446    }
447}
448
449impl Default for Bitmap65536DistinctCountAccumulatorI16 {
450    fn default() -> Self {
451        Self::new()
452    }
453}
454
455impl Accumulator for Bitmap65536DistinctCountAccumulatorI16 {
456    #[inline(never)]
457    fn update_batch(&mut self, values: &[ArrayRef]) -> datafusion_common::Result<()> {
458        if values.is_empty() {
459            return Ok(());
460        }
461
462        let arr = as_primitive_array::<arrow::datatypes::Int16Type>(&values[0])?;
463        for value in arr.iter().flatten() {
464            self.set_bit(value);
465        }
466        Ok(())
467    }
468
469    fn merge_batch(&mut self, states: &[ArrayRef]) -> datafusion_common::Result<()> {
470        if states.is_empty() {
471            return Ok(());
472        }
473
474        let arr = as_list_array(&states[0])?;
475        arr.iter().try_for_each(|maybe_list| {
476            if let Some(list) = maybe_list {
477                let list = as_primitive_array::<arrow::datatypes::Int16Type>(&list)?;
478                for value in list.values().iter() {
479                    self.set_bit(*value);
480                }
481            }
482            Ok(())
483        })
484    }
485
486    fn state(&mut self) -> datafusion_common::Result<Vec<ScalarValue>> {
487        let mut values = Vec::new();
488        for (word_idx, &word) in self.bitmap.iter().enumerate() {
489            if word != 0 {
490                for bit in 0..64 {
491                    if (word & (1u64 << bit)) != 0 {
492                        values.push(((word_idx as u16) * 64 + bit) as i16);
493                    }
494                }
495            }
496        }
497
498        let arr = Arc::new(
499            PrimitiveArray::<arrow::datatypes::Int16Type>::from_iter_values(values),
500        );
501        Ok(vec![
502            SingleRowListArrayBuilder::new(arr).build_list_scalar(),
503        ])
504    }
505
506    fn evaluate(&mut self) -> datafusion_common::Result<ScalarValue> {
507        Ok(ScalarValue::Int64(Some(self.count())))
508    }
509
510    fn size(&self) -> usize {
511        size_of_val(self) + 8192
512    }
513}
514
515/// Optimized COUNT DISTINCT accumulator for `Boolean` using two flags.
516///
517/// Tracks whether `false` and `true` have been observed; nulls are skipped.
518/// Result is always 0, 1, or 2.
519#[derive(Debug)]
520pub struct BooleanDistinctCountAccumulator {
521    has_seen_false: bool,
522    has_seen_true: bool,
523}
524
525impl BooleanDistinctCountAccumulator {
526    pub fn new() -> Self {
527        Self {
528            has_seen_false: false,
529            has_seen_true: false,
530        }
531    }
532
533    #[inline]
534    fn seen_both(&self) -> bool {
535        self.has_seen_false && self.has_seen_true
536    }
537
538    #[inline]
539    fn count(&self) -> i64 {
540        (self.has_seen_false as u8 + self.has_seen_true as u8) as i64
541    }
542
543    /// Update flags from a `BooleanArray`, short-circuiting per-flag once set.
544    #[inline]
545    fn observe(&mut self, arr: &BooleanArray) {
546        if !self.has_seen_false && arr.has_false() {
547            self.has_seen_false = true;
548        }
549        if !self.has_seen_true && arr.has_true() {
550            self.has_seen_true = true;
551        }
552    }
553}
554
555impl Default for BooleanDistinctCountAccumulator {
556    fn default() -> Self {
557        Self::new()
558    }
559}
560
561impl Accumulator for BooleanDistinctCountAccumulator {
562    fn update_batch(&mut self, values: &[ArrayRef]) -> datafusion_common::Result<()> {
563        if values.is_empty() || self.seen_both() {
564            return Ok(());
565        }
566
567        let arr = as_boolean_array(&values[0])?;
568        self.observe(arr);
569        Ok(())
570    }
571
572    fn merge_batch(&mut self, states: &[ArrayRef]) -> datafusion_common::Result<()> {
573        if states.is_empty() || self.seen_both() {
574            return Ok(());
575        }
576
577        let arr = as_list_array(&states[0])?;
578        arr.iter().try_for_each(|maybe_list| {
579            if self.seen_both() {
580                return Ok(());
581            }
582            if let Some(list) = maybe_list {
583                self.observe(as_boolean_array(&list)?);
584            }
585            Ok(())
586        })
587    }
588
589    fn state(&mut self) -> datafusion_common::Result<Vec<ScalarValue>> {
590        let mut values: Vec<bool> = Vec::with_capacity(2);
591        if self.has_seen_false {
592            values.push(false);
593        }
594        if self.has_seen_true {
595            values.push(true);
596        }
597
598        let arr = Arc::new(BooleanArray::from(values));
599        Ok(vec![
600            SingleRowListArrayBuilder::new(arr).build_list_scalar(),
601        ])
602    }
603
604    fn evaluate(&mut self) -> datafusion_common::Result<ScalarValue> {
605        Ok(ScalarValue::Int64(Some(self.count())))
606    }
607
608    fn size(&self) -> usize {
609        size_of_val(self)
610    }
611}
612
613#[cfg(test)]
614mod tests {
615    use super::*;
616    use arrow::array::Int64Array;
617    use arrow::datatypes::Int64Type;
618
619    #[test]
620    fn update_batch_null_free_fast_path_agrees_with_general_path() {
621        // The null-free fast path must produce the same distinct set as the
622        // general (validity-checking) path.
623        let dense: ArrayRef = Arc::new(Int64Array::from(vec![1, 2, 3, 2, 1]));
624        let sparse: ArrayRef = Arc::new(Int64Array::from(vec![
625            Some(1),
626            None,
627            Some(2),
628            None,
629            Some(3),
630            Some(2),
631            Some(1),
632        ]));
633
634        let mut dense_acc =
635            PrimitiveDistinctCountAccumulator::<Int64Type>::new(&DataType::Int64);
636        dense_acc
637            .update_batch(std::slice::from_ref(&dense))
638            .unwrap();
639
640        let mut sparse_acc =
641            PrimitiveDistinctCountAccumulator::<Int64Type>::new(&DataType::Int64);
642        sparse_acc
643            .update_batch(std::slice::from_ref(&sparse))
644            .unwrap();
645
646        // Both should count the 3 distinct non-null values {1, 2, 3}.
647        assert_eq!(dense_acc.evaluate().unwrap(), ScalarValue::Int64(Some(3)));
648        assert_eq!(sparse_acc.evaluate().unwrap(), ScalarValue::Int64(Some(3)));
649    }
650}