Skip to content

Commit 5bb1c4f

Browse files
alexanderbianchiLiaCastaneda
authored andcommitted
dictionary encoded group by's
1 parent 25799f5 commit 5bb1c4f

5 files changed

Lines changed: 603 additions & 198 deletions

File tree

‎datafusion/physical-plan/Cargo.toml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,3 +101,8 @@ name = "sort_preserving_merge"
101101
harness = false
102102
name = "aggregate_vectorized"
103103
required-features = ["test_utils"]
104+
105+
[[bench]]
106+
harness = false
107+
name = "dict_group_values"
108+
required-features = ["test_utils"]
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
// Licensed to the Apache Software Foundation (ASF) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The ASF licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// with the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
18+
//! Benchmarks for GROUP BY on dictionary-encoded columns.
19+
//!
20+
//! Compares three paths:
21+
//! - `column_utf8`: GroupValuesColumn with plain Utf8 (fast-path baseline)
22+
//! - `column_dict`: GroupValuesColumn with Dictionary(Int32, Utf8) (new path)
23+
//! - `rows_dict`: GroupValuesRows with Dictionary(Int32, Utf8) (old fallback)
24+
25+
use std::sync::Arc;
26+
27+
use arrow::array::{ArrayRef, StringArray};
28+
use arrow::compute::cast;
29+
use arrow::datatypes::{DataType, Field, Schema};
30+
use criterion::{
31+
BenchmarkId, Criterion, criterion_group, criterion_main,
32+
};
33+
use datafusion_physical_plan::aggregates::group_values::multi_group_by::GroupValuesColumn;
34+
use datafusion_physical_plan::aggregates::group_values::row::GroupValuesRows;
35+
use datafusion_physical_plan::aggregates::group_values::GroupValues;
36+
use rand::Rng;
37+
use rand::rngs::StdRng;
38+
use rand::SeedableRng;
39+
40+
const CARDINALITIES: [usize; 3] = [50, 1_000, 10_000];
41+
const BATCH_SIZES: [usize; 2] = [8_192, 65_536];
42+
const NUM_BATCHES: usize = 10;
43+
44+
/// Generate `num_rows` random string values chosen from `cardinality` distinct strings,
45+
/// returned as both plain Utf8 and Dictionary(Int32, Utf8) arrays.
46+
fn generate_string_batches(
47+
num_rows: usize,
48+
cardinality: usize,
49+
seed: u64,
50+
) -> (ArrayRef, ArrayRef) {
51+
let mut rng = StdRng::seed_from_u64(seed);
52+
53+
// Build a pool of distinct strings
54+
let pool: Vec<String> = (0..cardinality)
55+
.map(|i| format!("group_value_{i:06}"))
56+
.collect();
57+
58+
let values: Vec<&str> = (0..num_rows)
59+
.map(|_| pool[rng.random_range(0..cardinality)].as_str())
60+
.collect();
61+
62+
let utf8_array: ArrayRef = Arc::new(StringArray::from(values));
63+
let dict_array = cast(&utf8_array, &DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)))
64+
.expect("cast to dictionary");
65+
66+
(utf8_array, dict_array)
67+
}
68+
69+
fn bench_dict_group_values(c: &mut Criterion) {
70+
let mut group = c.benchmark_group("dict_group_values");
71+
72+
for &cardinality in &CARDINALITIES {
73+
for &batch_size in &BATCH_SIZES {
74+
// Pre-generate batches (both utf8 and dict variants)
75+
let batches: Vec<(ArrayRef, ArrayRef)> = (0..NUM_BATCHES as u64)
76+
.map(|seed| generate_string_batches(batch_size, cardinality, seed))
77+
.collect();
78+
79+
let param = format!("card_{cardinality}/batch_{batch_size}");
80+
81+
// ---- column_utf8: GroupValuesColumn with plain Utf8 (baseline fast path) ----
82+
{
83+
let schema = Arc::new(Schema::new(vec![
84+
Field::new("key", DataType::Utf8, false),
85+
]));
86+
let id = BenchmarkId::new("column_utf8", &param);
87+
group.bench_function(id, |b| {
88+
b.iter(|| {
89+
let mut gv = GroupValuesColumn::<false>::try_new(Arc::clone(&schema)).unwrap();
90+
let mut groups = Vec::new();
91+
for (utf8, _dict) in &batches {
92+
gv.intern(&[Arc::clone(utf8)], &mut groups).unwrap();
93+
}
94+
});
95+
});
96+
}
97+
98+
// ---- column_dict: GroupValuesColumn with Dictionary(Int32, Utf8) (new path) ----
99+
{
100+
let schema = Arc::new(Schema::new(vec![
101+
Field::new(
102+
"key",
103+
DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
104+
false,
105+
),
106+
]));
107+
let id = BenchmarkId::new("column_dict", &param);
108+
group.bench_function(id, |b| {
109+
b.iter(|| {
110+
let mut gv = GroupValuesColumn::<false>::try_new(Arc::clone(&schema)).unwrap();
111+
let mut groups = Vec::new();
112+
for (_utf8, dict) in &batches {
113+
gv.intern(&[Arc::clone(dict)], &mut groups).unwrap();
114+
}
115+
});
116+
});
117+
}
118+
119+
// ---- rows_dict: GroupValuesRows with Dictionary(Int32, Utf8) (old fallback) ----
120+
{
121+
let schema = Arc::new(Schema::new(vec![
122+
Field::new(
123+
"key",
124+
DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
125+
false,
126+
),
127+
]));
128+
let id = BenchmarkId::new("rows_dict", &param);
129+
group.bench_function(id, |b| {
130+
b.iter(|| {
131+
let mut gv = GroupValuesRows::try_new(Arc::clone(&schema)).unwrap();
132+
let mut groups = Vec::new();
133+
for (_utf8, dict) in &batches {
134+
gv.intern(&[Arc::clone(dict)], &mut groups).unwrap();
135+
}
136+
});
137+
});
138+
}
139+
}
140+
}
141+
142+
group.finish();
143+
}
144+
145+
criterion_group!(benches, bench_dict_group_values);
146+
criterion_main!(benches);

