kumarUjjawal commented on code in PR #25740:
URL: https://github.com/apache/datafusion/pull/25740#discussion_r4667420633
##########
datafusion/functions-aggregate/src/map_agg.rs:
##########
@@ -0,0 +1,1070 @@
+// 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,
new_empty_array,
+};
+use arrow::buffer::{NullBuffer, OffsetBuffer, ScalarBuffer};
+use arrow::compute::{SortOptions, concat, take};
+use arrow::datatypes::{DataType, Field, FieldRef, Fields};
+use arrow::row::{RowConverter, SortField};
+
+use datafusion_common::cast::as_map_array;
+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 {
+ 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 = &values[0];
+ let vals = &values[1];
+ 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(
+ values
+ .iter()
+ .map(|array| compact_array(take(array.as_ref(), &indices,
None)?))
+ .collect::<Result<_>>()?,
+ );
+ }
+
+ Ok(())
+ }
+ fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
+ if states.is_empty() {
+ return Ok(());
+ }
+
+ assert_eq_or_internal_err!(states.len(), 1, "expects single state");
+
+ let map_arr = as_map_array(states[0].as_ref())?;
+ for row in 0..map_arr.len() {
+ // Partial states are nullable so empty groups can produce a NULL
map
+ if map_arr.is_null(row) {
+ continue;
+ }
+ self.update_batch(&map_row_to_arrays(map_arr, row))?;
+ }
+
+ Ok(())
+ }
+
+ fn state(&mut self) -> Result<Vec<ScalarValue>> {
+ Ok(vec![self.evaluate()?])
+ }
+
+ fn evaluate(&mut self) -> Result<ScalarValue> {
+ let keys = concat_column(&self.batches, 0, &self.key_type)?;
+ let values = concat_column(&self.batches, 1, &self.value_type)?;
+ build_single_map(keys, values)
+ }
+
+ fn size(&self) -> usize {
+ // HashSet capacity excludes the empty buckets reserved for probing.
+ let buckets = if self.seen.capacity() == 0 {
+ 0
+ } else {
+ self.seen.capacity().next_power_of_two()
+ };
+ size_of_val(self) + batches_size(&self.batches) + self.key_type.size()
+ - size_of_val(&self.key_type)
+ + self.value_type.size()
+ - size_of_val(&self.value_type)
+ + buckets * (size_of::<ScalarValue>() + 1)
+ + self
+ .seen
+ .iter()
+ .map(|s| s.size() - size_of::<ScalarValue>())
+ .sum::<usize>()
+ }
+}
+
+/// 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 {
+ /// Data type of the map keys.
+ key_type: DataType,
+ /// Data type of the map values.
+ value_type: DataType,
+ /// Key, value, and ordering columns, retained as compact batches.
+ batches: Vec<Vec<ArrayRef>>,
+ /// Data types of the ordering expressions, used to build the state field.
+ ordering_dtypes: Vec<DataType>,
+ /// The `ORDER BY` requirement inside the aggregate.
+ ordering_req: LexOrdering,
+ /// When true the input already satisfies `ordering_req`, so the pairs do
+ /// not have to be sorted again before de-duplication.
+ is_input_pre_ordered: bool,
+ /// Whether to restore the output order after sorting by a reversed
requirement.
+ reverse: bool,
+}
+
+impl OrderSensitiveMapAggAccumulator {
+ /// Create a new accumulator for `map_agg(key, value ORDER BY ...)`.
+ ///
+ /// `ordering_dtypes` must hold one data type per entry of `ordering_req`.
+ pub fn new(
+ key_type: DataType,
+ value_type: DataType,
+ ordering_dtypes: Vec<DataType>,
+ ordering_req: LexOrdering,
+ is_input_pre_ordered: bool,
+ reverse: bool,
+ ) -> Self {
+ Self {
+ key_type,
+ value_type,
+ batches: Vec::new(),
+ ordering_dtypes,
+ ordering_req,
+ is_input_pre_ordered,
+ reverse,
+ }
+ }
+
+ /// Sort options of each ordering expression, used when sorting the pairs
+ /// and when merging partial states.
+ ///
+ /// For a reversed accumulator these are the already-reversed options;
+ /// the requested output order is restored separately by
+ /// reversing the rows in [`Self::sorted_deduped`].
+ fn sort_options(&self) -> Vec<SortOptions> {
+ self.ordering_req.iter().map(|s| s.options).collect()
+ }
+
+ /// Sorts and de-duplicates all columns using the same row indices.
+ #[allow(clippy::allow_attributes, clippy::mutable_key_type)] //
ScalarValue has interior mutability but is intentionally used as hash key
+ fn sorted_deduped(&self) -> Result<Vec<ArrayRef>> {
+ let columns = std::iter::once(&self.key_type)
+ .chain(std::iter::once(&self.value_type))
+ .chain(self.ordering_dtypes.iter())
+ .enumerate()
+ .map(|(i, dtype)| concat_column(&self.batches, i, dtype))
+ .collect::<Result<Vec<_>>>()?;
+ let mut rows: Vec<usize> = (0..columns[0].len()).collect();
+ if !self.is_input_pre_ordered {
+ let converter = RowConverter::new(
+ self.ordering_dtypes
+ .iter()
+ .zip(self.sort_options())
+ .map(|(dtype, options)| {
+ SortField::new_with_options(dtype.clone(), options)
+ })
+ .collect(),
+ )?;
+ let ordering_rows = converter.convert_columns(&columns[2..])?;
+ rows.sort_by(|&a, &b|
ordering_rows.row(a).cmp(&ordering_rows.row(b)));
+ }
+ if self.reverse {
+ rows.reverse();
+ }
+ let mut seen = HashSet::new();
+ let mut indices = Vec::new();
+ for i in rows {
+ if seen.insert(ScalarValue::try_from_array(&columns[0], i)?) {
+ indices.push(i as u64);
+ }
+ }
+ let indices = UInt64Array::from(indices);
+ columns
+ .iter()
+ .map(|array| Ok(take(array.as_ref(), &indices, None)?))
+ .collect()
+ }
+
+ /// Builds the `List<Struct<ordering...>>` state column from the given
+ /// ordering values. These must be the de-duplicated ordering values that
+ /// align with the map state, so both pieces of state describe the same
rows.
+ fn evaluate_orderings(&self, ordering_values: &[ArrayRef]) ->
Result<ScalarValue> {
+ let fields = ordering_fields(&self.ordering_req,
&self.ordering_dtypes);
+ let struct_array =
+ StructArray::try_new(Fields::from(fields),
ordering_values.to_vec(), None)?;
+
Ok(SingleRowListArrayBuilder::new(Arc::new(struct_array)).build_list_scalar())
+ }
+}
+
+impl Accumulator for OrderSensitiveMapAggAccumulator {
+ fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
+ assert_eq_or_internal_err!(
+ values.len(),
+ 2 + self.ordering_dtypes.len(),
+ "map_agg column count mismatch"
+ );
+ let keys = &values[0];
+ for array in &values[1..] {
+ assert_eq_or_internal_err!(
+ keys.len(),
+ array.len(),
+ "map_agg column length mismatch"
+ );
+ }
+ if keys.logical_null_count() != 0 {
+ return exec_err!("map key cannot be null");
+ }
+ if !keys.is_empty() {
+ self.batches.push(
+ values
+ .iter()
+ .map(|array| compact_array(Arc::clone(array)))
+ .collect::<Result<_>>()?,
+ );
+ }
+ Ok(())
+ }
+
+ fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
+ if states.is_empty() {
+ return Ok(());
+ }
+ if states.len() != 2 {
+ return exec_err!(
+ "map_agg ordered merge expects 2 state columns, got {}",
+ states.len()
+ );
+ }
+
+ let map_array = states[0].as_map();
+ let orderings = states[1].as_list::<i32>();
+
+ // Individually ordered partitions are not globally ordered. Sort once
+ // at output, including when the raw input was marked pre-ordered.
+ self.is_input_pre_ordered = false;
+ for row in 0..map_array.len() {
+ if map_array.is_null(row) {
+ continue;
+ }
+ let mut columns = map_row_to_arrays(map_array, row).to_vec();
+
columns.extend_from_slice(orderings.value(row).as_struct().columns());
+ self.update_batch(&columns)?;
+ }
+ Ok(())
+ }
+
+ fn state(&mut self) -> Result<Vec<ScalarValue>> {
+ let rows = self.sorted_deduped()?;
+ let orderings = self.evaluate_orderings(&rows[2..])?;
+ let map = build_single_map(Arc::clone(&rows[0]),
Arc::clone(&rows[1]))?;
+ Ok(vec![map, orderings])
+ }
+
+ fn evaluate(&mut self) -> Result<ScalarValue> {
+ let rows = self.sorted_deduped()?;
+ build_single_map(Arc::clone(&rows[0]), Arc::clone(&rows[1]))
+ }
+
+ fn size(&self) -> usize {
+ let mut total =
+ size_of_val(self) + batches_size(&self.batches) +
self.key_type.size()
+ - size_of_val(&self.key_type)
+ + self.value_type.size()
+ - size_of_val(&self.value_type);
+
+ // ordering_dtypes: Vec spine plus the heap owned by each DataType.
+ total += size_of::<DataType>() * self.ordering_dtypes.capacity();
+ for dtype in &self.ordering_dtypes {
+ total += dtype.size() - size_of_val(dtype);
+ }
+
+ total
+ }
+}
+
+/// Builds a single-row `Map` array holding `keys` and `values`.
+///
+/// An empty input yields a one-row array that is NULL, so empty groups
+/// evaluate to a NULL map just like [`MapAggAccumulator`] does.
+fn build_single_map(keys: ArrayRef, values: ArrayRef) -> Result<ScalarValue> {
+ let map_type = MapAgg::map_data_type(keys.data_type(), values.data_type());
Review Comment:
This derives the result type from the runtime arrays. I created an
accumulator whose declared value type was `Struct(n Int32 nullable)` and passed
it a batch where `n` was non-nullable. `evaluate()` returned a map with `n`
non-nullable, and Arrow rejected that map when I built a `RecordBatch` with the
aggregate’s declared schema.
Could we normalize the key and value arrays to their declared types before
retaining them? That would keep both `state()` and `evaluate()` consistent with
the schema. `array_agg` already has a regression test for this case. [Existing
test](https://github.com/apache/datafusion/blob/8928d044747eecf1bb2b89def88273613d381716/datafusion/functions-aggregate/src/array_agg.rs#L2712-L2781)
##########
datafusion/functions-aggregate/src/map_agg.rs:
##########
@@ -0,0 +1,1070 @@
+// 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,
new_empty_array,
+};
+use arrow::buffer::{NullBuffer, OffsetBuffer, ScalarBuffer};
+use arrow::compute::{SortOptions, concat, take};
+use arrow::datatypes::{DataType, Field, FieldRef, Fields};
+use arrow::row::{RowConverter, SortField};
+
+use datafusion_common::cast::as_map_array;
+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 {
+ 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 = &values[0];
+ let vals = &values[1];
+ 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(
+ values
+ .iter()
+ .map(|array| compact_array(take(array.as_ref(), &indices,
None)?))
+ .collect::<Result<_>>()?,
+ );
+ }
+
+ Ok(())
+ }
+ fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
+ if states.is_empty() {
+ return Ok(());
+ }
+
+ assert_eq_or_internal_err!(states.len(), 1, "expects single state");
+
+ let map_arr = as_map_array(states[0].as_ref())?;
+ for row in 0..map_arr.len() {
+ // Partial states are nullable so empty groups can produce a NULL
map
+ if map_arr.is_null(row) {
+ continue;
+ }
+ self.update_batch(&map_row_to_arrays(map_arr, row))?;
+ }
+
+ Ok(())
+ }
+
+ fn state(&mut self) -> Result<Vec<ScalarValue>> {
+ Ok(vec![self.evaluate()?])
+ }
+
+ fn evaluate(&mut self) -> Result<ScalarValue> {
+ let keys = concat_column(&self.batches, 0, &self.key_type)?;
+ let values = concat_column(&self.batches, 1, &self.value_type)?;
+ build_single_map(keys, values)
+ }
+
+ fn size(&self) -> usize {
+ // HashSet capacity excludes the empty buckets reserved for probing.
+ let buckets = if self.seen.capacity() == 0 {
+ 0
+ } else {
+ self.seen.capacity().next_power_of_two()
+ };
+ size_of_val(self) + batches_size(&self.batches) + self.key_type.size()
+ - size_of_val(&self.key_type)
+ + self.value_type.size()
+ - size_of_val(&self.value_type)
+ + buckets * (size_of::<ScalarValue>() + 1)
+ + self
+ .seen
+ .iter()
+ .map(|s| s.size() - size_of::<ScalarValue>())
+ .sum::<usize>()
+ }
+}
+
+/// 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 {
+ /// Data type of the map keys.
+ key_type: DataType,
+ /// Data type of the map values.
+ value_type: DataType,
+ /// Key, value, and ordering columns, retained as compact batches.
+ batches: Vec<Vec<ArrayRef>>,
+ /// Data types of the ordering expressions, used to build the state field.
+ ordering_dtypes: Vec<DataType>,
+ /// The `ORDER BY` requirement inside the aggregate.
+ ordering_req: LexOrdering,
+ /// When true the input already satisfies `ordering_req`, so the pairs do
+ /// not have to be sorted again before de-duplication.
+ is_input_pre_ordered: bool,
+ /// Whether to restore the output order after sorting by a reversed
requirement.
+ reverse: bool,
+}
+
+impl OrderSensitiveMapAggAccumulator {
+ /// Create a new accumulator for `map_agg(key, value ORDER BY ...)`.
+ ///
+ /// `ordering_dtypes` must hold one data type per entry of `ordering_req`.
+ pub fn new(
+ key_type: DataType,
+ value_type: DataType,
+ ordering_dtypes: Vec<DataType>,
+ ordering_req: LexOrdering,
+ is_input_pre_ordered: bool,
+ reverse: bool,
+ ) -> Self {
+ Self {
+ key_type,
+ value_type,
+ batches: Vec::new(),
+ ordering_dtypes,
+ ordering_req,
+ is_input_pre_ordered,
+ reverse,
+ }
+ }
+
+ /// Sort options of each ordering expression, used when sorting the pairs
+ /// and when merging partial states.
+ ///
+ /// For a reversed accumulator these are the already-reversed options;
+ /// the requested output order is restored separately by
+ /// reversing the rows in [`Self::sorted_deduped`].
+ fn sort_options(&self) -> Vec<SortOptions> {
+ self.ordering_req.iter().map(|s| s.options).collect()
+ }
+
+ /// Sorts and de-duplicates all columns using the same row indices.
+ #[allow(clippy::allow_attributes, clippy::mutable_key_type)] //
ScalarValue has interior mutability but is intentionally used as hash key
+ fn sorted_deduped(&self) -> Result<Vec<ArrayRef>> {
+ let columns = std::iter::once(&self.key_type)
+ .chain(std::iter::once(&self.value_type))
+ .chain(self.ordering_dtypes.iter())
+ .enumerate()
+ .map(|(i, dtype)| concat_column(&self.batches, i, dtype))
+ .collect::<Result<Vec<_>>>()?;
+ let mut rows: Vec<usize> = (0..columns[0].len()).collect();
+ if !self.is_input_pre_ordered {
Review Comment:
This can skip the sort when the input is ordered in the opposite direction.
I reproduced it with this query:
```sql
SET datafusion.execution.target_partitions = 1;
SELECT map_agg(k, v ORDER BY v ASC NULLS LAST)
FROM (
SELECT *
FROM (VALUES ('a', 20), ('b', 5), ('a', 10), ('z', 0)) t(k, v)
ORDER BY v DESC NULLS FIRST
LIMIT 3
) s;
```
This returns `{a: 20, b: 5}`. The aggregate requests ascending order, so it
should return `{b: 5, a: 10}`. `LIMIT 3` keeps the descending sort in the
physical plan. When `reverse_expr()` returns `None`, the optimizer keeps the
original expression and still calls `with_beneficial_ordering(true)`.
Could we leave the flag false when reversal fails and add this query to
`map_agg.slt`?
##########
datafusion/functions-aggregate/src/map_agg.rs:
##########
@@ -0,0 +1,1070 @@
+// 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,
new_empty_array,
+};
+use arrow::buffer::{NullBuffer, OffsetBuffer, ScalarBuffer};
+use arrow::compute::{SortOptions, concat, take};
+use arrow::datatypes::{DataType, Field, FieldRef, Fields};
+use arrow::row::{RowConverter, SortField};
+
+use datafusion_common::cast::as_map_array;
+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 {
+ 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 = &values[0];
+ let vals = &values[1];
+ 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(
+ values
+ .iter()
+ .map(|array| compact_array(take(array.as_ref(), &indices,
None)?))
+ .collect::<Result<_>>()?,
+ );
+ }
+
+ Ok(())
+ }
+ fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
+ if states.is_empty() {
+ return Ok(());
+ }
+
+ assert_eq_or_internal_err!(states.len(), 1, "expects single state");
+
+ let map_arr = as_map_array(states[0].as_ref())?;
+ for row in 0..map_arr.len() {
+ // Partial states are nullable so empty groups can produce a NULL
map
+ if map_arr.is_null(row) {
+ continue;
+ }
+ self.update_batch(&map_row_to_arrays(map_arr, row))?;
+ }
+
+ Ok(())
+ }
+
+ fn state(&mut self) -> Result<Vec<ScalarValue>> {
+ Ok(vec![self.evaluate()?])
+ }
+
+ fn evaluate(&mut self) -> Result<ScalarValue> {
+ let keys = concat_column(&self.batches, 0, &self.key_type)?;
+ let values = concat_column(&self.batches, 1, &self.value_type)?;
+ build_single_map(keys, values)
+ }
+
+ fn size(&self) -> usize {
+ // HashSet capacity excludes the empty buckets reserved for probing.
+ let buckets = if self.seen.capacity() == 0 {
+ 0
+ } else {
+ self.seen.capacity().next_power_of_two()
+ };
+ size_of_val(self) + batches_size(&self.batches) + self.key_type.size()
+ - size_of_val(&self.key_type)
+ + self.value_type.size()
+ - size_of_val(&self.value_type)
+ + buckets * (size_of::<ScalarValue>() + 1)
+ + self
+ .seen
+ .iter()
+ .map(|s| s.size() - size_of::<ScalarValue>())
+ .sum::<usize>()
+ }
+}
+
+/// 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 {
+ /// Data type of the map keys.
+ key_type: DataType,
+ /// Data type of the map values.
+ value_type: DataType,
+ /// Key, value, and ordering columns, retained as compact batches.
+ batches: Vec<Vec<ArrayRef>>,
+ /// Data types of the ordering expressions, used to build the state field.
+ ordering_dtypes: Vec<DataType>,
+ /// The `ORDER BY` requirement inside the aggregate.
+ ordering_req: LexOrdering,
+ /// When true the input already satisfies `ordering_req`, so the pairs do
+ /// not have to be sorted again before de-duplication.
+ is_input_pre_ordered: bool,
+ /// Whether to restore the output order after sorting by a reversed
requirement.
+ reverse: bool,
+}
+
+impl OrderSensitiveMapAggAccumulator {
+ /// Create a new accumulator for `map_agg(key, value ORDER BY ...)`.
+ ///
+ /// `ordering_dtypes` must hold one data type per entry of `ordering_req`.
+ pub fn new(
+ key_type: DataType,
+ value_type: DataType,
+ ordering_dtypes: Vec<DataType>,
+ ordering_req: LexOrdering,
+ is_input_pre_ordered: bool,
+ reverse: bool,
+ ) -> Self {
+ Self {
+ key_type,
+ value_type,
+ batches: Vec::new(),
+ ordering_dtypes,
+ ordering_req,
+ is_input_pre_ordered,
+ reverse,
+ }
+ }
+
+ /// Sort options of each ordering expression, used when sorting the pairs
+ /// and when merging partial states.
+ ///
+ /// For a reversed accumulator these are the already-reversed options;
+ /// the requested output order is restored separately by
+ /// reversing the rows in [`Self::sorted_deduped`].
+ fn sort_options(&self) -> Vec<SortOptions> {
+ self.ordering_req.iter().map(|s| s.options).collect()
+ }
+
+ /// Sorts and de-duplicates all columns using the same row indices.
+ #[allow(clippy::allow_attributes, clippy::mutable_key_type)] //
ScalarValue has interior mutability but is intentionally used as hash key
+ fn sorted_deduped(&self) -> Result<Vec<ArrayRef>> {
+ let columns = std::iter::once(&self.key_type)
+ .chain(std::iter::once(&self.value_type))
+ .chain(self.ordering_dtypes.iter())
+ .enumerate()
+ .map(|(i, dtype)| concat_column(&self.batches, i, dtype))
+ .collect::<Result<Vec<_>>>()?;
+ let mut rows: Vec<usize> = (0..columns[0].len()).collect();
+ if !self.is_input_pre_ordered {
+ let converter = RowConverter::new(
+ self.ordering_dtypes
+ .iter()
+ .zip(self.sort_options())
+ .map(|(dtype, options)| {
+ SortField::new_with_options(dtype.clone(), options)
+ })
+ .collect(),
+ )?;
+ let ordering_rows = converter.convert_columns(&columns[2..])?;
+ rows.sort_by(|&a, &b|
ordering_rows.row(a).cmp(&ordering_rows.row(b)));
+ }
+ if self.reverse {
+ rows.reverse();
+ }
+ let mut seen = HashSet::new();
+ let mut indices = Vec::new();
+ for i in rows {
+ if seen.insert(ScalarValue::try_from_array(&columns[0], i)?) {
+ indices.push(i as u64);
+ }
+ }
+ let indices = UInt64Array::from(indices);
+ columns
+ .iter()
+ .map(|array| Ok(take(array.as_ref(), &indices, None)?))
+ .collect()
+ }
+
+ /// Builds the `List<Struct<ordering...>>` state column from the given
+ /// ordering values. These must be the de-duplicated ordering values that
+ /// align with the map state, so both pieces of state describe the same
rows.
+ fn evaluate_orderings(&self, ordering_values: &[ArrayRef]) ->
Result<ScalarValue> {
+ let fields = ordering_fields(&self.ordering_req,
&self.ordering_dtypes);
+ let struct_array =
+ StructArray::try_new(Fields::from(fields),
ordering_values.to_vec(), None)?;
+
Ok(SingleRowListArrayBuilder::new(Arc::new(struct_array)).build_list_scalar())
+ }
+}
+
+impl Accumulator for OrderSensitiveMapAggAccumulator {
+ fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
+ assert_eq_or_internal_err!(
+ values.len(),
+ 2 + self.ordering_dtypes.len(),
+ "map_agg column count mismatch"
+ );
+ let keys = &values[0];
+ for array in &values[1..] {
+ assert_eq_or_internal_err!(
+ keys.len(),
+ array.len(),
+ "map_agg column length mismatch"
+ );
+ }
+ if keys.logical_null_count() != 0 {
+ return exec_err!("map key cannot be null");
+ }
+ if !keys.is_empty() {
+ self.batches.push(
+ values
+ .iter()
+ .map(|array| compact_array(Arc::clone(array)))
+ .collect::<Result<_>>()?,
+ );
+ }
+ Ok(())
+ }
+
+ fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
+ if states.is_empty() {
+ return Ok(());
+ }
+ if states.len() != 2 {
+ return exec_err!(
+ "map_agg ordered merge expects 2 state columns, got {}",
+ states.len()
+ );
+ }
+
+ let map_array = states[0].as_map();
+ let orderings = states[1].as_list::<i32>();
+
+ // Individually ordered partitions are not globally ordered. Sort once
+ // at output, including when the raw input was marked pre-ordered.
+ self.is_input_pre_ordered = false;
+ for row in 0..map_array.len() {
+ if map_array.is_null(row) {
+ continue;
+ }
+ let mut columns = map_row_to_arrays(map_array, row).to_vec();
+
columns.extend_from_slice(orderings.value(row).as_struct().columns());
+ self.update_batch(&columns)?;
+ }
+ Ok(())
+ }
+
+ fn state(&mut self) -> Result<Vec<ScalarValue>> {
+ let rows = self.sorted_deduped()?;
+ let orderings = self.evaluate_orderings(&rows[2..])?;
+ let map = build_single_map(Arc::clone(&rows[0]),
Arc::clone(&rows[1]))?;
+ Ok(vec![map, orderings])
+ }
+
+ fn evaluate(&mut self) -> Result<ScalarValue> {
+ let rows = self.sorted_deduped()?;
+ build_single_map(Arc::clone(&rows[0]), Arc::clone(&rows[1]))
+ }
+
+ fn size(&self) -> usize {
+ let mut total =
+ size_of_val(self) + batches_size(&self.batches) +
self.key_type.size()
+ - size_of_val(&self.key_type)
+ + self.value_type.size()
+ - size_of_val(&self.value_type);
+
+ // ordering_dtypes: Vec spine plus the heap owned by each DataType.
+ total += size_of::<DataType>() * self.ordering_dtypes.capacity();
+ for dtype in &self.ordering_dtypes {
+ total += dtype.size() - size_of_val(dtype);
+ }
+
+ total
+ }
+}
+
+/// Builds a single-row `Map` array holding `keys` and `values`.
+///
+/// An empty input yields a one-row array that is NULL, so empty groups
+/// evaluate to a NULL map just like [`MapAggAccumulator`] does.
+fn build_single_map(keys: ArrayRef, values: ArrayRef) -> Result<ScalarValue> {
+ let map_type = MapAgg::map_data_type(keys.data_type(), values.data_type());
+ let DataType::Map(entries_field, ordered) = &map_type else {
+ return internal_err!("map_agg expected Map type, got {map_type}");
+ };
+ let DataType::Struct(entry_fields) = entries_field.data_type() else {
+ return internal_err!(
+ "map_agg expected struct entries, got {}",
+ entries_field.data_type()
+ );
+ };
+
+ let entries = StructArray::try_new(entry_fields.clone(), vec![keys,
values], None)?;
+
+ let Ok(num_entries) = i32::try_from(entries.len()) else {
+ return internal_err!(
+ "map_agg produced {} entries which exceeds the map offset range",
+ entries.len()
+ );
+ };
+ let offsets = OffsetBuffer::new(ScalarBuffer::from(vec![0_i32,
num_entries]));
+ let nulls = entries.is_empty().then(|| NullBuffer::from(vec![false]));
+
+ Ok(ScalarValue::Map(Arc::new(MapArray::try_new(
+ Arc::clone(entries_field),
+ offsets,
+ entries,
+ nulls,
+ *ordered,
+ )?)))
+}
+
+fn map_row_to_arrays(map: &MapArray, row: usize) -> [ArrayRef; 2] {
+ let entries = map.value(row);
+ [Arc::clone(entries.column(0)), Arc::clone(entries.column(1))]
+}
+
+fn compact_array(array: ArrayRef) -> Result<ArrayRef> {
+ // Compact a whole column, including nested view buffers, rather than
+ // allocating one scalar per value or retaining the input batch's buffers.
+ let scalar = SingleRowListArrayBuilder::new(array)
+ .build_list_scalar()
+ .compacted();
Review Comment:
This compaction keeps unused dictionary values. I fed the unordered
accumulator one key and one dictionary-encoded value. With 10 entries in the
source dictionary, `size()` reported 1,652 bytes. With 10,000 entries, it
reported 565,428 bytes. The selected value and the resulting one-entry map were
identical in both runs. With `GROUP BY`, each group can be charged for the full
dictionary.
Could we share the dictionary compaction logic from ordered `array_agg` and
add a one-row test that checks the retained size stays bounded as the source
dictionary grows? [Existing compaction
logic](https://github.com/apache/datafusion/blob/8928d044747eecf1bb2b89def88273613d381716/datafusion/functions-aggregate/src/array_agg.rs#L2042-L2075)
--
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]