LiaCastaneda commented on code in PR #22996: URL: https://github.com/apache/datafusion/pull/22996#discussion_r3434516688
########## datafusion/functions-aggregate/src/map_agg.rs: ########## @@ -0,0 +1,725 @@ +// 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. + +//! `MAP_AGG` aggregate implementation: [`MapAgg`] + +use std::collections::VecDeque; +use std::mem::{size_of, size_of_val, take}; +use std::sync::Arc; + +use arrow::array::{Array, ArrayRef, AsArray, MapArray, StructArray}; +use arrow::buffer::{OffsetBuffer, ScalarBuffer}; +use arrow::compute::SortOptions; +use arrow::datatypes::{DataType, Field, FieldRef, Fields}; + +use datafusion_common::utils::{compare_rows, get_row_at_idx}; +use datafusion_common::{Result, ScalarValue, exec_err}; +use datafusion_expr::function::{AccumulatorArgs, StateFieldsArgs}; +use datafusion_expr::utils::format_state_name; +use datafusion_expr::{ + Accumulator, AggregateUDFImpl, Documentation, Signature, Volatility, +}; +use datafusion_functions_aggregate_common::merge_arrays::merge_ordered_arrays; +use datafusion_functions_aggregate_common::order::AggregateOrderSensitivity; +use datafusion_functions_aggregate_common::utils::ordering_fields; +use datafusion_macros::user_doc; +use datafusion_physical_expr_common::sort_expr::LexOrdering; + +use crate::utils::{map_row_to_scalars, struct_to_rows}; + +make_udaf_expr_and_func!( + MapAgg, + map_agg, + "Aggregate key-value pairs into a map", + map_agg_udaf +); + +#[user_doc( + doc_section(label = "General Functions"), + description = "Aggregate key-value pairs from two columns into a single map per group. Pairs with a NULL key are skipped; NULL values are retained. On a duplicate key the first value wins; use ORDER BY to make which value wins deterministic.", + syntax_example = "map_agg(key, value [ORDER BY expression])", + sql_example = r#" +```sql +> SELECT map_agg(name, score) FROM scores GROUP BY department; ++-------------------------------+ +| map_agg(name, score) | ++-------------------------------+ +| {Alice: 95, Bob: 87} | ++-------------------------------+ +``` +"#, + standard_argument(name = "key",), + standard_argument(name = "value",) +)] +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct MapAgg { + signature: Signature, +} + +impl Default for MapAgg { + fn default() -> Self { + Self { + signature: Signature::any(2, Volatility::Immutable), + } + } +} + +impl AggregateUDFImpl for MapAgg { + fn name(&self) -> &str { + "map_agg" + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> { + Ok(map_type(&arg_types[0], &arg_types[1])) + } + + fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> { + let key_type = args.input_fields[0].data_type(); + let value_type = args.input_fields[1].data_type(); + + let mut fields = vec![Arc::new(Field::new( + format_state_name(args.name, "map_agg"), + map_type(key_type, value_type), + true, + ))]; + + if !args.ordering_fields.is_empty() { + fields.push(Arc::new(Field::new_list( + format_state_name(args.name, "map_agg_orderings"), + Field::new_list_field( + DataType::Struct(Fields::from(args.ordering_fields.to_vec())), + true, + ), + false, + ))); + } + + Ok(fields) + } + + fn order_sensitivity(&self) -> AggregateOrderSensitivity { + // Order decides which value wins on a duplicate key, so the optimizer + // must satisfy it (inserts a SortExec). + // TODO: handle pre-sorted input like `array_agg` to skip the + // redundant sort. + AggregateOrderSensitivity::HardRequirement + } + + fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> { + let key_type = acc_args.expr_fields[0].data_type().clone(); + let value_type = acc_args.expr_fields[1].data_type().clone(); + + let Some(ordering) = LexOrdering::new(acc_args.order_bys.to_vec()) else { + return Ok(Box::new(MapAggAccumulator::new(key_type, value_type))); + }; + + let ordering_dtypes = ordering + .iter() + .map(|e| e.expr.data_type(acc_args.schema)) + .collect::<Result<Vec<_>>>()?; + + Ok(Box::new(OrderSensitiveMapAggAccumulator::new( + key_type, + value_type, + ordering_dtypes, + ordering, + ))) + } + + fn documentation(&self) -> Option<&Documentation> { + self.doc() + } +} + +fn map_type(key_type: &DataType, value_type: &DataType) -> DataType { + let key_field = Arc::new(Field::new("key", key_type.clone(), false)); + let value_field = Arc::new(Field::new("value", value_type.clone(), true)); + let entries_field = Arc::new(Field::new( + "entries", + DataType::Struct(Fields::from(vec![key_field, value_field])), + false, + )); + DataType::Map(entries_field, false) +} + +fn build_single_map( + keys: Vec<ScalarValue>, + values: Vec<ScalarValue>, + key_type: &DataType, + value_type: &DataType, +) -> Result<ArrayRef> { + debug_assert_eq!(keys.len(), values.len()); + + let key_field = Arc::new(Field::new("key", key_type.clone(), false)); + let value_field = Arc::new(Field::new("value", value_type.clone(), true)); + let entries_field = Arc::new(Field::new( + "entries", + DataType::Struct(Fields::from(vec![ + Arc::clone(&key_field), + Arc::clone(&value_field), + ])), + false, + )); + + let len = keys.len(); + let key_array = if len == 0 { + arrow::array::new_empty_array(key_type) + } else { + ScalarValue::iter_to_array(keys)? + }; + let value_array = if len == 0 { + arrow::array::new_empty_array(value_type) + } else { + ScalarValue::iter_to_array(values)? + }; + + let entries = StructArray::try_new( + Fields::from(vec![key_field, value_field]), + vec![key_array, value_array], + None, + )?; + + let offsets = OffsetBuffer::new(ScalarBuffer::from(vec![0i32, len as i32])); + Ok(Arc::new(MapArray::try_new( + entries_field, + offsets, + entries, + None, + false, + )?)) +} + +/// De-duplicates parallel key/value vectors keeping the first value seen for +/// each key. +fn dedup_first_wins( + keys: Vec<ScalarValue>, + values: Vec<ScalarValue>, +) -> (Vec<ScalarValue>, Vec<ScalarValue>) { + use std::collections::HashSet; + + let mut seen: HashSet<ScalarValue> = HashSet::with_capacity(keys.len()); + let mut out_keys: Vec<ScalarValue> = Vec::with_capacity(keys.len()); + let mut out_vals: Vec<ScalarValue> = Vec::with_capacity(keys.len()); + + for (k, v) in keys.into_iter().zip(values) { + // Keep only the first occurrence of each key; later ones are dropped. + if seen.insert(k.clone()) { + out_keys.push(k); + out_vals.push(v); + } + } + + (out_keys, out_vals) +} + +/// Plain accumulator used when there is no `ORDER BY`. +#[derive(Debug)] +pub struct MapAggAccumulator { + key_type: DataType, + value_type: DataType, + keys: Vec<ScalarValue>, + values: Vec<ScalarValue>, +} + +impl MapAggAccumulator { + pub fn new(key_type: DataType, value_type: DataType) -> Self { + Self { + key_type, + value_type, + keys: Vec::new(), + values: Vec::new(), + } + } +} + +impl Accumulator for MapAggAccumulator { + fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> { + if values.len() != 2 { + return exec_err!("map_agg expects 2 columns, got {}", values.len()); + } + let keys = &values[0]; + let vals = &values[1]; + + for i in 0..keys.len() { + // NULL keys cannot exist in a map; skip the whole pair. + if keys.is_null(i) { + continue; + } + self.keys + .push(ScalarValue::try_from_array(keys, i)?.compacted()); + self.values + .push(ScalarValue::try_from_array(vals, i)?.compacted()); + } + Ok(()) + } + + fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> { + if states.is_empty() { + return Ok(()); + } + let map_array = states[0].as_map(); + for row in 0..map_array.len() { + if map_array.is_null(row) { + continue; + } + let (keys, values) = map_row_to_scalars(map_array, row)?; + self.keys.extend(keys); + self.values.extend(values); + } + Ok(()) + } + + fn state(&mut self) -> Result<Vec<ScalarValue>> { + Ok(vec![self.evaluate()?]) + } + + fn evaluate(&mut self) -> Result<ScalarValue> { + let (keys, values) = dedup_first_wins(self.keys.clone(), self.values.clone()); + let map_array = build_single_map(keys, values, &self.key_type, &self.value_type)?; + ScalarValue::try_from_array(&map_array, 0) + } + + fn size(&self) -> usize { + size_of_val(self) + ScalarValue::size_of_vec(&self.keys) - size_of_val(&self.keys) + + ScalarValue::size_of_vec(&self.values) + - size_of_val(&self.values) + + self.key_type.size() + - size_of_val(&self.key_type) + + self.value_type.size() + - size_of_val(&self.value_type) + } +} + +/// Accumulator used when `map_agg` has an `ORDER BY`. Stores the ordering column +/// values alongside each pair so the input can be globally sorted (across +/// partitions). +#[derive(Debug)] +pub struct OrderSensitiveMapAggAccumulator { + key_type: DataType, + value_type: DataType, + keys: Vec<ScalarValue>, + values: Vec<ScalarValue>, + /// Ordering-expression values for each pair, parallel to `keys`/`values`. + ordering_values: Vec<Vec<ScalarValue>>, + ordering_dtypes: Vec<DataType>, + ordering_req: LexOrdering, +} + +impl OrderSensitiveMapAggAccumulator { + pub fn new( + key_type: DataType, + value_type: DataType, + ordering_dtypes: Vec<DataType>, + ordering_req: LexOrdering, + ) -> Self { + Self { + key_type, + value_type, + keys: Vec::new(), + values: Vec::new(), + ordering_values: Vec::new(), + ordering_dtypes, + ordering_req, + } + } + + fn sort_options(&self) -> Vec<SortOptions> { + self.ordering_req.iter().map(|s| s.options).collect() + } + + /// Sorts the accumulated pairs by their ordering values, then applies + /// first-wins de-duplication. + fn sorted_deduped(&self) -> Result<(Vec<ScalarValue>, Vec<ScalarValue>)> { + let sort_options = self.sort_options(); + let mut rows: Vec<usize> = (0..self.keys.len()).collect(); + let mut cmp_err = Ok(()); + rows.sort_by(|&a, &b| { + compare_rows( + &self.ordering_values[a], + &self.ordering_values[b], + &sort_options, + ) + .unwrap_or_else(|e| { + cmp_err = Err(e); + std::cmp::Ordering::Equal + }) + }); + cmp_err?; + + let keys = rows.iter().map(|&i| self.keys[i].clone()).collect(); + let values = rows.iter().map(|&i| self.values[i].clone()).collect(); Review Comment: We can't take these arrays since window functions call the same accumulator's `evaluate()` repeatedly , and after the first call it would see empty values. ########## datafusion/functions-aggregate/src/map_agg.rs: ########## @@ -0,0 +1,725 @@ +// 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. + +//! `MAP_AGG` aggregate implementation: [`MapAgg`] + +use std::collections::VecDeque; +use std::mem::{size_of, size_of_val, take}; +use std::sync::Arc; + +use arrow::array::{Array, ArrayRef, AsArray, MapArray, StructArray}; +use arrow::buffer::{OffsetBuffer, ScalarBuffer}; +use arrow::compute::SortOptions; +use arrow::datatypes::{DataType, Field, FieldRef, Fields}; + +use datafusion_common::utils::{compare_rows, get_row_at_idx}; +use datafusion_common::{Result, ScalarValue, exec_err}; +use datafusion_expr::function::{AccumulatorArgs, StateFieldsArgs}; +use datafusion_expr::utils::format_state_name; +use datafusion_expr::{ + Accumulator, AggregateUDFImpl, Documentation, Signature, Volatility, +}; +use datafusion_functions_aggregate_common::merge_arrays::merge_ordered_arrays; +use datafusion_functions_aggregate_common::order::AggregateOrderSensitivity; +use datafusion_functions_aggregate_common::utils::ordering_fields; +use datafusion_macros::user_doc; +use datafusion_physical_expr_common::sort_expr::LexOrdering; + +use crate::utils::{map_row_to_scalars, struct_to_rows}; + +make_udaf_expr_and_func!( + MapAgg, + map_agg, + "Aggregate key-value pairs into a map", + map_agg_udaf +); + +#[user_doc( + doc_section(label = "General Functions"), + description = "Aggregate key-value pairs from two columns into a single map per group. Pairs with a NULL key are skipped; NULL values are retained. On a duplicate key the first value wins; use ORDER BY to make which value wins deterministic.", + syntax_example = "map_agg(key, value [ORDER BY expression])", + sql_example = r#" +```sql +> SELECT map_agg(name, score) FROM scores GROUP BY department; ++-------------------------------+ +| map_agg(name, score) | ++-------------------------------+ +| {Alice: 95, Bob: 87} | ++-------------------------------+ +``` +"#, + standard_argument(name = "key",), + standard_argument(name = "value",) +)] +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct MapAgg { + signature: Signature, +} + +impl Default for MapAgg { + fn default() -> Self { + Self { + signature: Signature::any(2, Volatility::Immutable), + } + } +} + +impl AggregateUDFImpl for MapAgg { + fn name(&self) -> &str { + "map_agg" + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> { + Ok(map_type(&arg_types[0], &arg_types[1])) + } + + fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> { + let key_type = args.input_fields[0].data_type(); + let value_type = args.input_fields[1].data_type(); + + let mut fields = vec![Arc::new(Field::new( + format_state_name(args.name, "map_agg"), + map_type(key_type, value_type), + true, + ))]; + + if !args.ordering_fields.is_empty() { + fields.push(Arc::new(Field::new_list( + format_state_name(args.name, "map_agg_orderings"), + Field::new_list_field( + DataType::Struct(Fields::from(args.ordering_fields.to_vec())), + true, + ), + false, + ))); + } + + Ok(fields) + } + + fn order_sensitivity(&self) -> AggregateOrderSensitivity { + // Order decides which value wins on a duplicate key, so the optimizer + // must satisfy it (inserts a SortExec). + // TODO: handle pre-sorted input like `array_agg` to skip the + // redundant sort. + AggregateOrderSensitivity::HardRequirement + } + + fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> { + let key_type = acc_args.expr_fields[0].data_type().clone(); + let value_type = acc_args.expr_fields[1].data_type().clone(); + + let Some(ordering) = LexOrdering::new(acc_args.order_bys.to_vec()) else { + return Ok(Box::new(MapAggAccumulator::new(key_type, value_type))); + }; + + let ordering_dtypes = ordering + .iter() + .map(|e| e.expr.data_type(acc_args.schema)) + .collect::<Result<Vec<_>>>()?; + + Ok(Box::new(OrderSensitiveMapAggAccumulator::new( + key_type, + value_type, + ordering_dtypes, + ordering, + ))) + } + + fn documentation(&self) -> Option<&Documentation> { + self.doc() + } +} + +fn map_type(key_type: &DataType, value_type: &DataType) -> DataType { + let key_field = Arc::new(Field::new("key", key_type.clone(), false)); + let value_field = Arc::new(Field::new("value", value_type.clone(), true)); + let entries_field = Arc::new(Field::new( + "entries", + DataType::Struct(Fields::from(vec![key_field, value_field])), + false, + )); + DataType::Map(entries_field, false) +} + +fn build_single_map( + keys: Vec<ScalarValue>, + values: Vec<ScalarValue>, + key_type: &DataType, + value_type: &DataType, +) -> Result<ArrayRef> { + debug_assert_eq!(keys.len(), values.len()); + + let key_field = Arc::new(Field::new("key", key_type.clone(), false)); + let value_field = Arc::new(Field::new("value", value_type.clone(), true)); + let entries_field = Arc::new(Field::new( + "entries", + DataType::Struct(Fields::from(vec![ + Arc::clone(&key_field), + Arc::clone(&value_field), + ])), + false, + )); + + let len = keys.len(); + let key_array = if len == 0 { + arrow::array::new_empty_array(key_type) + } else { + ScalarValue::iter_to_array(keys)? + }; + let value_array = if len == 0 { + arrow::array::new_empty_array(value_type) + } else { + ScalarValue::iter_to_array(values)? + }; + + let entries = StructArray::try_new( + Fields::from(vec![key_field, value_field]), + vec![key_array, value_array], + None, + )?; + + let offsets = OffsetBuffer::new(ScalarBuffer::from(vec![0i32, len as i32])); + Ok(Arc::new(MapArray::try_new( + entries_field, + offsets, + entries, + None, + false, + )?)) +} + +/// De-duplicates parallel key/value vectors keeping the first value seen for +/// each key. +fn dedup_first_wins( + keys: Vec<ScalarValue>, + values: Vec<ScalarValue>, +) -> (Vec<ScalarValue>, Vec<ScalarValue>) { + use std::collections::HashSet; + + let mut seen: HashSet<ScalarValue> = HashSet::with_capacity(keys.len()); + let mut out_keys: Vec<ScalarValue> = Vec::with_capacity(keys.len()); + let mut out_vals: Vec<ScalarValue> = Vec::with_capacity(keys.len()); + + for (k, v) in keys.into_iter().zip(values) { + // Keep only the first occurrence of each key; later ones are dropped. + if seen.insert(k.clone()) { + out_keys.push(k); + out_vals.push(v); + } + } + + (out_keys, out_vals) +} + +/// Plain accumulator used when there is no `ORDER BY`. +#[derive(Debug)] +pub struct MapAggAccumulator { + key_type: DataType, + value_type: DataType, + keys: Vec<ScalarValue>, + values: Vec<ScalarValue>, +} + +impl MapAggAccumulator { + pub fn new(key_type: DataType, value_type: DataType) -> Self { + Self { + key_type, + value_type, + keys: Vec::new(), + values: Vec::new(), + } + } +} + +impl Accumulator for MapAggAccumulator { + fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> { + if values.len() != 2 { + return exec_err!("map_agg expects 2 columns, got {}", values.len()); + } + let keys = &values[0]; + let vals = &values[1]; + + for i in 0..keys.len() { + // NULL keys cannot exist in a map; skip the whole pair. + if keys.is_null(i) { + continue; + } + self.keys + .push(ScalarValue::try_from_array(keys, i)?.compacted()); + self.values + .push(ScalarValue::try_from_array(vals, i)?.compacted()); + } + Ok(()) + } + + fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> { + if states.is_empty() { + return Ok(()); + } + let map_array = states[0].as_map(); + for row in 0..map_array.len() { + if map_array.is_null(row) { + continue; + } + let (keys, values) = map_row_to_scalars(map_array, row)?; + self.keys.extend(keys); + self.values.extend(values); + } + Ok(()) + } + + fn state(&mut self) -> Result<Vec<ScalarValue>> { + Ok(vec![self.evaluate()?]) + } + + fn evaluate(&mut self) -> Result<ScalarValue> { + let (keys, values) = dedup_first_wins(self.keys.clone(), self.values.clone()); + let map_array = build_single_map(keys, values, &self.key_type, &self.value_type)?; + ScalarValue::try_from_array(&map_array, 0) + } + + fn size(&self) -> usize { + size_of_val(self) + ScalarValue::size_of_vec(&self.keys) - size_of_val(&self.keys) + + ScalarValue::size_of_vec(&self.values) + - size_of_val(&self.values) + + self.key_type.size() + - size_of_val(&self.key_type) + + self.value_type.size() + - size_of_val(&self.value_type) + } +} + +/// Accumulator used when `map_agg` has an `ORDER BY`. Stores the ordering column +/// values alongside each pair so the input can be globally sorted (across +/// partitions). +#[derive(Debug)] +pub struct OrderSensitiveMapAggAccumulator { + key_type: DataType, + value_type: DataType, + keys: Vec<ScalarValue>, + values: Vec<ScalarValue>, + /// Ordering-expression values for each pair, parallel to `keys`/`values`. + ordering_values: Vec<Vec<ScalarValue>>, + ordering_dtypes: Vec<DataType>, + ordering_req: LexOrdering, +} + +impl OrderSensitiveMapAggAccumulator { + pub fn new( + key_type: DataType, + value_type: DataType, + ordering_dtypes: Vec<DataType>, + ordering_req: LexOrdering, + ) -> Self { + Self { + key_type, + value_type, + keys: Vec::new(), + values: Vec::new(), + ordering_values: Vec::new(), + ordering_dtypes, + ordering_req, + } + } + + fn sort_options(&self) -> Vec<SortOptions> { + self.ordering_req.iter().map(|s| s.options).collect() + } + + /// Sorts the accumulated pairs by their ordering values, then applies + /// first-wins de-duplication. + fn sorted_deduped(&self) -> Result<(Vec<ScalarValue>, Vec<ScalarValue>)> { + let sort_options = self.sort_options(); + let mut rows: Vec<usize> = (0..self.keys.len()).collect(); + let mut cmp_err = Ok(()); + rows.sort_by(|&a, &b| { + compare_rows( + &self.ordering_values[a], + &self.ordering_values[b], + &sort_options, + ) + .unwrap_or_else(|e| { + cmp_err = Err(e); + std::cmp::Ordering::Equal + }) + }); + cmp_err?; + + let keys = rows.iter().map(|&i| self.keys[i].clone()).collect(); + let values = rows.iter().map(|&i| self.values[i].clone()).collect(); Review Comment: We can't `take` these arrays since window functions call the same accumulator's `evaluate()` repeatedly , and after the first call it would see empty values. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
