Skip to content

Commit 12d82c4

Browse files
Move array ArrayAgg to a UserDefinedAggregate (#11448)
* Add input_nullable to UDAF args StateField/AccumulatorArgs This follows how it done for input_type and only provide a single value. But might need to be changed into a Vec in the future. This is need when we are moving `arrag_agg` to udaf where one of the states nullability will depend on the nullability of the input. * Make ArragAgg (not ordered or distinct) into a UDAF * Add roundtrip_expr_api test case * Address PR comments * Propegate input nullability for aggregates * Remove from accumulator args * first draft Signed-off-by: jayzhan211 <[email protected]> * cleanup Signed-off-by: jayzhan211 <[email protected]> * fix test Signed-off-by: jayzhan211 <[email protected]> * distinct Signed-off-by: jayzhan211 <[email protected]> * fix Signed-off-by: jayzhan211 <[email protected]> * address comment Signed-off-by: jayzhan211 <[email protected]> --------- Signed-off-by: jayzhan211 <[email protected]> Co-authored-by: Emil Ejbyfeldt <[email protected]>
1 parent 723a595 commit 12d82c4

File tree

16 files changed

+328
-892
lines changed

16 files changed

+328
-892
lines changed

datafusion/core/src/dataframe/mod.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -1696,10 +1696,10 @@ mod tests {
16961696
use datafusion_common::{Constraint, Constraints, ScalarValue};
16971697
use datafusion_common_runtime::SpawnedTask;
16981698
use datafusion_expr::{
1699-
array_agg, cast, create_udf, expr, lit, BuiltInWindowFunction,
1700-
ScalarFunctionImplementation, Volatility, WindowFrame, WindowFunctionDefinition,
1699+
cast, create_udf, expr, lit, BuiltInWindowFunction, ScalarFunctionImplementation,
1700+
Volatility, WindowFrame, WindowFunctionDefinition,
17011701
};
1702-
use datafusion_functions_aggregate::expr_fn::count_distinct;
1702+
use datafusion_functions_aggregate::expr_fn::{array_agg, count_distinct};
17031703
use datafusion_physical_expr::expressions::Column;
17041704
use datafusion_physical_plan::{get_plan_string, ExecutionPlanProperties};
17051705

datafusion/core/src/physical_planner.rs

+28
Original file line numberDiff line numberDiff line change
@@ -1839,7 +1839,34 @@ pub fn create_aggregate_expr_with_name_and_maybe_filter(
18391839
.unwrap_or(sqlparser::ast::NullTreatment::RespectNulls)
18401840
== NullTreatment::IgnoreNulls;
18411841

1842+
// TODO: Remove this after array_agg are all udafs
18421843
let (agg_expr, filter, order_by) = match func_def {
1844+
AggregateFunctionDefinition::UDF(udf)
1845+
if udf.name() == "ARRAY_AGG" && order_by.is_some() =>
1846+
{
1847+
// not yet support UDAF, fallback to builtin
1848+
let physical_sort_exprs = match order_by {
1849+
Some(exprs) => Some(create_physical_sort_exprs(
1850+
exprs,
1851+
logical_input_schema,
1852+
execution_props,
1853+
)?),
1854+
None => None,
1855+
};
1856+
let ordering_reqs: Vec<PhysicalSortExpr> =
1857+
physical_sort_exprs.clone().unwrap_or(vec![]);
1858+
let fun = aggregates::AggregateFunction::ArrayAgg;
1859+
let agg_expr = aggregates::create_aggregate_expr(
1860+
&fun,
1861+
*distinct,
1862+
&physical_args,
1863+
&ordering_reqs,
1864+
physical_input_schema,
1865+
name,
1866+
ignore_nulls,
1867+
)?;
1868+
(agg_expr, filter, physical_sort_exprs)
1869+
}
18431870
AggregateFunctionDefinition::BuiltIn(fun) => {
18441871
let physical_sort_exprs = match order_by {
18451872
Some(exprs) => Some(create_physical_sort_exprs(
@@ -1888,6 +1915,7 @@ pub fn create_aggregate_expr_with_name_and_maybe_filter(
18881915
(agg_expr, filter, physical_sort_exprs)
18891916
}
18901917
};
1918+
18911919
Ok((agg_expr, filter, order_by))
18921920
}
18931921
other => internal_err!("Invalid aggregate expression '{other:?}'"),

datafusion/core/tests/dataframe/mod.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -54,11 +54,11 @@ use datafusion_execution::runtime_env::RuntimeEnv;
5454
use datafusion_expr::expr::{GroupingSet, Sort};
5555
use datafusion_expr::var_provider::{VarProvider, VarType};
5656
use datafusion_expr::{
57-
array_agg, cast, col, exists, expr, in_subquery, lit, max, out_ref_col, placeholder,
57+
cast, col, exists, expr, in_subquery, lit, max, out_ref_col, placeholder,
5858
scalar_subquery, when, wildcard, Expr, ExprSchemable, WindowFrame, WindowFrameBound,
5959
WindowFrameUnits, WindowFunctionDefinition,
6060
};
61-
use datafusion_functions_aggregate::expr_fn::{avg, count, sum};
61+
use datafusion_functions_aggregate::expr_fn::{array_agg, avg, count, sum};
6262

6363
#[tokio::test]
6464
async fn test_count_wildcard_on_sort() -> Result<()> {
@@ -1389,7 +1389,7 @@ async fn unnest_with_redundant_columns() -> Result<()> {
13891389
let expected = vec![
13901390
"Projection: shapes.shape_id [shape_id:UInt32]",
13911391
" Unnest: lists[shape_id2] structs[] [shape_id:UInt32, shape_id2:UInt32;N]",
1392-
" Aggregate: groupBy=[[shapes.shape_id]], aggr=[[ARRAY_AGG(shapes.shape_id) AS shape_id2]] [shape_id:UInt32, shape_id2:List(Field { name: \"item\", data_type: UInt32, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} });N]",
1392+
" Aggregate: groupBy=[[shapes.shape_id]], aggr=[[ARRAY_AGG(shapes.shape_id) AS shape_id2]] [shape_id:UInt32, shape_id2:List(Field { name: \"item\", data_type: UInt32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} });N]",
13931393
" TableScan: shapes projection=[shape_id] [shape_id:UInt32]",
13941394
];
13951395

datafusion/expr/src/expr_fn.rs

-12
Original file line numberDiff line numberDiff line change
@@ -171,18 +171,6 @@ pub fn max(expr: Expr) -> Expr {
171171
))
172172
}
173173

174-
/// Create an expression to represent the array_agg() aggregate function
175-
pub fn array_agg(expr: Expr) -> Expr {
176-
Expr::AggregateFunction(AggregateFunction::new(
177-
aggregate_function::AggregateFunction::ArrayAgg,
178-
vec![expr],
179-
false,
180-
None,
181-
None,
182-
None,
183-
))
184-
}
185-
186174
/// Return a new expression with bitwise AND
187175
pub fn bitwise_and(left: Expr, right: Expr) -> Expr {
188176
Expr::BinaryExpr(BinaryExpr::new(
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,261 @@
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+
//! `ARRAY_AGG` aggregate implementation: [`ArrayAgg`]
19+
20+
use arrow::array::{Array, ArrayRef, AsArray};
21+
use arrow::datatypes::DataType;
22+
use arrow_schema::Field;
23+
24+
use datafusion_common::cast::as_list_array;
25+
use datafusion_common::utils::array_into_list_array_nullable;
26+
use datafusion_common::ScalarValue;
27+
use datafusion_common::{internal_err, Result};
28+
use datafusion_expr::function::{AccumulatorArgs, StateFieldsArgs};
29+
use datafusion_expr::utils::format_state_name;
30+
use datafusion_expr::AggregateUDFImpl;
31+
use datafusion_expr::{Accumulator, Signature, Volatility};
32+
use std::collections::HashSet;
33+
use std::sync::Arc;
34+
35+
make_udaf_expr_and_func!(
36+
ArrayAgg,
37+
array_agg,
38+
expression,
39+
"input values, including nulls, concatenated into an array",
40+
array_agg_udaf
41+
);
42+
43+
#[derive(Debug)]
44+
/// ARRAY_AGG aggregate expression
45+
pub struct ArrayAgg {
46+
signature: Signature,
47+
alias: Vec<String>,
48+
}
49+
50+
impl Default for ArrayAgg {
51+
fn default() -> Self {
52+
Self {
53+
signature: Signature::any(1, Volatility::Immutable),
54+
alias: vec!["array_agg".to_string()],
55+
}
56+
}
57+
}
58+
59+
impl AggregateUDFImpl for ArrayAgg {
60+
fn as_any(&self) -> &dyn std::any::Any {
61+
self
62+
}
63+
64+
// TODO: change name to lowercase
65+
fn name(&self) -> &str {
66+
"ARRAY_AGG"
67+
}
68+
69+
fn aliases(&self) -> &[String] {
70+
&self.alias
71+
}
72+
73+
fn signature(&self) -> &Signature {
74+
&self.signature
75+
}
76+
77+
fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
78+
Ok(DataType::List(Arc::new(Field::new(
79+
"item",
80+
arg_types[0].clone(),
81+
true,
82+
))))
83+
}
84+
85+
fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<Field>> {
86+
if args.is_distinct {
87+
return Ok(vec![Field::new_list(
88+
format_state_name(args.name, "distinct_array_agg"),
89+
Field::new("item", args.input_type.clone(), true),
90+
true,
91+
)]);
92+
}
93+
94+
Ok(vec![Field::new_list(
95+
format_state_name(args.name, "array_agg"),
96+
Field::new("item", args.input_type.clone(), true),
97+
true,
98+
)])
99+
}
100+
101+
fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> {
102+
if acc_args.is_distinct {
103+
return Ok(Box::new(DistinctArrayAggAccumulator::try_new(
104+
acc_args.input_type,
105+
)?));
106+
}
107+
108+
Ok(Box::new(ArrayAggAccumulator::try_new(acc_args.input_type)?))
109+
}
110+
}
111+
112+
#[derive(Debug)]
113+
pub struct ArrayAggAccumulator {
114+
values: Vec<ArrayRef>,
115+
datatype: DataType,
116+
}
117+
118+
impl ArrayAggAccumulator {
119+
/// new array_agg accumulator based on given item data type
120+
pub fn try_new(datatype: &DataType) -> Result<Self> {
121+
Ok(Self {
122+
values: vec![],
123+
datatype: datatype.clone(),
124+
})
125+
}
126+
}
127+
128+
impl Accumulator for ArrayAggAccumulator {
129+
fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
130+
// Append value like Int64Array(1,2,3)
131+
if values.is_empty() {
132+
return Ok(());
133+
}
134+
135+
if values.len() != 1 {
136+
return internal_err!("expects single batch");
137+
}
138+
139+
let val = Arc::clone(&values[0]);
140+
if val.len() > 0 {
141+
self.values.push(val);
142+
}
143+
Ok(())
144+
}
145+
146+
fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
147+
// Append value like ListArray(Int64Array(1,2,3), Int64Array(4,5,6))
148+
if states.is_empty() {
149+
return Ok(());
150+
}
151+
152+
if states.len() != 1 {
153+
return internal_err!("expects single state");
154+
}
155+
156+
let list_arr = as_list_array(&states[0])?;
157+
for arr in list_arr.iter().flatten() {
158+
self.values.push(arr);
159+
}
160+
Ok(())
161+
}
162+
163+
fn state(&mut self) -> Result<Vec<ScalarValue>> {
164+
Ok(vec![self.evaluate()?])
165+
}
166+
167+
fn evaluate(&mut self) -> Result<ScalarValue> {
168+
// Transform Vec<ListArr> to ListArr
169+
let element_arrays: Vec<&dyn Array> =
170+
self.values.iter().map(|a| a.as_ref()).collect();
171+
172+
if element_arrays.is_empty() {
173+
return Ok(ScalarValue::new_null_list(self.datatype.clone(), true, 1));
174+
}
175+
176+
let concated_array = arrow::compute::concat(&element_arrays)?;
177+
let list_array = array_into_list_array_nullable(concated_array);
178+
179+
Ok(ScalarValue::List(Arc::new(list_array)))
180+
}
181+
182+
fn size(&self) -> usize {
183+
std::mem::size_of_val(self)
184+
+ (std::mem::size_of::<ArrayRef>() * self.values.capacity())
185+
+ self
186+
.values
187+
.iter()
188+
.map(|arr| arr.get_array_memory_size())
189+
.sum::<usize>()
190+
+ self.datatype.size()
191+
- std::mem::size_of_val(&self.datatype)
192+
}
193+
}
194+
195+
#[derive(Debug)]
196+
struct DistinctArrayAggAccumulator {
197+
values: HashSet<ScalarValue>,
198+
datatype: DataType,
199+
}
200+
201+
impl DistinctArrayAggAccumulator {
202+
pub fn try_new(datatype: &DataType) -> Result<Self> {
203+
Ok(Self {
204+
values: HashSet::new(),
205+
datatype: datatype.clone(),
206+
})
207+
}
208+
}
209+
210+
impl Accumulator for DistinctArrayAggAccumulator {
211+
fn state(&mut self) -> Result<Vec<ScalarValue>> {
212+
Ok(vec![self.evaluate()?])
213+
}
214+
215+
fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
216+
if values.len() != 1 {
217+
return internal_err!("expects single batch");
218+
}
219+
220+
let array = &values[0];
221+
222+
for i in 0..array.len() {
223+
let scalar = ScalarValue::try_from_array(&array, i)?;
224+
self.values.insert(scalar);
225+
}
226+
227+
Ok(())
228+
}
229+
230+
fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
231+
if states.is_empty() {
232+
return Ok(());
233+
}
234+
235+
if states.len() != 1 {
236+
return internal_err!("expects single state");
237+
}
238+
239+
states[0]
240+
.as_list::<i32>()
241+
.iter()
242+
.flatten()
243+
.try_for_each(|val| self.update_batch(&[val]))
244+
}
245+
246+
fn evaluate(&mut self) -> Result<ScalarValue> {
247+
let values: Vec<ScalarValue> = self.values.iter().cloned().collect();
248+
if values.is_empty() {
249+
return Ok(ScalarValue::new_null_list(self.datatype.clone(), true, 1));
250+
}
251+
let arr = ScalarValue::new_list(&values, &self.datatype, true);
252+
Ok(ScalarValue::List(arr))
253+
}
254+
255+
fn size(&self) -> usize {
256+
std::mem::size_of_val(self) + ScalarValue::size_of_hashset(&self.values)
257+
- std::mem::size_of_val(&self.values)
258+
+ self.datatype.size()
259+
- std::mem::size_of_val(&self.datatype)
260+
}
261+
}

datafusion/functions-aggregate/src/lib.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@
5858
pub mod macros;
5959

6060
pub mod approx_distinct;
61+
pub mod array_agg;
6162
pub mod correlation;
6263
pub mod count;
6364
pub mod covariance;
@@ -93,6 +94,7 @@ pub mod expr_fn {
9394
pub use super::approx_median::approx_median;
9495
pub use super::approx_percentile_cont::approx_percentile_cont;
9596
pub use super::approx_percentile_cont_with_weight::approx_percentile_cont_with_weight;
97+
pub use super::array_agg::array_agg;
9698
pub use super::average::avg;
9799
pub use super::bit_and_or_xor::bit_and;
98100
pub use super::bit_and_or_xor::bit_or;
@@ -128,6 +130,7 @@ pub mod expr_fn {
128130
/// Returns all default aggregate functions
129131
pub fn all_default_aggregate_functions() -> Vec<Arc<AggregateUDF>> {
130132
vec![
133+
array_agg::array_agg_udaf(),
131134
first_last::first_value_udaf(),
132135
first_last::last_value_udaf(),
133136
covariance::covar_samp_udaf(),
@@ -191,8 +194,9 @@ mod tests {
191194
let mut names = HashSet::new();
192195
for func in all_default_aggregate_functions() {
193196
// TODO: remove this
194-
// These functions are in intermediate migration state, skip them
195-
if func.name().to_lowercase() == "count" {
197+
// These functions are in intermidiate migration state, skip them
198+
let name_lower_case = func.name().to_lowercase();
199+
if name_lower_case == "count" || name_lower_case == "array_agg" {
196200
continue;
197201
}
198202
assert!(

0 commit comments

Comments
 (0)