You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "LiaCastaneda (via GitHub)" <gi...@apache.org> on 2026/06/17 13:17:02 UTC

[PR] implement map_agg [datafusion]

LiaCastaneda opened a new pull request, #22996:
URL: https://github.com/apache/datafusion/pull/22996

   ## Which issue does this PR close?
   
   - Closes https://github.com/apache/datafusion/issues/22993
   
   
   ## Rationale for this change
   
   DataFusion has no way to aggregate key-value pairs into a map. map_agg is a common aggregate in other engines (Trino, Presto, Spark, Postgres via `json_object_agg`), and Arrow already has a native `MapArray` to back it. This PR adds it.
   
   
   
   ## What changes are included in this PR?
   
   New `map_agg(key, value)` aggregate function that collects key-value pairs into a `Map(K, V)`, one map per group.
   `ORDER BY` support (`map_agg(key, value ORDER BY expr)`).
   
   ## Are these changes tested?
   
   Yes
   
   - Unit tests in `map_agg.rs` covering pair collection, NULL-key skipping, NULL-value retention, first-wins dedup, multi-partition merge, and the ORDER BY ASC/DESC paths.
   - sqllogictest cases in `map_agg.slt` exercising `GROUP BY` and `ORDER BY` through the full SQL plan.
   
   ## Are there any user-facing changes?
   
   Yes -- adds a new `map_agg` aggregate function available from SQL. No breaking changes to existing APIs.


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] implement map_agg [datafusion]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #22996:
URL: https://github.com/apache/datafusion/pull/22996#issuecomment-5503121427

   Thank you for your contribution. Unfortunately, this pull request is stale because it has been open 60 days with no activity. Please remove the stale label or comment or this will be closed in 7 days.


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] implement map_agg [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #22996:
URL: https://github.com/apache/datafusion/pull/22996#discussion_r3459291325


##########
datafusion/functions-aggregate/src/map_agg.rs:
##########
@@ -0,0 +1,814 @@
+// 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::{HashSet, 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::{NullBuffer, OffsetBuffer, ScalarBuffer};
+use arrow::compute::SortOptions;
+use arrow::datatypes::{DataType, Field, FieldRef, Fields};
+
+use datafusion_common::utils::{SingleRowListArrayBuilder, 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.",

Review Comment:
   Suggested rewording: "For duplicate keys, the first value in aggregate order wins; use ORDER BY to make that order deterministic."



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] implement map_agg [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #22996:
URL: https://github.com/apache/datafusion/pull/22996#discussion_r3435738659


##########
datafusion/functions-aggregate/src/map_agg.rs:
##########
@@ -0,0 +1,710 @@
+// 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::{HashSet, 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::{SingleRowListArrayBuilder, 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 {

Review Comment:
   I’m not sure this should be a hard ordering requirement. The accumulator already stores the ORDER BY values and sorts internally, so the query can still produce a correct answer without the input already being sorted. Marking this as hard can force extra sorts and can also reject queries with multiple ordered aggregates that could otherwise be evaluated. Could this follow the array_agg pattern instead, where ordering is helpful but not required for correctness?



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] implement map_agg [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #22996:
URL: https://github.com/apache/datafusion/pull/22996#discussion_r3435742026


##########
datafusion/functions-aggregate/src/map_agg.rs:
##########
@@ -0,0 +1,710 @@
+// 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::{HashSet, 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::{SingleRowListArrayBuilder, 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 fields = Fields::from(vec![
+        Field::new("key", key_type.clone(), false),
+        Field::new("value", value_type.clone(), true),
+    ]);
+    let entries_field = Arc::new(Field::new("entries", DataType::Struct(fields), 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 fields = Fields::from(vec![
+        Field::new("key", key_type.clone(), false),
+        Field::new("value", value_type.clone(), true),
+    ]);
+    let entries_field = Arc::new(Field::new(
+        "entries",
+        DataType::Struct(fields.clone()),
+        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, 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,
+    )?))
+}
+
+fn dedup_first_wins(
+    keys: Vec<ScalarValue>,
+    values: Vec<ScalarValue>,
+) -> (Vec<ScalarValue>, Vec<ScalarValue>) {
+    // First pass: mark each position that is the first occurrence of its key.
+    let mut seen = HashSet::with_capacity(keys.len());
+    let keep: Vec<bool> = keys.iter().map(|k| seen.insert(k)).collect();
+
+    // Second pass: keep only the first-occurrence positions.
+    let out_keys = keys
+        .into_iter()
+        .zip(&keep)
+        .filter_map(|(k, &keep)| keep.then_some(k))
+        .collect();
+    let out_values = values
+        .into_iter()
+        .zip(&keep)
+        .filter_map(|(v, &keep)| keep.then_some(v))
+        .collect();
+    (out_keys, out_values)
+}
+
+/// 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();
+        Ok(dedup_first_wins(keys, values))
+    }
+
+    /// Builds the `List<Struct<ordering...>>` state column carrying ordering
+    /// values for every accumulated pair.
+    fn evaluate_orderings(&self) -> Result<ScalarValue> {
+        let fields = ordering_fields(&self.ordering_req, &self.ordering_dtypes);
+        let num_rows = self.ordering_values.len();
+        let struct_field = Fields::from(fields.clone());
+
+        let mut column_wise: Vec<ArrayRef> = Vec::with_capacity(fields.len());
+        for (col_idx, field) in fields.iter().enumerate() {
+            if num_rows == 0 {
+                column_wise.push(arrow::array::new_empty_array(field.data_type()));
+            } else {
+                let col_vals =
+                    self.ordering_values.iter().map(|row| row[col_idx].clone());
+                column_wise.push(ScalarValue::iter_to_array(col_vals)?);
+            }
+        }
+
+        let struct_array = StructArray::try_new(struct_field, column_wise, None)?;
+        Ok(SingleRowListArrayBuilder::new(Arc::new(struct_array)).build_list_scalar())
+    }
+}
+
+impl Accumulator for OrderSensitiveMapAggAccumulator {
+    fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
+        if values.len() < 2 {
+            return exec_err!("map_agg expects at least 2 columns, got {}", values.len());
+        }
+        let keys = &values[0];
+        let vals = &values[1];
+        let ordering_cols = &values[2..];
+
+        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());
+            self.ordering_values.push(
+                get_row_at_idx(ordering_cols, i)?
+                    .into_iter()
+                    .map(|v| v.compacted())
+                    .collect(),
+            );
+        }
+        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>();
+
+        // Each partition contributes one map row plus a parallel list of
+        // ordering-value structs. Collect them, then merge by ordering.
+        let mut partition_keys: Vec<VecDeque<ScalarValue>> =
+            vec![take(&mut self.keys).into()];
+        let mut partition_orderings: Vec<VecDeque<Vec<ScalarValue>>> =
+            vec![take(&mut self.ordering_values).into()];
+        let mut partition_values: Vec<VecDeque<ScalarValue>> =
+            vec![take(&mut self.values).into()];
+
+        // Push keys and values from each partition's state into the merge buffers.
+        for row in 0..map_array.len() {
+            if map_array.is_null(row) {
+                continue;
+            }
+            let (keys, values) = map_row_to_scalars(map_array, row)?;
+            let ord_vals = struct_to_rows(orderings.value(row).as_struct())?;
+
+            partition_keys.push(keys.into());
+            partition_values.push(values.into());
+            partition_orderings.push(ord_vals.into());
+        }
+
+        // Merge keys and values along the ordering. `merge_ordered_arrays`
+        // merges a single value stream; run it once for keys and once for
+        // values using the same ordering inputs so they stay aligned.
+        let sort_options = self.sort_options();
+
+        let (merged_keys, merged_orderings) = merge_ordered_arrays(
+            &mut partition_keys,
+            &mut partition_orderings.clone(),
+            &sort_options,
+        )?;
+        let (merged_values, _) = merge_ordered_arrays(
+            &mut partition_values,
+            &mut partition_orderings,
+            &sort_options,
+        )?;
+
+        self.keys = merged_keys;
+        self.values = merged_values;
+        self.ordering_values = merged_orderings;
+        Ok(())
+    }
+
+    fn state(&mut self) -> Result<Vec<ScalarValue>> {
+        let (keys, values) = self.sorted_deduped()?;
+        let map_array = build_single_map(keys, values, &self.key_type, &self.value_type)?;
+        Ok(vec![
+            ScalarValue::try_from_array(&map_array, 0)?,
+            self.evaluate_orderings()?,
+        ])
+    }
+
+    fn evaluate(&mut self) -> Result<ScalarValue> {
+        let (keys, values) = self.sorted_deduped()?;
+        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 {

Review Comment:
   Small accounting issue: this size() does not include the heap memory owned by key_type, value_type, or the nested ordering_dtypes. The plain accumulator accounts for the key/value types, so this one should probably do the same to avoid under-reporting memory use for larger or nested types.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] implement map_agg [datafusion]

Posted by "LiaCastaneda (via GitHub)" <gi...@apache.org>.
LiaCastaneda commented on code in PR #22996:
URL: https://github.com/apache/datafusion/pull/22996#discussion_r3441594549


##########
datafusion/functions-aggregate/src/map_agg.rs:
##########
@@ -0,0 +1,710 @@
+// 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::{HashSet, 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::{SingleRowListArrayBuilder, 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 {

Review Comment:
   yeah I thinkwe can skip having `HardRequirement`, i didn't specify `SoftRequirement` because we would need to handle the fast path in the code and wanted to leave that as a follow up but the change is small so I'll do it here, thanks 



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] implement map_agg [datafusion]

