kumarUjjawal commented on code in PR #25740:
URL: https://github.com/apache/datafusion/pull/25740#discussion_r4781311258
##########
datafusion/functions-aggregate/src/map_agg.rs:
##########
@@ -0,0 +1,1247 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF)
under one or more contributor license agreements
+
+//! `MAP_AGG` aggregate implementation: [`MapAgg`]
+//!
+//! Aggregates key/value pairs into a `Map`, analogous to how `array_agg`
+//! aggregates values into a `List`.
+//!
+//! # Accumulators
+//!
+//! Two accumulators implement the function, selected in
+//! [`MapAgg::accumulator`] by whether the aggregate carries an `ORDER BY`:
+//!
+//! * [`MapAggAccumulator`] keeps the pairs in input order and serializes its
+//! state as a single `Map` column.
+//! * [`OrderSensitiveMapAggAccumulator`] additionally records the values of
the
+//! ordering expressions for every pair. Its state therefore has two columns,
+//! the `Map` plus a `List<Struct<ordering...>>` that lets partial states
from
+//! every partition be sorted together at output, so the final
+//! entry order stays deterministic under parallelism.
+//!
+//! [`MapAgg::order_sensitivity`] is
[`AggregateOrderSensitivity::SoftRequirement`],
+//! so when a plan's input already satisfies the ordering the accumulator is
+//! marked through [`AggregateUDFImpl::with_beneficial_ordering`] and the pairs
+//! are not sorted again unless partial states are merged.
+//!
+//! # De-duplication
+//!
+//! Duplicate keys are removed during unordered updates or after sorting
ordered
+//! input. Without `ORDER BY`, neither entry order nor the duplicate winner is
+//! guaranteed. With `ORDER BY`, the first pair in the requested ordering wins;
+//! ties require additional ordering expressions for deterministic selection.
+//!
+//! # Nulls
+//!
+//! Both accumulators reject `NULL` keys in `update_batch` with
+//! `map key cannot be null`.
+//! `NULL` values are ordinary map values and are kept. An empty group
+//! evaluates to a `NULL` map, matching `array_agg`.
+
+use std::collections::HashSet;
+use std::mem::{size_of, size_of_val};
+use std::sync::Arc;
+
+use arrow::array::{
+ Array, ArrayRef, AsArray, MapArray, StructArray, UInt64Array, make_array,
+ new_empty_array,
+};
+use arrow::buffer::{NullBuffer, OffsetBuffer, ScalarBuffer};
+use arrow::compute::{SortOptions, cast, concat, take};
+use arrow::datatypes::{DataType, Field, FieldRef, Fields};
+use arrow::row::{RowConverter, SortField};
+
+use crate::array_agg::compact_payload;
+use datafusion_common::cast::as_map_array;
+use datafusion_common::scalar::copy_array_data;
+use datafusion_common::utils::{SingleRowListArrayBuilder, take_function_args};
+use datafusion_common::{
+ Result, ScalarValue, assert_eq_or_internal_err, exec_err, internal_err,
not_impl_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::order::AggregateOrderSensitivity;
+use datafusion_functions_aggregate_common::utils::ordering_fields;
+use datafusion_macros::user_doc;
+use datafusion_physical_expr_common::sort_expr::LexOrdering;
+make_udaf_expr_and_func!(
+ MapAgg,
+ map_agg,
+ key value,
+ "Aggregates keys and values into a map",
+ map_agg_udaf
+);
+
+#[user_doc(
+ doc_section(label = "General Functions"),
+ description = "Returns a map created from the key and value expression
elements. \
+For each row, the key expression becomes a map key and the value expression
becomes the corresponding map value. \
+Without `ORDER BY`, neither entry order nor the value retained for a duplicate
key is guaranteed. \
+With `ORDER BY`, the first entry for each key in the requested ordering is
kept; ties are not deterministic. \
+NULL keys cause an error, NULL values are retained, and empty input returns
NULL. \
+DISTINCT is not supported.",
+ syntax_example = "map_agg(key, value [ORDER BY expression])",
+ sql_example = r#"```sql
+> SELECT map_agg(k, v ORDER BY k) AS m FROM (VALUES ('a', 1)) t(k, v);
++--------+
+| m |
++--------+
+| {a: 1} |
++--------+
+```"#,
+ argument(
+ name = "key",
+ description = "Expression used as the map key. Can be a column or any
valid expression."
+ ),
+ argument(
+ name = "value",
+ description = "Expression used as the map value. Can be a column or
any valid expression."
+ )
+)]
+#[derive(Debug, PartialEq, Eq, Hash)]
+/// MAP_AGG aggregate expression
+pub struct MapAgg {
+ /// Accepts two arguments of any type: the key and the value.
+ signature: Signature,
+ /// Whether the input is known to arrive already ordered by the `ORDER BY`
+ /// inside the aggregate.
+ is_input_pre_ordered: bool,
+}
+
+impl Default for MapAgg {
+ fn default() -> Self {
+ Self {
+ signature: Signature::any(2, Volatility::Immutable),
+ is_input_pre_ordered: false,
+ }
+ }
+}
+
+impl MapAgg {
+ /// Create a new MAP_AGG aggregate function
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Build the Arrow `Map` data type for `map_agg(key, value)`
+ fn map_data_type(key_type: &DataType, value_type: &DataType) -> DataType {
+ DataType::Map(
+ Arc::new(Field::new(
+ "entries",
+ DataType::Struct(Fields::from(vec![
+ Field::new("key", key_type.clone(), false),
+ Field::new("value", value_type.clone(), true),
+ ])),
+ false,
+ )),
+ false,
+ )
+ }
+}
+
+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> {
+ let [key_type, value_type] = take_function_args(self.name(),
arg_types)?;
+ Ok(Self::map_data_type(key_type, value_type))
+ }
+
+ fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
+ let map_type = Self::map_data_type(
+ args.input_fields[0].data_type(),
+ args.input_fields[1].data_type(),
+ );
+
+ let mut fields = vec![
+ Field::new(
+ format_state_name(args.name, "map_agg"),
+ // Nullable so empty groups can produce a NULL map
+ map_type,
+ true,
+ )
+ .into(),
+ ];
+
+ if args.ordering_fields.is_empty() {
+ return Ok(fields);
+ }
+
+ let orderings = args.ordering_fields.to_vec();
+ fields.push(
+ Field::new_list(
+ format_state_name(args.name, "map_agg_orderings"),
+
Field::new_list_field(DataType::Struct(Fields::from(orderings)), true),
+ false,
+ )
+ .into(),
+ );
+
+ Ok(fields)
+ }
+
+ fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn
Accumulator>> {
+ if acc_args.is_distinct {
+ return not_impl_err!("map_agg does not support DISTINCT");
+ }
+ let [key_field, value_field] =
+ take_function_args(self.name(), acc_args.expr_fields)?;
+ let key_type = key_field.data_type().clone();
+ let value_type = value_field.data_type().clone();
+
+ let Some(ordering) = LexOrdering::new(acc_args.order_bys.to_vec())
else {
+ return MapAggAccumulator::try_new(key_type, value_type)
+ .map(|acc| Box::new(acc) as _);
+ };
+
+ 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,
+ self.is_input_pre_ordered,
+ acc_args.is_reversed,
+ )))
+ }
+
+ fn order_sensitivity(&self) -> AggregateOrderSensitivity {
+ AggregateOrderSensitivity::SoftRequirement
+ }
+
+ fn reverse_expr(&self) -> datafusion_expr::ReversedUDAF {
+ // Not Supported because order matters for aggregate first-wins
semantics for duplicate keys
+ datafusion_expr::ReversedUDAF::NotSupported
+ }
+
+ fn with_beneficial_ordering(
+ self: Arc<Self>,
+ beneficial_ordering: bool,
+ ) -> Result<Option<Arc<dyn AggregateUDFImpl>>> {
+ Ok(Some(Arc::new(Self {
+ signature: self.signature.clone(),
+ is_input_pre_ordered: beneficial_ordering,
+ })))
+ }
+
+ fn documentation(&self) -> Option<&Documentation> {
+ self.doc()
+ }
+}
+
+/// Accumulates key/value pairs for [`MapAgg`].
+///
+/// Only the first pair for each key is retained, in compact array batches.
+#[derive(Debug)]
+pub struct MapAggAccumulator {
+ /// Data type of the map keys.
+ key_type: DataType,
+ /// Data type of the map values.
+ value_type: DataType,
+ batches: Vec<Vec<ArrayRef>>,
+ seen: HashSet<ScalarValue>,
+}
+
+impl MapAggAccumulator {
+ /// Create a new map_agg accumulator for the given key and value types
+ pub fn try_new(key_type: DataType, value_type: DataType) -> Result<Self> {
+ Ok(Self {
+ key_type,
+ value_type,
+ batches: vec![],
+ seen: HashSet::new(),
+ })
+ }
+}
+
+impl Accumulator for MapAggAccumulator {
+ fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
+ assert_eq_or_internal_err!(values.len(), 2, "map_agg expects (key,
value)");
+
+ let keys = cast(&values[0], &self.key_type)?;
+ let vals = cast(&values[1], &self.value_type)?;
+
+ assert_eq_or_internal_err!(keys.len(), vals.len(), "key/value length
mismatch");
+ if keys.logical_null_count() != 0 {
+ return exec_err!("map key cannot be null");
+ }
+ let mut indices = Vec::new();
+ for row in 0..keys.len() {
+ if self
+ .seen
+ .insert(ScalarValue::try_from_array(&keys, row)?.compacted())
+ {
+ indices.push(row as u64);
+ }
+ }
+ if !indices.is_empty() {
+ let indices = UInt64Array::from(indices);
+ self.batches.push(
+ [keys, vals]
+ .into_iter()
+ .map(|array| compact_array(take(array.as_ref(), &indices,
None)?))
Review Comment:
For `ListView<Int32>`, `take()` keeps the whole child array even when this
group keeps only one short list. `compact_payload()` leaves that integer buffer
in place. Can we copy the selected list values and add a one-row memory test
for this case? [Arrow’s
`take_list_view`](https://docs.rs/arrow-select/60.2.0/src/arrow_select/take.rs.html#1179-1207)
##########
datafusion/functions-aggregate/src/map_agg.rs:
##########
@@ -0,0 +1,1247 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF)
under one or more contributor license agreements
+
+//! `MAP_AGG` aggregate implementation: [`MapAgg`]
+//!
+//! Aggregates key/value pairs into a `Map`, analogous to how `array_agg`
+//! aggregates values into a `List`.
+//!
+//! # Accumulators
+//!
+//! Two accumulators implement the function, selected in
+//! [`MapAgg::accumulator`] by whether the aggregate carries an `ORDER BY`:
+//!
+//! * [`MapAggAccumulator`] keeps the pairs in input order and serializes its
+//! state as a single `Map` column.
+//! * [`OrderSensitiveMapAggAccumulator`] additionally records the values of
the
+//! ordering expressions for every pair. Its state therefore has two columns,
+//! the `Map` plus a `List<Struct<ordering...>>` that lets partial states
from
+//! every partition be sorted together at output, so the final
+//! entry order stays deterministic under parallelism.
+//!
+//! [`MapAgg::order_sensitivity`] is
[`AggregateOrderSensitivity::SoftRequirement`],
+//! so when a plan's input already satisfies the ordering the accumulator is
+//! marked through [`AggregateUDFImpl::with_beneficial_ordering`] and the pairs
+//! are not sorted again unless partial states are merged.
+//!
+//! # De-duplication
+//!
+//! Duplicate keys are removed during unordered updates or after sorting
ordered
+//! input. Without `ORDER BY`, neither entry order nor the duplicate winner is
+//! guaranteed. With `ORDER BY`, the first pair in the requested ordering wins;
+//! ties require additional ordering expressions for deterministic selection.
+//!
+//! # Nulls
+//!
+//! Both accumulators reject `NULL` keys in `update_batch` with
+//! `map key cannot be null`.
+//! `NULL` values are ordinary map values and are kept. An empty group
+//! evaluates to a `NULL` map, matching `array_agg`.
+
+use std::collections::HashSet;
+use std::mem::{size_of, size_of_val};
+use std::sync::Arc;
+
+use arrow::array::{
+ Array, ArrayRef, AsArray, MapArray, StructArray, UInt64Array, make_array,
+ new_empty_array,
+};
+use arrow::buffer::{NullBuffer, OffsetBuffer, ScalarBuffer};
+use arrow::compute::{SortOptions, cast, concat, take};
+use arrow::datatypes::{DataType, Field, FieldRef, Fields};
+use arrow::row::{RowConverter, SortField};
+
+use crate::array_agg::compact_payload;
+use datafusion_common::cast::as_map_array;
+use datafusion_common::scalar::copy_array_data;
+use datafusion_common::utils::{SingleRowListArrayBuilder, take_function_args};
+use datafusion_common::{
+ Result, ScalarValue, assert_eq_or_internal_err, exec_err, internal_err,
not_impl_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::order::AggregateOrderSensitivity;
+use datafusion_functions_aggregate_common::utils::ordering_fields;
+use datafusion_macros::user_doc;
+use datafusion_physical_expr_common::sort_expr::LexOrdering;
+make_udaf_expr_and_func!(
+ MapAgg,
+ map_agg,
+ key value,
+ "Aggregates keys and values into a map",
+ map_agg_udaf
+);
+
+#[user_doc(
+ doc_section(label = "General Functions"),
+ description = "Returns a map created from the key and value expression
elements. \
+For each row, the key expression becomes a map key and the value expression
becomes the corresponding map value. \
+Without `ORDER BY`, neither entry order nor the value retained for a duplicate
key is guaranteed. \
+With `ORDER BY`, the first entry for each key in the requested ordering is
kept; ties are not deterministic. \
+NULL keys cause an error, NULL values are retained, and empty input returns
NULL. \
+DISTINCT is not supported.",
+ syntax_example = "map_agg(key, value [ORDER BY expression])",
+ sql_example = r#"```sql
+> SELECT map_agg(k, v ORDER BY k) AS m FROM (VALUES ('a', 1)) t(k, v);
++--------+
+| m |
++--------+
+| {a: 1} |
++--------+
+```"#,
+ argument(
+ name = "key",
+ description = "Expression used as the map key. Can be a column or any
valid expression."
+ ),
+ argument(
+ name = "value",
+ description = "Expression used as the map value. Can be a column or
any valid expression."
+ )
+)]
+#[derive(Debug, PartialEq, Eq, Hash)]
+/// MAP_AGG aggregate expression
+pub struct MapAgg {
+ /// Accepts two arguments of any type: the key and the value.
+ signature: Signature,
+ /// Whether the input is known to arrive already ordered by the `ORDER BY`
+ /// inside the aggregate.
+ is_input_pre_ordered: bool,
+}
+
+impl Default for MapAgg {
+ fn default() -> Self {
+ Self {
+ signature: Signature::any(2, Volatility::Immutable),
+ is_input_pre_ordered: false,
+ }
+ }
+}
+
+impl MapAgg {
+ /// Create a new MAP_AGG aggregate function
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Build the Arrow `Map` data type for `map_agg(key, value)`
+ fn map_data_type(key_type: &DataType, value_type: &DataType) -> DataType {
+ DataType::Map(
+ Arc::new(Field::new(
+ "entries",
+ DataType::Struct(Fields::from(vec![
+ Field::new("key", key_type.clone(), false),
+ Field::new("value", value_type.clone(), true),
+ ])),
+ false,
+ )),
+ false,
+ )
+ }
+}
+
+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> {
+ let [key_type, value_type] = take_function_args(self.name(),
arg_types)?;
+ Ok(Self::map_data_type(key_type, value_type))
+ }
+
+ fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
+ let map_type = Self::map_data_type(
+ args.input_fields[0].data_type(),
+ args.input_fields[1].data_type(),
+ );
+
+ let mut fields = vec![
+ Field::new(
+ format_state_name(args.name, "map_agg"),
+ // Nullable so empty groups can produce a NULL map
+ map_type,
+ true,
+ )
+ .into(),
+ ];
+
+ if args.ordering_fields.is_empty() {
+ return Ok(fields);
+ }
+
+ let orderings = args.ordering_fields.to_vec();
+ fields.push(
+ Field::new_list(
+ format_state_name(args.name, "map_agg_orderings"),
+
Field::new_list_field(DataType::Struct(Fields::from(orderings)), true),
+ false,
+ )
+ .into(),
+ );
+
+ Ok(fields)
+ }
+
+ fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn
Accumulator>> {
+ if acc_args.is_distinct {
Review Comment:
Can we return `DistinctHandling::Unsupported` from `distinct_handling()`, as
`nth_value` does? The default tells callers that the accumulator handles
`DISTINCT`, but this accumulator rejects it.
--
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]