datafusion_functions_aggregate_common/aggregate/count_distinct/
bytes.rs1use arrow::array::{ArrayRef, OffsetSizeTrait};
8use datafusion_common::ScalarValue;
9use datafusion_common::cast::as_list_array;
10use datafusion_common::utils::SingleRowListArrayBuilder;
11use datafusion_expr_common::accumulator::Accumulator;
12use datafusion_physical_expr_common::binary_map::{ArrowBytesSet, OutputType};
13use datafusion_physical_expr_common::binary_view_map::ArrowBytesViewSet;
14use std::fmt::Debug;
15use std::mem::size_of_val;
16
17#[derive(Debug)]
26pub struct BytesDistinctCountAccumulator<O: OffsetSizeTrait>(ArrowBytesSet<O>);
27
28impl<O: OffsetSizeTrait> BytesDistinctCountAccumulator<O> {
29 pub fn new(output_type: OutputType) -> Self {
42 Self(ArrowBytesSet::new(output_type))
43 }
44}
45
46impl<O: OffsetSizeTrait> Accumulator for BytesDistinctCountAccumulator<O> {
47 fn state(&mut self) -> datafusion_common::Result<Vec<ScalarValue>> {
48 let set = self.0.take();
49 let arr = set.into_state();
50 Ok(vec![
51 SingleRowListArrayBuilder::new(arr).build_list_scalar(),
52 ])
53 }
54
55 fn update_batch(&mut self, values: &[ArrayRef]) -> datafusion_common::Result<()> {
56 if values.is_empty() {
57 return Ok(());
58 }
59
60 self.0.insert(&values[0]);
61
62 Ok(())
63 }
64
65 fn merge_batch(&mut self, states: &[ArrayRef]) -> datafusion_common::Result<()> {
66 if states.is_empty() {
67 return Ok(());
68 }
69 assert_eq!(
70 states.len(),
71 1,
72 "count_distinct states must be single array"
73 );
74
75 let arr = as_list_array(&states[0])?;
76 arr.iter().try_for_each(|maybe_list| {
77 if let Some(list) = maybe_list {
78 self.0.insert(&list);
79 }
80 Ok(())
81 })
82 }
83
84 fn evaluate(&mut self) -> datafusion_common::Result<ScalarValue> {
85 Ok(ScalarValue::Int64(Some(self.0.non_null_len() as i64)))
86 }
87
88 fn size(&self) -> usize {
89 size_of_val(self) + self.0.size()
90 }
91}
92
93#[derive(Debug)]
99pub struct BytesViewDistinctCountAccumulator(ArrowBytesViewSet);
100
101impl BytesViewDistinctCountAccumulator {
102 pub fn new(output_type: OutputType) -> Self {
105 Self(ArrowBytesViewSet::new(output_type))
106 }
107}
108
109impl Accumulator for BytesViewDistinctCountAccumulator {
110 fn state(&mut self) -> datafusion_common::Result<Vec<ScalarValue>> {
111 let set = self.0.take();
112 let arr = set.into_state();
113 Ok(vec![
114 SingleRowListArrayBuilder::new(arr).build_list_scalar(),
115 ])
116 }
117
118 fn update_batch(&mut self, values: &[ArrayRef]) -> datafusion_common::Result<()> {
119 if values.is_empty() {
120 return Ok(());
121 }
122
123 self.0.insert(&values[0]);
124
125 Ok(())
126 }
127
128 fn merge_batch(&mut self, states: &[ArrayRef]) -> datafusion_common::Result<()> {
129 if states.is_empty() {
130 return Ok(());
131 }
132 assert_eq!(
133 states.len(),
134 1,
135 "count_distinct states must be single array"
136 );
137
138 let arr = as_list_array(&states[0])?;
139 arr.iter().try_for_each(|maybe_list| {
140 if let Some(list) = maybe_list {
141 self.0.insert(&list);
142 }
143 Ok(())
144 })
145 }
146
147 fn evaluate(&mut self) -> datafusion_common::Result<ScalarValue> {
148 Ok(ScalarValue::Int64(Some(self.0.non_null_len() as i64)))
149 }
150
151 fn size(&self) -> usize {
152 size_of_val(self) + self.0.size()
153 }
154}
155
156#[cfg(all(test, not(feature = "force_hash_collisions")))]
166mod tests {
167 use super::*;
168 use arrow::array::{StringArray, StringViewArray};
169 use datafusion_physical_expr_common::binary_map::INITIAL_MAP_CAPACITY;
170 use datafusion_physical_expr_common::binary_view_map::INITIAL_MAP_CAPACITY as INITIAL_VIEW_MAP_CAPACITY;
171 use std::sync::Arc;
172
173 const BATCH_SIZE: usize = 8192;
175
176 const CARDINALITIES: [usize; 7] = [0, 1, 100, 1_000, 10_000, 100_000, 500_000];
179
180 const PER_GROUP_SCALE: usize = 100;
184
185 const UNGROUPED_SCALE: usize = 10_000;
189
190 fn distinct_value(i: usize) -> String {
193 format!("distinct value number {i}")
194 }
195
196 fn batches(distinct_values: usize, view: bool) -> Vec<ArrayRef> {
197 (0..distinct_values)
198 .step_by(BATCH_SIZE)
199 .map(|start| {
200 let values = (start..(start + BATCH_SIZE).min(distinct_values))
201 .map(distinct_value);
202 if view {
203 Arc::new(StringViewArray::from_iter_values(values)) as ArrayRef
204 } else {
205 Arc::new(StringArray::from_iter_values(values)) as ArrayRef
206 }
207 })
208 .collect()
209 }
210
211 fn assert_lazy_is_not_worse(
214 distinct_values: usize,
215 lazy_size: usize,
216 pre_allocated_size: usize,
217 ) {
218 assert!(
220 lazy_size <= pre_allocated_size,
221 "at {distinct_values} distinct values the lazy set reported \
222 {lazy_size} bytes against the {pre_allocated_size} bytes the \
223 pre-allocated one reported"
224 );
225
226 if distinct_values <= PER_GROUP_SCALE {
227 assert!(
230 lazy_size < pre_allocated_size,
231 "at {distinct_values} distinct values the lazy set should be \
232 strictly cheaper, but reported {lazy_size} bytes against \
233 {pre_allocated_size}"
234 );
235 }
236
237 if distinct_values >= UNGROUPED_SCALE {
238 assert_eq!(
245 lazy_size, pre_allocated_size,
246 "at {distinct_values} distinct values the lazy and pre-allocated \
247 sets should have converged"
248 );
249 }
250 }
251
252 #[test]
256 fn ungrouped_utf8_accumulator_is_never_worse_than_a_pre_allocated_set() {
257 for distinct_values in CARDINALITIES {
258 let mut accumulator =
259 BytesDistinctCountAccumulator::<i32>::new(OutputType::Utf8);
260 let mut pre_allocated = ArrowBytesSet::<i32>::with_capacity(
261 OutputType::Utf8,
262 INITIAL_MAP_CAPACITY,
263 );
264
265 for batch in batches(distinct_values, false) {
266 accumulator.update_batch(&[Arc::clone(&batch)]).unwrap();
267 pre_allocated.insert(&batch);
268 }
269
270 assert_eq!(accumulator.0.non_null_len(), distinct_values);
271 assert_lazy_is_not_worse(
272 distinct_values,
273 accumulator.0.size(),
274 pre_allocated.size(),
275 );
276 }
277 }
278
279 #[test]
282 fn ungrouped_utf8_view_accumulator_is_never_worse_than_a_pre_allocated_set() {
283 for distinct_values in CARDINALITIES {
284 let mut accumulator =
285 BytesViewDistinctCountAccumulator::new(OutputType::Utf8View);
286 let mut pre_allocated = ArrowBytesViewSet::with_capacity(
287 OutputType::Utf8View,
288 INITIAL_VIEW_MAP_CAPACITY,
289 );
290
291 for batch in batches(distinct_values, true) {
292 accumulator.update_batch(&[Arc::clone(&batch)]).unwrap();
293 pre_allocated.insert(&batch);
294 }
295
296 assert_eq!(accumulator.0.non_null_len(), distinct_values);
297 assert_lazy_is_not_worse(
298 distinct_values,
299 accumulator.0.size(),
300 pre_allocated.size(),
301 );
302 }
303 }
304}