Posted by "LiaCastaneda (via GitHub)" <gi...@apache.org>.
LiaCastaneda commented on code in PR #22996:
URL: https://github.com/apache/datafusion/pull/22996#discussion_r3441463981


##########
datafusion/functions-aggregate/src/map_agg.rs:
##########
@@ -0,0 +1,710 @@
+// 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::{HashSet, 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::{SingleRowListArrayBuilder, 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 fields = Fields::from(vec![
+        Field::new("key", key_type.clone(), false),
+        Field::new("value", value_type.clone(), true),
+    ]);
+    let entries_field = Arc::new(Field::new("entries", DataType::Struct(fields), 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 fields = Fields::from(vec![
+        Field::new("key", key_type.clone(), false),
+        Field::new("value", value_type.clone(), true),
+    ]);
+    let entries_field = Arc::new(Field::new(
+        "entries",
+        DataType::Struct(fields.clone()),
+        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, 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,
+    )?))
+}
+
+fn dedup_first_wins(
+    keys: Vec<ScalarValue>,
+    values: Vec<ScalarValue>,
+) -> (Vec<ScalarValue>, Vec<ScalarValue>) {
+    // First pass: mark each position that is the first occurrence of its key.
+    let mut seen = HashSet::with_capacity(keys.len());
+    let keep: Vec<bool> = keys.iter().map(|k| seen.insert(k)).collect();
+
+    // Second pass: keep only the first-occurrence positions.
+    let out_keys = keys
+        .into_iter()
+        .zip(&keep)
+        .filter_map(|(k, &keep)| keep.then_some(k))
+        .collect();
+    let out_values = values
+        .into_iter()
+        .zip(&keep)
+        .filter_map(|(v, &keep)| keep.then_some(v))
+        .collect();
+    (out_keys, out_values)
+}
+
+/// 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();
+        Ok(dedup_first_wins(keys, values))
+    }
+
+    /// Builds the `List<Struct<ordering...>>` state column carrying ordering
+    /// values for every accumulated pair.
+    fn evaluate_orderings(&self) -> Result<ScalarValue> {
+        let fields = ordering_fields(&self.ordering_req, &self.ordering_dtypes);
+        let num_rows = self.ordering_values.len();
+        let struct_field = Fields::from(fields.clone());
+
+        let mut column_wise: Vec<ArrayRef> = Vec::with_capacity(fields.len());
+        for (col_idx, field) in fields.iter().enumerate() {
+            if num_rows == 0 {
+                column_wise.push(arrow::array::new_empty_array(field.data_type()));
+            } else {
+                let col_vals =
+                    self.ordering_values.iter().map(|row| row[col_idx].clone());
+                column_wise.push(ScalarValue::iter_to_array(col_vals)?);
+            }
+        }
+
+        let struct_array = StructArray::try_new(struct_field, column_wise, None)?;
+        Ok(SingleRowListArrayBuilder::new(Arc::new(struct_array)).build_list_scalar())
+    }
+}
+
+impl Accumulator for OrderSensitiveMapAggAccumulator {
+    fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
+        if values.len() < 2 {
+            return exec_err!("map_agg expects at least 2 columns, got {}", values.len());
+        }
+        let keys = &values[0];
+        let vals = &values[1];
+        let ordering_cols = &values[2..];
+
+        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());
+            self.ordering_values.push(
+                get_row_at_idx(ordering_cols, i)?
+                    .into_iter()
+                    .map(|v| v.compacted())
+                    .collect(),
+            );
+        }
+        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>();
+
+        // Each partition contributes one map row plus a parallel list of
+        // ordering-value structs. Collect them, then merge by ordering.
+        let mut partition_keys: Vec<VecDeque<ScalarValue>> =
+            vec![take(&mut self.keys).into()];
+        let mut partition_orderings: Vec<VecDeque<Vec<ScalarValue>>> =
+            vec![take(&mut self.ordering_values).into()];
+        let mut partition_values: Vec<VecDeque<ScalarValue>> =
+            vec![take(&mut self.values).into()];
+
+        // Push keys and values from each partition's state into the merge buffers.
+        for row in 0..map_array.len() {
+            if map_array.is_null(row) {
+                continue;
+            }
+            let (keys, values) = map_row_to_scalars(map_array, row)?;
+            let ord_vals = struct_to_rows(orderings.value(row).as_struct())?;
+
+            partition_keys.push(keys.into());
+            partition_values.push(values.into());
+            partition_orderings.push(ord_vals.into());
+        }
+
+        // Merge keys and values along the ordering. `merge_ordered_arrays`
+        // merges a single value stream; run it once for keys and once for
+        // values using the same ordering inputs so they stay aligned.
+        let sort_options = self.sort_options();
+
+        let (merged_keys, merged_orderings) = merge_ordered_arrays(
+            &mut partition_keys,
+            &mut partition_orderings.clone(),
+            &sort_options,
+        )?;
+        let (merged_values, _) = merge_ordered_arrays(
+            &mut partition_values,
+            &mut partition_orderings,
+            &sort_options,
+        )?;
+
+        self.keys = merged_keys;
+        self.values = merged_values;
+        self.ordering_values = merged_orderings;
+        Ok(())
+    }
+
+    fn state(&mut self) -> Result<Vec<ScalarValue>> {

Review Comment:
   yes, good catch https://github.com/apache/datafusion/pull/22996/commits/3aa09db75dbcadf335c7712a785b28058cc559a7



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] implement map_agg [datafusion]

