|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +use arrow::array::ArrayRef; |
| 19 | +use arrow::datatypes::{DataType, Field, FieldRef}; |
| 20 | +use datafusion_common::utils::SingleRowListArrayBuilder; |
| 21 | +use datafusion_common::{Result, ScalarValue}; |
| 22 | +use datafusion_expr::function::{AccumulatorArgs, StateFieldsArgs}; |
| 23 | +use datafusion_expr::utils::format_state_name; |
| 24 | +use datafusion_expr::{Accumulator, AggregateUDFImpl, Signature, Volatility}; |
| 25 | +use datafusion_functions_aggregate::array_agg::{ |
| 26 | + ArrayAggAccumulator, DistinctArrayAggAccumulator, |
| 27 | +}; |
| 28 | +use std::{any::Any, sync::Arc}; |
| 29 | + |
| 30 | +// Spark implementation of collect_list/collect_set aggregate function. |
| 31 | +// Differs from DataFusion ArrayAgg in that it returns an empty list when all inputs are NULL and it doesn't respect/allow ordering. |
| 32 | + |
| 33 | +// <https://spark.apache.org/docs/latest/api/sql/index.html#collect_list> |
| 34 | +#[derive(Debug, PartialEq, Eq, Hash)] |
| 35 | +pub struct SparkCollectList { |
| 36 | + signature: Signature, |
| 37 | +} |
| 38 | + |
| 39 | +impl Default for SparkCollectList { |
| 40 | + fn default() -> Self { |
| 41 | + Self::new() |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +impl SparkCollectList { |
| 46 | + pub fn new() -> Self { |
| 47 | + Self { |
| 48 | + signature: Signature::any(1, Volatility::Immutable), |
| 49 | + } |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +impl AggregateUDFImpl for SparkCollectList { |
| 54 | + fn as_any(&self) -> &dyn Any { |
| 55 | + self |
| 56 | + } |
| 57 | + |
| 58 | + fn name(&self) -> &str { |
| 59 | + "collect_list" |
| 60 | + } |
| 61 | + |
| 62 | + fn signature(&self) -> &Signature { |
| 63 | + &self.signature |
| 64 | + } |
| 65 | + |
| 66 | + fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> { |
| 67 | + Ok(DataType::List(Arc::new(Field::new_list_field( |
| 68 | + arg_types[0].clone(), |
| 69 | + true, |
| 70 | + )))) |
| 71 | + } |
| 72 | + |
| 73 | + fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> { |
| 74 | + Ok(vec![ |
| 75 | + Field::new_list( |
| 76 | + format_state_name(args.name, "collect_list"), |
| 77 | + Field::new_list_field(args.input_fields[0].data_type().clone(), true), |
| 78 | + true, |
| 79 | + ) |
| 80 | + .into(), |
| 81 | + ]) |
| 82 | + } |
| 83 | + |
| 84 | + fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> { |
| 85 | + let field = &acc_args.expr_fields[0]; |
| 86 | + let data_type = field.data_type().clone(); |
| 87 | + let ignore_nulls = true; |
| 88 | + Ok(Box::new(NullToEmptyListAccumulator::new( |
| 89 | + ArrayAggAccumulator::try_new(&data_type, ignore_nulls)?, |
| 90 | + data_type, |
| 91 | + ))) |
| 92 | + } |
| 93 | +} |
| 94 | + |
| 95 | +// <https://spark.apache.org/docs/latest/api/sql/index.html#collect_set> |
| 96 | +#[derive(Debug, PartialEq, Eq, Hash)] |
| 97 | +pub struct SparkCollectSet { |
| 98 | + signature: Signature, |
| 99 | +} |
| 100 | + |
| 101 | +impl Default for SparkCollectSet { |
| 102 | + fn default() -> Self { |
| 103 | + Self::new() |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +impl SparkCollectSet { |
| 108 | + pub fn new() -> Self { |
| 109 | + Self { |
| 110 | + signature: Signature::any(1, Volatility::Immutable), |
| 111 | + } |
| 112 | + } |
| 113 | +} |
| 114 | + |
| 115 | +impl AggregateUDFImpl for SparkCollectSet { |
| 116 | + fn as_any(&self) -> &dyn Any { |
| 117 | + self |
| 118 | + } |
| 119 | + |
| 120 | + fn name(&self) -> &str { |
| 121 | + "collect_set" |
| 122 | + } |
| 123 | + |
| 124 | + fn signature(&self) -> &Signature { |
| 125 | + &self.signature |
| 126 | + } |
| 127 | + |
| 128 | + fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> { |
| 129 | + Ok(DataType::List(Arc::new(Field::new_list_field( |
| 130 | + arg_types[0].clone(), |
| 131 | + true, |
| 132 | + )))) |
| 133 | + } |
| 134 | + |
| 135 | + fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> { |
| 136 | + Ok(vec![ |
| 137 | + Field::new_list( |
| 138 | + format_state_name(args.name, "collect_set"), |
| 139 | + Field::new_list_field(args.input_fields[0].data_type().clone(), true), |
| 140 | + true, |
| 141 | + ) |
| 142 | + .into(), |
| 143 | + ]) |
| 144 | + } |
| 145 | + |
| 146 | + fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> { |
| 147 | + let field = &acc_args.expr_fields[0]; |
| 148 | + let data_type = field.data_type().clone(); |
| 149 | + let ignore_nulls = true; |
| 150 | + let inner = DistinctArrayAggAccumulator::try_new(&data_type, None, ignore_nulls)?; |
| 151 | + Ok(Box::new(NullToEmptyListAccumulator::new(inner, data_type))) |
| 152 | + } |
| 153 | +} |
| 154 | + |
| 155 | +/// Wrapper accumulator that returns an empty list instead of NULL when all inputs are NULL. |
| 156 | +/// This implements Spark's behavior for collect_list and collect_set. |
| 157 | +#[derive(Debug)] |
| 158 | +struct NullToEmptyListAccumulator<T: Accumulator> { |
| 159 | + inner: T, |
| 160 | + data_type: DataType, |
| 161 | +} |
| 162 | + |
| 163 | +impl<T: Accumulator> NullToEmptyListAccumulator<T> { |
| 164 | + pub fn new(inner: T, data_type: DataType) -> Self { |
| 165 | + Self { inner, data_type } |
| 166 | + } |
| 167 | +} |
| 168 | + |
| 169 | +impl<T: Accumulator> Accumulator for NullToEmptyListAccumulator<T> { |
| 170 | + fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> { |
| 171 | + self.inner.update_batch(values) |
| 172 | + } |
| 173 | + |
| 174 | + fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> { |
| 175 | + self.inner.merge_batch(states) |
| 176 | + } |
| 177 | + |
| 178 | + fn state(&mut self) -> Result<Vec<ScalarValue>> { |
| 179 | + self.inner.state() |
| 180 | + } |
| 181 | + |
| 182 | + fn evaluate(&mut self) -> Result<ScalarValue> { |
| 183 | + let result = self.inner.evaluate()?; |
| 184 | + if result.is_null() { |
| 185 | + let empty_array = arrow::array::new_empty_array(&self.data_type); |
| 186 | + Ok(SingleRowListArrayBuilder::new(empty_array).build_list_scalar()) |
| 187 | + } else { |
| 188 | + Ok(result) |
| 189 | + } |
| 190 | + } |
| 191 | + |
| 192 | + fn size(&self) -> usize { |
| 193 | + self.inner.size() + self.data_type.size() |
| 194 | + } |
| 195 | +} |
0 commit comments