我有一个聚合的DataFrame,其中包含使用collect_set
创建的列。现在,我需要再次对该DataFrame进行聚合,并将collect_set
再次应用于该列的值。问题是我需要对集合的值进行collect_Set
的验证-到目前为止,我看到的唯一方法是分解聚合的DataFrame。有更好的方法吗?
示例:
初始DataFrame:
country | continent | attributes
-------------------------------------
Canada | America | A
Belgium | Europe | Z
USA | America | A
Canada | America | B
France | Europe | Y
France | Europe | X
聚合的DataFrame(我收到的输入数据)-通过country
聚合:
country | continent | attributes
-------------------------------------
Canada | America | A, B
Belgium | Europe | Z
USA | America | A
France | Europe | Y, X
我想要的输出-通过continent
进行汇总:
continent | attributes
-------------------------------------
America | A, B
Europe | X, Y, Z
答案 0 :(得分:2)
由于此时您只能有少量的行,所以您只需按原样收集属性并将结果展平(Spark> = 2.4)
import org.apache.spark.sql.functions.{collect_set, flatten, array_distinct}
val byState = Seq(
("Canada", "America", Seq("A", "B")),
("Belgium", "Europe", Seq("Z")),
("USA", "America", Seq("A")),
("France", "Europe", Seq("Y", "X"))
).toDF("country", "continent", "attributes")
byState
.groupBy("continent")
.agg(array_distinct(flatten(collect_set($"attributes"))) as "attributes")
.show
+---------+----------+
|continent|attributes|
+---------+----------+
| Europe| [Y, X, Z]|
| America| [A, B]|
+---------+----------+
通常情况下,处理起来要困难得多,并且在许多情况下,如果您期望大型列表,每个组具有许多重复项和多个值,则最佳解决方案*是仅从头开始重新计算结果,即
input.groupBy($"continent").agg(collect_set($"attributes") as "attributes")
一种可能的替代方法是使用Aggregator
import org.apache.spark.sql.expressions.Aggregator
import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder
import org.apache.spark.sql.{Encoder, Encoders}
import scala.collection.mutable.{Set => MSet}
class MergeSets[T, U](f: T => Seq[U])(implicit enc: Encoder[Seq[U]]) extends
Aggregator[T, MSet[U], Seq[U]] with Serializable {
def zero = MSet.empty[U]
def reduce(acc: MSet[U], x: T) = {
for { v <- f(x) } acc.add(v)
acc
}
def merge(acc1: MSet[U], acc2: MSet[U]) = {
acc1 ++= acc2
}
def finish(acc: MSet[U]) = acc.toSeq
def bufferEncoder: Encoder[MSet[U]] = Encoders.kryo[MSet[U]]
def outputEncoder: Encoder[Seq[U]] = enc
}
并按如下所述应用它
case class CountryAggregate(
country: String, continent: String, attributes: Seq[String])
byState
.as[CountryAggregate]
.groupByKey(_.continent)
.agg(new MergeSets[CountryAggregate, String](_.attributes).toColumn)
.toDF("continent", "attributes")
.show
+---------+----------+
|continent|attributes|
+---------+----------+
| Europe| [X, Y, Z]|
| America| [B, A]|
+---------+----------+
但这显然不是Java友好的选项。
另请参见How to aggregate values into collection after groupBy?(相似,但没有唯一性约束)。
*这是因为explode
可能非常昂贵,尤其是在较旧的Spark版本中,与对SQL集合的外部表示的访问相同。