Posted by "LiaCastaneda (via GitHub)" <gi...@apache.org>.
LiaCastaneda commented on code in PR #22996:
URL: https://github.com/apache/datafusion/pull/22996#discussion_r3441677287


##########
datafusion/functions-aggregate/src/map_agg.rs:
##########
@@ -0,0 +1,710 @@
+// 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::{HashSet, 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::{SingleRowListArrayBuilder, 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 fields = Fields::from(vec![
+        Field::new("key", key_type.clone(), false),
+        Field::new("value", value_type.clone(), true),
+    ]);
+    let entries_field = Arc::new(Field::new("entries", DataType::Struct(fields), 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 fields = Fields::from(vec![
+        Field::new("key", key_type.clone(), false),
+        Field::new("value", value_type.clone(), true),
+    ]);
+    let entries_field = Arc::new(Field::new(
+        "entries",
+        DataType::Struct(fields.clone()),
+        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, 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,
+    )?))
+}
+
+fn dedup_first_wins(
+    keys: Vec<ScalarValue>,
+    values: Vec<ScalarValue>,
+) -> (Vec<ScalarValue>, Vec<ScalarValue>) {
+    // First pass: mark each position that is the first occurrence of its key.
+    let mut seen = HashSet::with_capacity(keys.len());
+    let keep: Vec<bool> = keys.iter().map(|k| seen.insert(k)).collect();
+
+    // Second pass: keep only the first-occurrence positions.
+    let out_keys = keys
+        .into_iter()
+        .zip(&keep)
+        .filter_map(|(k, &keep)| keep.then_some(k))
+        .collect();
+    let out_values = values
+        .into_iter()
+        .zip(&keep)
+        .filter_map(|(v, &keep)| keep.then_some(v))
+        .collect();
+    (out_keys, out_values)
+}
+
+/// 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();
+        Ok(dedup_first_wins(keys, values))
+    }
+
+    /// Builds the `List<Struct<ordering...>>` state column carrying ordering
+    /// values for every accumulated pair.
+    fn evaluate_orderings(&self) -> Result<ScalarValue> {
+        let fields = ordering_fields(&self.ordering_req, &self.ordering_dtypes);
+        let num_rows = self.ordering_values.len();
+        let struct_field = Fields::from(fields.clone());
+
+        let mut column_wise: Vec<ArrayRef> = Vec::with_capacity(fields.len());
+        for (col_idx, field) in fields.iter().enumerate() {
+            if num_rows == 0 {
+                column_wise.push(arrow::array::new_empty_array(field.data_type()));
+            } else {
+                let col_vals =
+                    self.ordering_values.iter().map(|row| row[col_idx].clone());
+                column_wise.push(ScalarValue::iter_to_array(col_vals)?);
+            }
+        }
+
+        let struct_array = StructArray::try_new(struct_field, column_wise, None)?;
+        Ok(SingleRowListArrayBuilder::new(Arc::new(struct_array)).build_list_scalar())
+    }
+}
+
+impl Accumulator for OrderSensitiveMapAggAccumulator {
+    fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
+        if values.len() < 2 {
+            return exec_err!("map_agg expects at least 2 columns, got {}", values.len());
+        }
+        let keys = &values[0];
+        let vals = &values[1];
+        let ordering_cols = &values[2..];
+
+        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());
+            self.ordering_values.push(
+                get_row_at_idx(ordering_cols, i)?
+                    .into_iter()
+                    .map(|v| v.compacted())
+                    .collect(),
+            );
+        }
+        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>();
+
+        // Each partition contributes one map row plus a parallel list of
+        // ordering-value structs. Collect them, then merge by ordering.
+        let mut partition_keys: Vec<VecDeque<ScalarValue>> =
+            vec![take(&mut self.keys).into()];
+        let mut partition_orderings: Vec<VecDeque<Vec<ScalarValue>>> =
+            vec![take(&mut self.ordering_values).into()];
+        let mut partition_values: Vec<VecDeque<ScalarValue>> =
+            vec![take(&mut self.values).into()];
+
+        // Push keys and values from each partition's state into the merge buffers.
+        for row in 0..map_array.len() {
+            if map_array.is_null(row) {
+                continue;
+            }
+            let (keys, values) = map_row_to_scalars(map_array, row)?;
+            let ord_vals = struct_to_rows(orderings.value(row).as_struct())?;
+
+            partition_keys.push(keys.into());
+            partition_values.push(values.into());
+            partition_orderings.push(ord_vals.into());
+        }
+
+        // Merge keys and values along the ordering. `merge_ordered_arrays`
+        // merges a single value stream; run it once for keys and once for
+        // values using the same ordering inputs so they stay aligned.
+        let sort_options = self.sort_options();
+
+        let (merged_keys, merged_orderings) = merge_ordered_arrays(
+            &mut partition_keys,
+            &mut partition_orderings.clone(),
+            &sort_options,
+        )?;
+        let (merged_values, _) = merge_ordered_arrays(
+            &mut partition_values,
+            &mut partition_orderings,
+            &sort_options,
+        )?;
+
+        self.keys = merged_keys;
+        self.values = merged_values;
+        self.ordering_values = merged_orderings;
+        Ok(())
+    }
+
+    fn state(&mut self) -> Result<Vec<ScalarValue>> {
+        let (keys, values) = self.sorted_deduped()?;
+        let map_array = build_single_map(keys, values, &self.key_type, &self.value_type)?;
+        Ok(vec![
+            ScalarValue::try_from_array(&map_array, 0)?,
+            self.evaluate_orderings()?,
+        ])
+    }
+
+    fn evaluate(&mut self) -> Result<ScalarValue> {
+        let (keys, values) = self.sorted_deduped()?;
+        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 {
+        let mut total = 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);
+        total += size_of::<Vec<ScalarValue>>() * self.ordering_values.capacity();
+        for row in &self.ordering_values {
+            total += ScalarValue::size_of_vec(row) - size_of_val(row);
+        }
+        total += size_of::<DataType>() * self.ordering_dtypes.capacity();
+        total
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use arrow::array::{Int32Array, StringArray};
+    use arrow::datatypes::{Int32Type, Schema};
+    use datafusion_physical_expr::expressions::Column;
+    use datafusion_physical_expr_common::sort_expr::PhysicalSortExpr;
+
+    fn make_acc() -> MapAggAccumulator {
+        MapAggAccumulator::new(DataType::Utf8, DataType::Int32)
+    }
+
+    fn str_arr(vals: &[&str]) -> ArrayRef {
+        Arc::new(StringArray::from(vals.to_vec()))
+    }
+
+    fn int_arr(vals: &[i32]) -> ArrayRef {
+        Arc::new(Int32Array::from(vals.to_vec()))
+    }
+
+    fn str_arr_nullable(vals: Vec<Option<&str>>) -> ArrayRef {
+        Arc::new(StringArray::from(vals))
+    }
+
+    fn extract_map(sv: ScalarValue) -> Vec<(String, Option<i32>)> {
+        let ScalarValue::Map(arr) = sv else {
+            panic!("expected ScalarValue::Map, got {sv:?}");
+        };
+        let entries = arr.value(0);
+        let entries = entries.as_any().downcast_ref::<StructArray>().unwrap();
+        let keys = entries.column(0).as_string::<i32>();
+        let vals = entries.column(1).as_primitive::<Int32Type>();
+        (0..keys.len())
+            .map(|i| {
+                let v = if vals.is_null(i) {
+                    None
+                } else {
+                    Some(vals.value(i))
+                };
+                (keys.value(i).to_string(), v)
+            })
+            .collect()
+    }
+
+    #[test]
+    fn collects_distinct_pairs_in_order() -> Result<()> {
+        let mut acc = make_acc();
+        acc.update_batch(&[str_arr(&["a", "b", "c"]), int_arr(&[1, 2, 3])])?;
+        let pairs = extract_map(acc.evaluate()?);
+        assert_eq!(
+            pairs,
+            vec![
+                ("a".into(), Some(1)),
+                ("b".into(), Some(2)),
+                ("c".into(), Some(3)),
+            ]
+        );
+        Ok(())
+    }
+
+    #[test]
+    fn null_key_skipped() -> Result<()> {
+        let mut acc = make_acc();
+        // A null-key pair is dropped (matches Trino map_agg).
+        acc.update_batch(&[
+            str_arr_nullable(vec![Some("a"), None, Some("c")]),
+            int_arr(&[1, 2, 3]),
+        ])?;
+        let pairs = extract_map(acc.evaluate()?);
+        assert_eq!(pairs.len(), 2);
+        assert_eq!(pairs[0].0, "a");
+        assert_eq!(pairs[1].0, "c");
+        Ok(())
+    }
+
+    #[test]
+    fn null_value_retained() -> Result<()> {
+        let mut acc = make_acc();
+        let vals: ArrayRef = Arc::new(Int32Array::from(vec![Some(1), None, Some(3)]));
+        acc.update_batch(&[str_arr(&["a", "b", "c"]), vals])?;
+        let pairs = extract_map(acc.evaluate()?);
+        assert_eq!(pairs[1], ("b".into(), None));
+        Ok(())
+    }
+
+    #[test]
+    fn duplicate_key_first_wins() -> Result<()> {
+        let mut acc = make_acc();
+        // a appears twice; the first value (1) wins, later one is dropped.
+        acc.update_batch(&[str_arr(&["a", "b", "a"]), int_arr(&[1, 2, 3])])?;
+        let pairs = extract_map(acc.evaluate()?);
+        assert_eq!(pairs, vec![("a".into(), Some(1)), ("b".into(), Some(2))]);
+        Ok(())
+    }
+
+    #[test]
+    fn empty_produces_empty_map() -> Result<()> {

Review Comment:
   Yeah I think it should return NULL, trino/postgres returns null as well.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] implement map_agg [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #22996:
URL: https://github.com/apache/datafusion/pull/22996#discussion_r3442788342


##########
datafusion/functions-aggregate/src/map_agg.rs:
##########
@@ -0,0 +1,710 @@
+// 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::{HashSet, 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::{SingleRowListArrayBuilder, 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,
+        )))
+    }

