You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "ChuckLin2025 (via GitHub)" <gi...@apache.org> on 2026/07/28 04:16:28 UTC
[PR] [SPARK-XXXXX][SQL][PYTHON] Add `collect_union` aggregate function [spark]
ChuckLin2025 opened a new pull request, #57592:
URL: https://github.com/apache/spark/pull/57592
### What changes were proposed in this pull request?
This PR adds a new aggregate function `collect_union` that takes an
array-typed column and returns the distinct union of the elements of the
arrays across rows.
`collect_union(col: array<T>) : array<T>`
It is equivalent to `array_distinct(flatten(collect_list(col)))`, but the
aggregation buffer holds only the distinct elements (a `HashSet`), so its
size is bounded by the element universe rather than by the number of input
rows. This avoids buffering every row's whole array, which for a hot
grouping key can grow without bound.
The function is implemented as a `Collect[mutable.HashSet[Any]]`
(sibling of `collect_set`); the only material difference is that `update`
iterates the input array and adds each non-null element, and the result
element type is the input array's element type. NULL input arrays and NULL
elements are skipped, following `collect_set` semantics.
Added across the usual surfaces: Catalyst expression + registry, the Scala
DataFrame API, and PySpark (classic + Spark Connect). Spark Connect needs
no protocol change: the function travels as a generic `UnresolvedFunction`
resolved against the registry.
### Why are the changes needed?
There is no built-in aggregate that unions the elements of an array column
across rows into a single distinct array. The workaround
`array_distinct(flatten(collect_list(arr)))` buffers every row's whole
array before de-duplicating, which can OOM on skewed keys. `collect_union`
de-duplicates during aggregation, keeping the buffer bounded by the
distinct-element universe.
### Does this PR introduce _any_ user-facing change?
Yes. It adds a new SQL function `collect_union` and the corresponding
`functions.collect_union` in the Scala and Python DataFrame APIs.
### How was this patch tested?
- New `collect_union function` case in `DataFrameAggregateSuite` (distinct
union, NULL array, NULL element, per-group, empty result). Full suite:
170 tests, all pass.
- New `test_collect_union` in `python/pyspark/sql/tests/test_functions.py`
(passes end-to-end through the PySpark runtime).
- Spark Connect parity check in `test_connect_function.py`.
- `ExpressionsSchemaSuite` regenerated `sql-expression-schema.md`.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58399][SQL][PYTHON] Add `collect_union` aggregate function [spark]
Posted by "ChuckLin2025 (via GitHub)" <gi...@apache.org>.
ChuckLin2025 commented on PR #57592:
URL: https://github.com/apache/spark/pull/57592#issuecomment-5100521310
Hi @cloud-fan @srielau, could you help me review this PR.
Today for this kind of query:
select key1, key2, array_distinct(flatten(collect_list(array_col1))), array_distinct(flatten(collect_list(array_col2))) FROM ...
Spark can't run it in an effiecnt way, we have to buffer a huge array_of_array and perform array distinct on it later. Also it can be rewrote by collect_set in a graceful way. An additional join cost need to be paid, like
```
with col1 as (
select key1, key2, collect_set(col) as distinct_col1
FROM ... LATERAL VIEW explode(array_col1) e AS col
),
col2 as (
select key1, key2, collect_set(col) as distinct_col2
FROM ... LATERAL VIEW explode(array_col2) e AS col
)
select key1, key2, distinct_col1, distinct_col2
from col1 join col2
using (key1, key2)
```
So I propose to introdue this `collect_union` function to the `collect` familiy. Also this is already supported in googleSQL by ARRAY_CONCAT_AGG(distinct ...).
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58399][SQL][PYTHON] Add `collect_union` aggregate function [spark]
Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on PR #57592:
URL: https://github.com/apache/spark/pull/57592#issuecomment-5130454442
**Merge Summary:**
- merged into master https://github.com/apache/spark/commit/d5ec6583c9ce7d9bde1a2f9948ff4a563cd79f51
- merged into branch-4.x https://github.com/apache/spark/commit/eeab9be122c6be5b8760001fe256c26d2588a7b6
*Posted by `merge_spark_pr.py`*
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58399][SQL][PYTHON] Add `collect_union` aggregate function [spark]
Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #57592:
URL: https://github.com/apache/spark/pull/57592#discussion_r3675457447
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/collect.scala:
##########
@@ -316,6 +316,175 @@ case class CollectSet(
copy(child = newChild)
}
+/**
+ * Collect the distinct union of the elements of an array-typed input across rows.
+ *
+ * Unlike collect_set, whose input is a scalar and whose output is the set of those scalars,
+ * collect_union's input is itself an array and its output is the set of the array's
+ * *elements* unioned across all rows. The aggregation buffer holds only the distinct
+ * elements (a set), so its size is bounded by the element universe rather than by the
+ * number of input rows.
+ *
+ * Null handling mirrors collect_set: by default (IGNORE NULLS) null elements are dropped.
+ * With RESPECT NULLS, one null element is kept, in which case collect_union is equivalent to
+ * `array_distinct(flatten(collect_list(arr)))`.
+ *
+ * @param ignoreNulls when true (IGNORE NULLS, the default), null elements are excluded from
+ * the result array. When false (RESPECT NULLS), a single null element is
+ * kept.
+ */
+@ExpressionDescription(
+ usage =
+ "_FUNC_(expr) - Collects and returns the distinct union of the elements of array `expr`.",
+ examples = """
+ Examples:
+ > SELECT _FUNC_(col) FROM VALUES (array(1, 2)), (array(2, 3)), (array(1)) AS tab(col);
+ [1,2,3]
+ """,
+ note = """
+ The function is non-deterministic because the order of collected results depends
+ on the order of the rows which may be non-deterministic after a shuffle.
+ """,
+ group = "agg_funcs",
+ since = "4.3.0")
+case class CollectUnion(
+ child: Expression,
+ mutableAggBufferOffset: Int = 0,
+ inputAggBufferOffset: Int = 0,
+ ignoreNulls: Boolean = true)
+ extends Collect[mutable.HashSet[Any]] with QueryErrorsBase with UnaryLike[Expression] {
+
+ def this(child: Expression) = this(child, 0, 0, true)
+
+ // The input is guarded by checkInputDataTypes to be an ArrayType; this is its element type.
+ private lazy val elementType: DataType = child.dataType match {
+ case ArrayType(et, _) => et
+ case other => other
+ }
+
+ // The result array contains a null only when null elements are respected (RESPECT NULLS).
+ override protected def bufferContainsNull: Boolean = !ignoreNulls
+
+ // Result is array<elementType>; nullable iff null elements are kept.
Review Comment:
`nullable` describes whether the array value itself may be null, while this field controls whether its elements may be null.
```suggestion
// Result is array<elementType>; containsNull is true iff null elements are kept.
```
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58399][SQL][PYTHON] Add `collect_union` aggregate function [spark]
Posted by "ChuckLin2025 (via GitHub)" <gi...@apache.org>.
ChuckLin2025 commented on code in PR #57592:
URL: https://github.com/apache/spark/pull/57592#discussion_r3671170450
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/collect.scala:
##########
@@ -316,6 +316,150 @@ case class CollectSet(
copy(child = newChild)
}
+/**
+ * Collect the distinct union of the elements of an array-typed input across rows.
+ *
+ * Unlike collect_set, whose input is a scalar and whose output is the set of those scalars,
+ * collect_union's input is itself an array and its output is the set of the array's
+ * *elements* unioned across all rows. It is equivalent to
+ * `array_distinct(flatten(collect_list(arr)))`, but the aggregation buffer holds only the
+ * distinct elements (a set), so its size is bounded by the element universe rather than by
+ * the number of input rows.
+ */
+@ExpressionDescription(
+ usage =
+ "_FUNC_(expr) - Collects and returns the distinct union of the elements of array `expr`.",
+ examples = """
+ Examples:
+ > SELECT _FUNC_(col) FROM VALUES (array(1, 2)), (array(2, 3)), (array(1)) AS tab(col);
+ [1,2,3]
+ """,
+ note = """
+ The function is non-deterministic because the order of collected results depends
+ on the order of the rows which may be non-deterministic after a shuffle.
+ """,
+ group = "agg_funcs",
+ since = "4.3.0")
+case class CollectUnion(
+ child: Expression,
+ mutableAggBufferOffset: Int = 0,
+ inputAggBufferOffset: Int = 0)
+ extends Collect[mutable.HashSet[Any]] with QueryErrorsBase with UnaryLike[Expression] {
+
+ def this(child: Expression) = this(child, 0, 0)
+
+ // The element type of the input array. Guarded by checkInputDataTypes to be an ArrayType.
Review Comment:
Applied, 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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58399][SQL][PYTHON] Add `collect_union` aggregate function [spark]
Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #57592:
URL: https://github.com/apache/spark/pull/57592#discussion_r3665856406
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/collect.scala:
##########
@@ -316,6 +316,150 @@ case class CollectSet(
copy(child = newChild)
}
+/**
+ * Collect the distinct union of the elements of an array-typed input across rows.
+ *
+ * Unlike collect_set, whose input is a scalar and whose output is the set of those scalars,
+ * collect_union's input is itself an array and its output is the set of the array's
+ * *elements* unioned across all rows. It is equivalent to
+ * `array_distinct(flatten(collect_list(arr)))`, but the aggregation buffer holds only the
+ * distinct elements (a set), so its size is bounded by the element universe rather than by
+ * the number of input rows.
+ */
+@ExpressionDescription(
+ usage =
+ "_FUNC_(expr) - Collects and returns the distinct union of the elements of array `expr`.",
+ examples = """
+ Examples:
+ > SELECT _FUNC_(col) FROM VALUES (array(1, 2)), (array(2, 3)), (array(1)) AS tab(col);
+ [1,2,3]
+ """,
+ note = """
+ The function is non-deterministic because the order of collected results depends
+ on the order of the rows which may be non-deterministic after a shuffle.
+ """,
+ group = "agg_funcs",
+ since = "4.3.0")
+case class CollectUnion(
+ child: Expression,
+ mutableAggBufferOffset: Int = 0,
+ inputAggBufferOffset: Int = 0)
+ extends Collect[mutable.HashSet[Any]] with QueryErrorsBase with UnaryLike[Expression] {
+
+ def this(child: Expression) = this(child, 0, 0)
+
+ // The element type of the input array. Guarded by checkInputDataTypes to be an ArrayType.
+ private lazy val elementType: DataType = child.dataType match {
+ case ArrayType(et, _) => et
+ case other => other
+ }
+
+ // Result is array<elementType>; NULL elements are dropped, so it never contains nulls.
+ override def dataType: DataType = ArrayType(elementType, containsNull = false)
+
+ // The buffer stores distinct elements. Mirror CollectSet's keying so equality is correct
+ // for float/double (bit pattern) and binary (byte array) element types.
+ override lazy val bufferElementType: DataType = elementType match {
+ case BinaryType => ArrayType(ByteType)
+ case DoubleType => LongType
+ case FloatType => IntegerType
+ case other => other
+ }
+
+ @transient private lazy val complexNormalizer: Any => Any = {
+ val ref = BoundReference(0, elementType, nullable = true)
+ val proj = UnsafeProjection.create(NormalizeFloatingNumbers.normalize(ref))
+ (value: Any) => InternalRow.copyValue(proj(InternalRow(value)).get(0, elementType))
+ }
+
+ override def convertToBufferElement(value: Any): Any = elementType match {
+ // See CollectSet.convertToBufferElement for why binary/float/double are keyed specially.
+ case BinaryType => UnsafeArrayData.fromPrimitiveArray(value.asInstanceOf[Array[Byte]])
+ case DoubleType =>
+ java.lang.Double.doubleToLongBits(
+ NormalizeFloatingNumbers.DOUBLE_NORMALIZER(value).asInstanceOf[Double])
+ case FloatType =>
+ java.lang.Float.floatToIntBits(
+ NormalizeFloatingNumbers.FLOAT_NORMALIZER(value).asInstanceOf[Float])
+ case dt if NormalizeFloatingNumbers.needNormalize(dt) => complexNormalizer(value)
+ case _ => InternalRow.copyValue(value)
+ }
+
+ // Iterate the input array and add each non-null element to the set. NULL input arrays and
+ // NULL elements are skipped (following collect_set's ignore-null semantics).
+ override def update(
+ buffer: mutable.HashSet[Any],
+ input: InternalRow): mutable.HashSet[Any] = {
+ val arr = child.eval(input)
+ if (arr != null) {
+ arr.asInstanceOf[ArrayData].foreach(elementType, (_, element: Any) =>
+ if (element != null) {
Review Comment:
The documented equivalent expression preserves one null element, so this aggregate should do the same. For `array(1, NULL)`, `array_distinct(flatten(collect_list(...)))` returns `[1, NULL]`, but this branch drops the null and the result metadata declares `containsNull = false`. Please retain one null in the buffer, update the result nullability, and change the null-element test accordingly.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/collect.scala:
##########
@@ -316,6 +316,150 @@ case class CollectSet(
copy(child = newChild)
}
+/**
+ * Collect the distinct union of the elements of an array-typed input across rows.
+ *
+ * Unlike collect_set, whose input is a scalar and whose output is the set of those scalars,
+ * collect_union's input is itself an array and its output is the set of the array's
+ * *elements* unioned across all rows. It is equivalent to
+ * `array_distinct(flatten(collect_list(arr)))`, but the aggregation buffer holds only the
+ * distinct elements (a set), so its size is bounded by the element universe rather than by
+ * the number of input rows.
+ */
+@ExpressionDescription(
+ usage =
+ "_FUNC_(expr) - Collects and returns the distinct union of the elements of array `expr`.",
+ examples = """
+ Examples:
+ > SELECT _FUNC_(col) FROM VALUES (array(1, 2)), (array(2, 3)), (array(1)) AS tab(col);
+ [1,2,3]
+ """,
+ note = """
+ The function is non-deterministic because the order of collected results depends
+ on the order of the rows which may be non-deterministic after a shuffle.
+ """,
+ group = "agg_funcs",
+ since = "4.3.0")
+case class CollectUnion(
+ child: Expression,
+ mutableAggBufferOffset: Int = 0,
+ inputAggBufferOffset: Int = 0)
+ extends Collect[mutable.HashSet[Any]] with QueryErrorsBase with UnaryLike[Expression] {
+
+ def this(child: Expression) = this(child, 0, 0)
+
+ // The element type of the input array. Guarded by checkInputDataTypes to be an ArrayType.
Review Comment:
The second sentence currently makes the element type sound like the value guarded to be an `ArrayType`.
```suggestion
// The input is guarded by checkInputDataTypes to be an ArrayType; this is its element type.
```
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58399][SQL][PYTHON] Add `collect_union` aggregate function [spark]
Posted by "ChuckLin2025 (via GitHub)" <gi...@apache.org>.
ChuckLin2025 commented on code in PR #57592:
URL: https://github.com/apache/spark/pull/57592#discussion_r3670952584
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/collect.scala:
##########
@@ -316,6 +316,150 @@ case class CollectSet(
copy(child = newChild)
}
+/**
+ * Collect the distinct union of the elements of an array-typed input across rows.
+ *
+ * Unlike collect_set, whose input is a scalar and whose output is the set of those scalars,
+ * collect_union's input is itself an array and its output is the set of the array's
+ * *elements* unioned across all rows. It is equivalent to
+ * `array_distinct(flatten(collect_list(arr)))`, but the aggregation buffer holds only the
+ * distinct elements (a set), so its size is bounded by the element universe rather than by
+ * the number of input rows.
+ */
+@ExpressionDescription(
+ usage =
+ "_FUNC_(expr) - Collects and returns the distinct union of the elements of array `expr`.",
+ examples = """
+ Examples:
+ > SELECT _FUNC_(col) FROM VALUES (array(1, 2)), (array(2, 3)), (array(1)) AS tab(col);
+ [1,2,3]
+ """,
+ note = """
+ The function is non-deterministic because the order of collected results depends
+ on the order of the rows which may be non-deterministic after a shuffle.
+ """,
+ group = "agg_funcs",
+ since = "4.3.0")
+case class CollectUnion(
+ child: Expression,
+ mutableAggBufferOffset: Int = 0,
+ inputAggBufferOffset: Int = 0)
+ extends Collect[mutable.HashSet[Any]] with QueryErrorsBase with UnaryLike[Expression] {
+
+ def this(child: Expression) = this(child, 0, 0)
+
+ // The element type of the input array. Guarded by checkInputDataTypes to be an ArrayType.
+ private lazy val elementType: DataType = child.dataType match {
+ case ArrayType(et, _) => et
+ case other => other
+ }
+
+ // Result is array<elementType>; NULL elements are dropped, so it never contains nulls.
+ override def dataType: DataType = ArrayType(elementType, containsNull = false)
+
+ // The buffer stores distinct elements. Mirror CollectSet's keying so equality is correct
+ // for float/double (bit pattern) and binary (byte array) element types.
+ override lazy val bufferElementType: DataType = elementType match {
+ case BinaryType => ArrayType(ByteType)
+ case DoubleType => LongType
+ case FloatType => IntegerType
+ case other => other
+ }
+
+ @transient private lazy val complexNormalizer: Any => Any = {
+ val ref = BoundReference(0, elementType, nullable = true)
+ val proj = UnsafeProjection.create(NormalizeFloatingNumbers.normalize(ref))
+ (value: Any) => InternalRow.copyValue(proj(InternalRow(value)).get(0, elementType))
+ }
+
+ override def convertToBufferElement(value: Any): Any = elementType match {
+ // See CollectSet.convertToBufferElement for why binary/float/double are keyed specially.
+ case BinaryType => UnsafeArrayData.fromPrimitiveArray(value.asInstanceOf[Array[Byte]])
+ case DoubleType =>
+ java.lang.Double.doubleToLongBits(
+ NormalizeFloatingNumbers.DOUBLE_NORMALIZER(value).asInstanceOf[Double])
+ case FloatType =>
+ java.lang.Float.floatToIntBits(
+ NormalizeFloatingNumbers.FLOAT_NORMALIZER(value).asInstanceOf[Float])
+ case dt if NormalizeFloatingNumbers.needNormalize(dt) => complexNormalizer(value)
+ case _ => InternalRow.copyValue(value)
+ }
+
+ // Iterate the input array and add each non-null element to the set. NULL input arrays and
+ // NULL elements are skipped (following collect_set's ignore-null semantics).
+ override def update(
+ buffer: mutable.HashSet[Any],
+ input: InternalRow): mutable.HashSet[Any] = {
+ val arr = child.eval(input)
+ if (arr != null) {
+ arr.asInstanceOf[ArrayData].foreach(elementType, (_, element: Any) =>
+ if (element != null) {
Review Comment:
Looks like `array_distinct` is already inconsistnt with `collect_set`. and we need to make a decision here:
- Pick array_distinct's so that `collect_union` can fully replace `array_distinct(flatten(collect_list(...)))`. Like its document claims right now;
- Or pick `collect_set`'s, as they are in the same funciton family. Different null hanlding will bring confusing easier.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58399][SQL][PYTHON] Add `collect_union` aggregate function [spark]
Posted by "ChuckLin2025 (via GitHub)" <gi...@apache.org>.
ChuckLin2025 commented on code in PR #57592:
URL: https://github.com/apache/spark/pull/57592#discussion_r3670929550
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/collect.scala:
##########
@@ -316,6 +316,150 @@ case class CollectSet(
copy(child = newChild)
}
+/**
+ * Collect the distinct union of the elements of an array-typed input across rows.
+ *
+ * Unlike collect_set, whose input is a scalar and whose output is the set of those scalars,
+ * collect_union's input is itself an array and its output is the set of the array's
+ * *elements* unioned across all rows. It is equivalent to
+ * `array_distinct(flatten(collect_list(arr)))`, but the aggregation buffer holds only the
+ * distinct elements (a set), so its size is bounded by the element universe rather than by
+ * the number of input rows.
+ */
+@ExpressionDescription(
+ usage =
+ "_FUNC_(expr) - Collects and returns the distinct union of the elements of array `expr`.",
+ examples = """
+ Examples:
+ > SELECT _FUNC_(col) FROM VALUES (array(1, 2)), (array(2, 3)), (array(1)) AS tab(col);
+ [1,2,3]
+ """,
+ note = """
+ The function is non-deterministic because the order of collected results depends
+ on the order of the rows which may be non-deterministic after a shuffle.
+ """,
+ group = "agg_funcs",
+ since = "4.3.0")
+case class CollectUnion(
+ child: Expression,
+ mutableAggBufferOffset: Int = 0,
+ inputAggBufferOffset: Int = 0)
+ extends Collect[mutable.HashSet[Any]] with QueryErrorsBase with UnaryLike[Expression] {
+
+ def this(child: Expression) = this(child, 0, 0)
+
+ // The element type of the input array. Guarded by checkInputDataTypes to be an ArrayType.
+ private lazy val elementType: DataType = child.dataType match {
+ case ArrayType(et, _) => et
+ case other => other
+ }
+
+ // Result is array<elementType>; NULL elements are dropped, so it never contains nulls.
+ override def dataType: DataType = ArrayType(elementType, containsNull = false)
+
+ // The buffer stores distinct elements. Mirror CollectSet's keying so equality is correct
+ // for float/double (bit pattern) and binary (byte array) element types.
+ override lazy val bufferElementType: DataType = elementType match {
+ case BinaryType => ArrayType(ByteType)
+ case DoubleType => LongType
+ case FloatType => IntegerType
+ case other => other
+ }
+
+ @transient private lazy val complexNormalizer: Any => Any = {
+ val ref = BoundReference(0, elementType, nullable = true)
+ val proj = UnsafeProjection.create(NormalizeFloatingNumbers.normalize(ref))
+ (value: Any) => InternalRow.copyValue(proj(InternalRow(value)).get(0, elementType))
+ }
+
+ override def convertToBufferElement(value: Any): Any = elementType match {
+ // See CollectSet.convertToBufferElement for why binary/float/double are keyed specially.
+ case BinaryType => UnsafeArrayData.fromPrimitiveArray(value.asInstanceOf[Array[Byte]])
+ case DoubleType =>
+ java.lang.Double.doubleToLongBits(
+ NormalizeFloatingNumbers.DOUBLE_NORMALIZER(value).asInstanceOf[Double])
+ case FloatType =>
+ java.lang.Float.floatToIntBits(
+ NormalizeFloatingNumbers.FLOAT_NORMALIZER(value).asInstanceOf[Float])
+ case dt if NormalizeFloatingNumbers.needNormalize(dt) => complexNormalizer(value)
+ case _ => InternalRow.copyValue(value)
+ }
+
+ // Iterate the input array and add each non-null element to the set. NULL input arrays and
+ // NULL elements are skipped (following collect_set's ignore-null semantics).
+ override def update(
+ buffer: mutable.HashSet[Any],
+ input: InternalRow): mutable.HashSet[Any] = {
+ val arr = child.eval(input)
+ if (arr != null) {
+ arr.asInstanceOf[ArrayData].foreach(elementType, (_, element: Any) =>
+ if (element != null) {
Review Comment:
It's a little tricky here:
```
┌────────────────────────────────────────────┬────────────────┬──────────────┬─────────────────────────────────┐
│ Expression │ Input │ Result │ Keeps NULL? │
├────────────────────────────────────────────┼────────────────┼──────────────┼─────────────────────────────────┤
│ array_distinct(array(1, NULL, NULL)) │ one row │ [1, None] │ yes — keeps one │
├────────────────────────────────────────────┼────────────────┼──────────────┼─────────────────────────────────┤
│ array_distinct(flatten(collect_list(...))) │ [[1,NULL],[2]] │ [1, 2, None] │ yes — the documented equivalent │
├────────────────────────────────────────────┼────────────────┼──────────────┼─────────────────────────────────┤
│ collect_union (mine) │ [[1,NULL],[2]] │ [1, 2] │ no — drops it │
├────────────────────────────────────────────┼────────────────┼──────────────┼─────────────────────────────────┤
│ collect_set(1,NULL,2) │ scalars │ [1, 2] │ no │
└────────────────────────────────────────────┴────────────────┴──────────────┴─────────────────────────────────┘```
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58399][SQL][PYTHON] Add `collect_union` aggregate function [spark]
Posted by "ChuckLin2025 (via GitHub)" <gi...@apache.org>.
ChuckLin2025 commented on code in PR #57592:
URL: https://github.com/apache/spark/pull/57592#discussion_r3671168741
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/collect.scala:
##########
@@ -316,6 +316,150 @@ case class CollectSet(
copy(child = newChild)
}
+/**
+ * Collect the distinct union of the elements of an array-typed input across rows.
+ *
+ * Unlike collect_set, whose input is a scalar and whose output is the set of those scalars,
+ * collect_union's input is itself an array and its output is the set of the array's
+ * *elements* unioned across all rows. It is equivalent to
+ * `array_distinct(flatten(collect_list(arr)))`, but the aggregation buffer holds only the
+ * distinct elements (a set), so its size is bounded by the element universe rather than by
+ * the number of input rows.
+ */
+@ExpressionDescription(
+ usage =
+ "_FUNC_(expr) - Collects and returns the distinct union of the elements of array `expr`.",
+ examples = """
+ Examples:
+ > SELECT _FUNC_(col) FROM VALUES (array(1, 2)), (array(2, 3)), (array(1)) AS tab(col);
+ [1,2,3]
+ """,
+ note = """
+ The function is non-deterministic because the order of collected results depends
+ on the order of the rows which may be non-deterministic after a shuffle.
+ """,
+ group = "agg_funcs",
+ since = "4.3.0")
+case class CollectUnion(
+ child: Expression,
+ mutableAggBufferOffset: Int = 0,
+ inputAggBufferOffset: Int = 0)
+ extends Collect[mutable.HashSet[Any]] with QueryErrorsBase with UnaryLike[Expression] {
+
+ def this(child: Expression) = this(child, 0, 0)
+
+ // The element type of the input array. Guarded by checkInputDataTypes to be an ArrayType.
+ private lazy val elementType: DataType = child.dataType match {
+ case ArrayType(et, _) => et
+ case other => other
+ }
+
+ // Result is array<elementType>; NULL elements are dropped, so it never contains nulls.
+ override def dataType: DataType = ArrayType(elementType, containsNull = false)
+
+ // The buffer stores distinct elements. Mirror CollectSet's keying so equality is correct
+ // for float/double (bit pattern) and binary (byte array) element types.
+ override lazy val bufferElementType: DataType = elementType match {
+ case BinaryType => ArrayType(ByteType)
+ case DoubleType => LongType
+ case FloatType => IntegerType
+ case other => other
+ }
+
+ @transient private lazy val complexNormalizer: Any => Any = {
+ val ref = BoundReference(0, elementType, nullable = true)
+ val proj = UnsafeProjection.create(NormalizeFloatingNumbers.normalize(ref))
+ (value: Any) => InternalRow.copyValue(proj(InternalRow(value)).get(0, elementType))
+ }
+
+ override def convertToBufferElement(value: Any): Any = elementType match {
+ // See CollectSet.convertToBufferElement for why binary/float/double are keyed specially.
+ case BinaryType => UnsafeArrayData.fromPrimitiveArray(value.asInstanceOf[Array[Byte]])
+ case DoubleType =>
+ java.lang.Double.doubleToLongBits(
+ NormalizeFloatingNumbers.DOUBLE_NORMALIZER(value).asInstanceOf[Double])
+ case FloatType =>
+ java.lang.Float.floatToIntBits(
+ NormalizeFloatingNumbers.FLOAT_NORMALIZER(value).asInstanceOf[Float])
+ case dt if NormalizeFloatingNumbers.needNormalize(dt) => complexNormalizer(value)
+ case _ => InternalRow.copyValue(value)
+ }
+
+ // Iterate the input array and add each non-null element to the set. NULL input arrays and
+ // NULL elements are skipped (following collect_set's ignore-null semantics).
+ override def update(
+ buffer: mutable.HashSet[Any],
+ input: InternalRow): mutable.HashSet[Any] = {
+ val arr = child.eval(input)
+ if (arr != null) {
+ arr.asInstanceOf[ArrayData].foreach(elementType, (_, element: Any) =>
+ if (element != null) {
Review Comment:
Thanks -- I went with **supporting both `IGNORE`/`RESPECT NULLS`, defaulting to IGNORE**, matching `collect_list`/`collect_set`:
- **Default (IGNORE NULLS):** null elements dropped -- consistent with `collect_set` and the rest of the `collect` family.
- **RESPECT NULLS:** keeps a single null element, and in that mode `collect_union` is exactly `array_distinct(flatten(collect_list(...)))` (verified: `[[1,NULL],[2]]` -> `{1, 2, NULL}`).
This fixes the inconsistency: the buffer retains one null under RESPECT NULLS and the result's `containsNull` is derived from `ignoreNulls` (`!ignoreNulls`), so nullability metadata is correct in both modes. Wired `CollectUnion` into `FunctionResolution.applyIgnoreNulls` next to `CollectList`/`CollectSet`; updated the docs so the `array_distinct(flatten(collect_list))` equivalence is scoped to RESPECT NULLS; and split the null-element test into IGNORE (default) and RESPECT cases. Also applied your line-351 comment suggestion.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58399][SQL][PYTHON] Add `collect_union` aggregate function [spark]
Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan closed pull request #57592: [SPARK-58399][SQL][PYTHON] Add `collect_union` aggregate function
URL: https://github.com/apache/spark/pull/57592
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org