‎datafusion/physical-plan/src/aggregates/group_values/mod.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ use datafusion_expr::EmitTo;
3030

3131
pub mod multi_group_by;
3232

33-
mod row;
33+
pub mod row;
3434
mod single_group_by;
3535
use datafusion_physical_expr::binary_map::OutputType;
3636
use multi_group_by::GroupValuesColumn;
Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
// Licensed to the Apache Software Foundation (ASF) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The ASF licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// with the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
18+
//! [`DictionaryGroupValueBuilder`] for dictionary-encoded GROUP BY columns.
19+
20+
use std::marker::PhantomData;
21+
22+
use arrow::array::{Array, ArrayRef, DictionaryArray, new_null_array};
23+
use arrow::datatypes::{ArrowDictionaryKeyType, ArrowNativeType, DataType};
24+
use datafusion_common::Result;
25+
26+
use super::GroupColumn;
27+
28+
/// A [`GroupColumn`] wrapper that transparently handles dictionary-encoded
29+
/// input arrays by resolving dictionary keys on-demand.
30+
///
31+
/// Instead of materializing the full decoded array via `cast()` (which copies
32+
/// O(batch_size) strings per batch), this builder looks up values through
33+
/// dictionary keys, only copying data for rows that are actually appended as
34+
/// new groups. Comparisons index directly into the dictionary's values array.
35+
///
36+
/// The inner builder stores decoded values. On emit, the existing code in
37+
/// [`GroupValuesColumn::emit`] re-encodes back to dictionary via `cast()`.
38+
///
39+
/// [`GroupValuesColumn::emit`]: super::GroupValuesColumn
40+
pub struct DictionaryGroupValueBuilder<K: ArrowDictionaryKeyType> {
41+
/// Inner builder that operates on the dictionary's value type
42+
inner: Box<dyn GroupColumn>,
43+
/// A single-element null array of the value type, used to represent null
44+
/// dictionary keys to the inner builder
45+
null_array: ArrayRef,
46+
_phantom: PhantomData<K>,
47+
}
48+
49+
impl<K: ArrowDictionaryKeyType> DictionaryGroupValueBuilder<K> {
50+
pub fn new(inner: Box<dyn GroupColumn>, value_type: &DataType) -> Self {
51+
let null_array = new_null_array(value_type, 1);
52+
Self {
53+
inner,
54+
null_array,
55+
_phantom: PhantomData,
56+
}
57+
}
58+
}
59+
60+
impl<K: ArrowDictionaryKeyType + Send + Sync> GroupColumn for DictionaryGroupValueBuilder<K> {
61+
fn equal_to(&self, lhs_row: usize, array: &ArrayRef, rhs_row: usize) -> bool {
62+
let dict = array
63+
.as_any()
64+
.downcast_ref::<DictionaryArray<K>>()
65+
.unwrap();
66+
if dict.is_null(rhs_row) {
67+
return self.inner.equal_to(lhs_row, &self.null_array, 0);
68+
}
69+
let key = dict.keys().value(rhs_row).as_usize();
70+
self.inner.equal_to(lhs_row, dict.values(), key)
71+
}
72+
73+
fn append_val(&mut self, array: &ArrayRef, row: usize) -> Result<()> {
74+
let dict = array
75+
.as_any()
76+
.downcast_ref::<DictionaryArray<K>>()
77+
.unwrap();
78+
if dict.is_null(row) {
79+
return self.inner.append_val(&self.null_array, 0);
80+
}
81+
let key = dict.keys().value(row).as_usize();
82+
self.inner.append_val(dict.values(), key)
83+
}
84+
85+
fn vectorized_equal_to(
86+
&self,
87+
lhs_rows: &[usize],
88+
array: &ArrayRef,
89+
rhs_rows: &[usize],
90+
equal_to_results: &mut [bool],
91+
) {
92+
let dict = array
93+
.as_any()
94+
.downcast_ref::<DictionaryArray<K>>()
95+
.unwrap();
96+
let keys = dict.keys();
97+
let values = dict.values();
98+
99+
if dict.null_count() == 0 {
100+
// Fast path: no null keys, remap indices and delegate to inner
101+
let mapped_rhs: Vec<usize> = rhs_rows
102+
.iter()
103+
.map(|&row| keys.value(row).as_usize())
104+
.collect();
105+
self.inner
106+
.vectorized_equal_to(lhs_rows, values, &mapped_rhs, equal_to_results);
107+
} else {
108+
// Null keys present: fall back to scalar comparison
109+
for (i, (&lhs_row, &rhs_row)) in
110+
lhs_rows.iter().zip(rhs_rows.iter()).enumerate()
111+
{
112+
if !equal_to_results[i] {
113+
continue;
114+
}
115+
if dict.is_null(rhs_row) {
116+
equal_to_results[i] =
117+
self.inner.equal_to(lhs_row, &self.null_array, 0);
118+
} else {
119+
let key = keys.value(rhs_row).as_usize();
120+
equal_to_results[i] =
121+
self.inner.equal_to(lhs_row, values, key);
122+
}
123+
}
124+
}
125+
}
126+
127+
fn vectorized_append(&mut self, array: &ArrayRef, rows: &[usize]) -> Result<()> {
128+
let dict = array
129+
.as_any()
130+
.downcast_ref::<DictionaryArray<K>>()
131+
.unwrap();
132+
let keys = dict.keys();
133+
let values = dict.values();
134+
135+
if dict.null_count() == 0 {
136+
// Fast path: no null keys, remap indices and delegate to inner
137+
let mapped_rows: Vec<usize> = rows
138+
.iter()
139+
.map(|&row| keys.value(row).as_usize())
140+
.collect();
141+
self.inner.vectorized_append(values, &mapped_rows)
142+
} else {
143+
// Null keys present: process in order, chunking consecutive
144+
// non-null rows for vectorized processing
145+
let mut i = 0;
146+
while i < rows.len() {
147+
if dict.is_null(rows[i]) {
148+
self.inner.append_val(&self.null_array, 0)?;
149+
i += 1;
150+
} else {
151+
// Collect consecutive non-null rows
152+
let mut chunk = Vec::new();
153+
while i < rows.len() && !dict.is_null(rows[i]) {
154+
chunk.push(keys.value(rows[i]).as_usize());
155+
i += 1;
156+
}
157+
self.inner.vectorized_append(values, &chunk)?;
158+
}
159+
}
160+
Ok(())
161+
}
162+
}
163+
164+
fn len(&self) -> usize {
165+
self.inner.len()
166+
}
167+
168+
fn size(&self) -> usize {
169+
self.inner.size() + self.null_array.get_array_memory_size()
170+
}
171+
172+
fn build(self: Box<Self>) -> ArrayRef {
173+
self.inner.build()
174+
}
175+
176+
fn take_n(&mut self, n: usize) -> ArrayRef {
177+
self.inner.take_n(n)
178+
}
179+
}

0 commit comments

Comments
 (0)