Review Comment:
   Yep, follow up PR makes the most sense: this isn't a fix like the other comments.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] implement map_agg [datafusion]

Posted by "LiaCastaneda (via GitHub)" <gi...@apache.org>.
LiaCastaneda commented on code in PR #22996:
URL: https://github.com/apache/datafusion/pull/22996#discussion_r3441824180


##########
datafusion/functions-aggregate/src/map_agg.rs:
##########
@@ -0,0 +1,710 @@
+// 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::{HashSet, 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::{SingleRowListArrayBuilder, 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,
+        )))
+    }

Review Comment:
   Makes sense. However, would it be ok to leave this as a follow up pr? I can branch the follow up off this one. This PR is getting quite large, and I'm afraid it'll be cumbersome to review if it grows further.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] implement map_agg [datafusion]

Posted by "LiaCastaneda (via GitHub)" <gi...@apache.org>.
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] implement map_agg [datafusion]

Posted by "LiaCastaneda (via GitHub)" <gi...@apache.org>.
LiaCastaneda commented on PR #22996:
URL: https://github.com/apache/datafusion/pull/22996#issuecomment-4876916915

   closing this one until someone else needs it! we are implementing it as a UDAF


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] implement map_agg [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #22996:
URL: https://github.com/apache/datafusion/pull/22996#discussion_r3442788342


##########
datafusion/functions-aggregate/src/map_agg.rs:
##########
@@ -0,0 +1,710 @@
+// 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::{HashSet, 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::{SingleRowListArrayBuilder, 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,
+        )))
+    }

Review Comment:
   Yep, follow up PR makes the most sense.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] implement map_agg [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #22996:
URL: https://github.com/apache/datafusion/pull/22996#discussion_r3435737470


##########
datafusion/functions-aggregate/src/map_agg.rs:
##########
@@ -0,0 +1,710 @@
+// 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::{HashSet, 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::{SingleRowListArrayBuilder, 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 fields = Fields::from(vec![
+        Field::new("key", key_type.clone(), false),
+        Field::new("value", value_type.clone(), true),
+    ]);
+    let entries_field = Arc::new(Field::new("entries", DataType::Struct(fields), 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 fields = Fields::from(vec![
+        Field::new("key", key_type.clone(), false),
+        Field::new("value", value_type.clone(), true),
+    ]);
+    let entries_field = Arc::new(Field::new(
+        "entries",
+        DataType::Struct(fields.clone()),
+        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, 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,
+    )?))
+}
+
+fn dedup_first_wins(
+    keys: Vec<ScalarValue>,
+    values: Vec<ScalarValue>,
+) -> (Vec<ScalarValue>, Vec<ScalarValue>) {
+    // First pass: mark each position that is the first occurrence of its key.
+    let mut seen = HashSet::with_capacity(keys.len());
+    let keep: Vec<bool> = keys.iter().map(|k| seen.insert(k)).collect();
+
+    // Second pass: keep only the first-occurrence positions.
+    let out_keys = keys
+        .into_iter()
+        .zip(&keep)
+        .filter_map(|(k, &keep)| keep.then_some(k))
+        .collect();
+    let out_values = values
+        .into_iter()
+        .zip(&keep)
+        .filter_map(|(v, &keep)| keep.then_some(v))
+        .collect();
+    (out_keys, out_values)
+}
+
+/// 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();
+        Ok(dedup_first_wins(keys, values))
+    }
+
+    /// Builds the `List<Struct<ordering...>>` state column carrying ordering
+    /// values for every accumulated pair.
+    fn evaluate_orderings(&self) -> Result<ScalarValue> {
+        let fields = ordering_fields(&self.ordering_req, &self.ordering_dtypes);
+        let num_rows = self.ordering_values.len();
+        let struct_field = Fields::from(fields.clone());
+
+        let mut column_wise: Vec<ArrayRef> = Vec::with_capacity(fields.len());
+        for (col_idx, field) in fields.iter().enumerate() {
+            if num_rows == 0 {
+                column_wise.push(arrow::array::new_empty_array(field.data_type()));
+            } else {
+                let col_vals =
+                    self.ordering_values.iter().map(|row| row[col_idx].clone());
+                column_wise.push(ScalarValue::iter_to_array(col_vals)?);
+            }
+        }
+
+        let struct_array = StructArray::try_new(struct_field, column_wise, None)?;
+        Ok(SingleRowListArrayBuilder::new(Arc::new(struct_array)).build_list_scalar())
+    }
+}
+
+impl Accumulator for OrderSensitiveMapAggAccumulator {
+    fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
+        if values.len() < 2 {
+            return exec_err!("map_agg expects at least 2 columns, got {}", values.len());
+        }
+        let keys = &values[0];
+        let vals = &values[1];
+        let ordering_cols = &values[2..];
+
+        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());
+            self.ordering_values.push(
+                get_row_at_idx(ordering_cols, i)?
+                    .into_iter()
+                    .map(|v| v.compacted())
+                    .collect(),
+            );
+        }
+        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>();
+
+        // Each partition contributes one map row plus a parallel list of
+        // ordering-value structs. Collect them, then merge by ordering.
+        let mut partition_keys: Vec<VecDeque<ScalarValue>> =
+            vec![take(&mut self.keys).into()];
+        let mut partition_orderings: Vec<VecDeque<Vec<ScalarValue>>> =
+            vec![take(&mut self.ordering_values).into()];
+        let mut partition_values: Vec<VecDeque<ScalarValue>> =
+            vec![take(&mut self.values).into()];
+
+        // Push keys and values from each partition's state into the merge buffers.
+        for row in 0..map_array.len() {
+            if map_array.is_null(row) {
+                continue;
+            }
+            let (keys, values) = map_row_to_scalars(map_array, row)?;
+            let ord_vals = struct_to_rows(orderings.value(row).as_struct())?;
+
+            partition_keys.push(keys.into());
+            partition_values.push(values.into());
+            partition_orderings.push(ord_vals.into());
+        }
+
+        // Merge keys and values along the ordering. `merge_ordered_arrays`
+        // merges a single value stream; run it once for keys and once for
+        // values using the same ordering inputs so they stay aligned.
+        let sort_options = self.sort_options();
+
+        let (merged_keys, merged_orderings) = merge_ordered_arrays(
+            &mut partition_keys,
+            &mut partition_orderings.clone(),
+            &sort_options,
+        )?;
+        let (merged_values, _) = merge_ordered_arrays(
+            &mut partition_values,
+            &mut partition_orderings,
+            &sort_options,
+        )?;
+
+        self.keys = merged_keys;
+        self.values = merged_values;
+        self.ordering_values = merged_orderings;
+        Ok(())
+    }
+
+    fn state(&mut self) -> Result<Vec<ScalarValue>> {

Review Comment:
   I think this can produce incorrect partial results when ORDER BY is used. The map state is built from the sorted and de-duplicated keys and values, but the ordering state is still built from the original ordering values. If a partition has duplicate keys, these two pieces of state no longer describe the same rows, so the final merge can either fail or pair a key/value with the wrong ordering value. Could we build the ordering state from the same sorted/de-duplicated rows used for the map?



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] implement map_agg [datafusion]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] closed pull request #22996: implement map_agg
URL: https://github.com/apache/datafusion/pull/22996


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] implement map_agg [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #22996:
URL: https://github.com/apache/datafusion/pull/22996#discussion_r3435739885


##########
datafusion/functions-aggregate/src/map_agg.rs:
##########
@@ -0,0 +1,710 @@
+// 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::{HashSet, 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::{SingleRowListArrayBuilder, 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 fields = Fields::from(vec![
+        Field::new("key", key_type.clone(), false),
+        Field::new("value", value_type.clone(), true),
+    ]);
+    let entries_field = Arc::new(Field::new("entries", DataType::Struct(fields), 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 fields = Fields::from(vec![
+        Field::new("key", key_type.clone(), false),
+        Field::new("value", value_type.clone(), true),
+    ]);
+    let entries_field = Arc::new(Field::new(
+        "entries",
+        DataType::Struct(fields.clone()),
+        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, 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,
+    )?))
+}
+
+fn dedup_first_wins(
+    keys: Vec<ScalarValue>,
+    values: Vec<ScalarValue>,
+) -> (Vec<ScalarValue>, Vec<ScalarValue>) {
+    // First pass: mark each position that is the first occurrence of its key.
+    let mut seen = HashSet::with_capacity(keys.len());
+    let keep: Vec<bool> = keys.iter().map(|k| seen.insert(k)).collect();
+
+    // Second pass: keep only the first-occurrence positions.
+    let out_keys = keys
+        .into_iter()
+        .zip(&keep)
+        .filter_map(|(k, &keep)| keep.then_some(k))
+        .collect();
+    let out_values = values
+        .into_iter()
+        .zip(&keep)
+        .filter_map(|(v, &keep)| keep.then_some(v))
+        .collect();
+    (out_keys, out_values)
+}
+
+/// 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();
+        Ok(dedup_first_wins(keys, values))
+    }
+
+    /// Builds the `List<Struct<ordering...>>` state column carrying ordering
+    /// values for every accumulated pair.
+    fn evaluate_orderings(&self) -> Result<ScalarValue> {
+        let fields = ordering_fields(&self.ordering_req, &self.ordering_dtypes);
+        let num_rows = self.ordering_values.len();
+        let struct_field = Fields::from(fields.clone());
+
+        let mut column_wise: Vec<ArrayRef> = Vec::with_capacity(fields.len());
+        for (col_idx, field) in fields.iter().enumerate() {
+            if num_rows == 0 {
+                column_wise.push(arrow::array::new_empty_array(field.data_type()));
+            } else {
+                let col_vals =
+                    self.ordering_values.iter().map(|row| row[col_idx].clone());
+                column_wise.push(ScalarValue::iter_to_array(col_vals)?);
+            }
+        }
+
+        let struct_array = StructArray::try_new(struct_field, column_wise, None)?;
+        Ok(SingleRowListArrayBuilder::new(Arc::new(struct_array)).build_list_scalar())
+    }
+}
+
+impl Accumulator for OrderSensitiveMapAggAccumulator {
+    fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
+        if values.len() < 2 {
+            return exec_err!("map_agg expects at least 2 columns, got {}", values.len());
+        }
+        let keys = &values[0];
+        let vals = &values[1];
+        let ordering_cols = &values[2..];
+
+        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());
+            self.ordering_values.push(
+                get_row_at_idx(ordering_cols, i)?
+                    .into_iter()
+                    .map(|v| v.compacted())
+                    .collect(),
+            );
+        }
+        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>();
+
+        // Each partition contributes one map row plus a parallel list of
+        // ordering-value structs. Collect them, then merge by ordering.
+        let mut partition_keys: Vec<VecDeque<ScalarValue>> =
+            vec![take(&mut self.keys).into()];
+        let mut partition_orderings: Vec<VecDeque<Vec<ScalarValue>>> =
+            vec![take(&mut self.ordering_values).into()];
+        let mut partition_values: Vec<VecDeque<ScalarValue>> =
+            vec![take(&mut self.values).into()];
+
+        // Push keys and values from each partition's state into the merge buffers.
+        for row in 0..map_array.len() {
+            if map_array.is_null(row) {
+                continue;
+            }
+            let (keys, values) = map_row_to_scalars(map_array, row)?;
+            let ord_vals = struct_to_rows(orderings.value(row).as_struct())?;
+
+            partition_keys.push(keys.into());
+            partition_values.push(values.into());
+            partition_orderings.push(ord_vals.into());
+        }
+
+        // Merge keys and values along the ordering. `merge_ordered_arrays`
+        // merges a single value stream; run it once for keys and once for
+        // values using the same ordering inputs so they stay aligned.
+        let sort_options = self.sort_options();
+
+        let (merged_keys, merged_orderings) = merge_ordered_arrays(
+            &mut partition_keys,
+            &mut partition_orderings.clone(),
+            &sort_options,
+        )?;
+        let (merged_values, _) = merge_ordered_arrays(
+            &mut partition_values,
+            &mut partition_orderings,
+            &sort_options,
+        )?;
+
+        self.keys = merged_keys;
+        self.values = merged_values;
+        self.ordering_values = merged_orderings;
+        Ok(())
+    }
+
+    fn state(&mut self) -> Result<Vec<ScalarValue>> {
+        let (keys, values) = self.sorted_deduped()?;
+        let map_array = build_single_map(keys, values, &self.key_type, &self.value_type)?;
+        Ok(vec![
+            ScalarValue::try_from_array(&map_array, 0)?,
+            self.evaluate_orderings()?,
+        ])
+    }
+
+    fn evaluate(&mut self) -> Result<ScalarValue> {
+        let (keys, values) = self.sorted_deduped()?;
+        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 {
+        let mut total = 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);
+        total += size_of::<Vec<ScalarValue>>() * self.ordering_values.capacity();
+        for row in &self.ordering_values {
+            total += ScalarValue::size_of_vec(row) - size_of_val(row);
+        }
+        total += size_of::<DataType>() * self.ordering_dtypes.capacity();
+        total
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use arrow::array::{Int32Array, StringArray};
+    use arrow::datatypes::{Int32Type, Schema};
+    use datafusion_physical_expr::expressions::Column;
+    use datafusion_physical_expr_common::sort_expr::PhysicalSortExpr;
+
+    fn make_acc() -> MapAggAccumulator {
+        MapAggAccumulator::new(DataType::Utf8, DataType::Int32)
+    }
+
+    fn str_arr(vals: &[&str]) -> ArrayRef {
+        Arc::new(StringArray::from(vals.to_vec()))
+    }
+
+    fn int_arr(vals: &[i32]) -> ArrayRef {
+        Arc::new(Int32Array::from(vals.to_vec()))
+    }
+
+    fn str_arr_nullable(vals: Vec<Option<&str>>) -> ArrayRef {
+        Arc::new(StringArray::from(vals))
+    }
+
+    fn extract_map(sv: ScalarValue) -> Vec<(String, Option<i32>)> {
+        let ScalarValue::Map(arr) = sv else {
+            panic!("expected ScalarValue::Map, got {sv:?}");
+        };
+        let entries = arr.value(0);
+        let entries = entries.as_any().downcast_ref::<StructArray>().unwrap();
+        let keys = entries.column(0).as_string::<i32>();
+        let vals = entries.column(1).as_primitive::<Int32Type>();
+        (0..keys.len())
+            .map(|i| {
+                let v = if vals.is_null(i) {
+                    None
+                } else {
+                    Some(vals.value(i))
+                };
+                (keys.value(i).to_string(), v)
+            })
+            .collect()
+    }
+
+    #[test]
+    fn collects_distinct_pairs_in_order() -> Result<()> {
+        let mut acc = make_acc();
+        acc.update_batch(&[str_arr(&["a", "b", "c"]), int_arr(&[1, 2, 3])])?;
+        let pairs = extract_map(acc.evaluate()?);
+        assert_eq!(
+            pairs,
+            vec![
+                ("a".into(), Some(1)),
+                ("b".into(), Some(2)),
+                ("c".into(), Some(3)),
+            ]
+        );
+        Ok(())
+    }
+
+    #[test]
+    fn null_key_skipped() -> Result<()> {
+        let mut acc = make_acc();
+        // A null-key pair is dropped (matches Trino map_agg).
+        acc.update_batch(&[
+            str_arr_nullable(vec![Some("a"), None, Some("c")]),
+            int_arr(&[1, 2, 3]),
+        ])?;
+        let pairs = extract_map(acc.evaluate()?);
+        assert_eq!(pairs.len(), 2);
+        assert_eq!(pairs[0].0, "a");
+        assert_eq!(pairs[1].0, "c");
+        Ok(())
+    }
+
+    #[test]
+    fn null_value_retained() -> Result<()> {
+        let mut acc = make_acc();
+        let vals: ArrayRef = Arc::new(Int32Array::from(vec![Some(1), None, Some(3)]));
+        acc.update_batch(&[str_arr(&["a", "b", "c"]), vals])?;
+        let pairs = extract_map(acc.evaluate()?);
+        assert_eq!(pairs[1], ("b".into(), None));
+        Ok(())
+    }
+
+    #[test]
+    fn duplicate_key_first_wins() -> Result<()> {
+        let mut acc = make_acc();
+        // a appears twice; the first value (1) wins, later one is dropped.
+        acc.update_batch(&[str_arr(&["a", "b", "a"]), int_arr(&[1, 2, 3])])?;
+        let pairs = extract_map(acc.evaluate()?);
+        assert_eq!(pairs, vec![("a".into(), Some(1)), ("b".into(), Some(2))]);
+        Ok(())
+    }
+
+    #[test]
+    fn empty_produces_empty_map() -> Result<()> {

Review Comment:
   Should empty input return NULL instead of an empty map? array_agg returns NULL for empty input in DataFusion, and most aggregates here follow that convention for no rows contributed. Returning an empty map is understandable, but it makes map_agg behave differently from array_agg. If the empty map behavior is intentional, could we document it and add SQL tests for both empty input and all-NULL keys?



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] implement map_agg [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #22996:
URL: https://github.com/apache/datafusion/pull/22996#discussion_r3435741112


##########
datafusion/functions-aggregate/src/map_agg.rs:
##########
@@ -0,0 +1,710 @@
+// 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::{HashSet, 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::{SingleRowListArrayBuilder, 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,
+        )))
+    }

Review Comment:
   Since map_agg will commonly be used with GROUP BY, I think the simple grouped case could use a specialized groups accumulator. Without one, DataFusion creates one separate accumulator per group, which adds overhead for many groups. array_agg and string_agg both have a faster grouped path for the simple non-ORDER BY case; could we add the same kind of path for map_agg(key, value) and leave the ordered case on the generic path for now?



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] implement map_agg [datafusion]

Posted by "LiaCastaneda (via GitHub)" <gi...@apache.org>.
LiaCastaneda closed pull request #22996: implement map_agg
URL: https://github.com/apache/datafusion/pull/22996


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org