使用 Apache Spark DataFrame 或 SQL 的不同计数

Distinct counts using Apache Spark DataFrame or SQL

我的架构如下所示:

scala> airing.printSchema()
root
 |-- program: struct (nullable = true)
 |    |-- detail: struct (nullable = true)
 |    |    |-- contributors: array (nullable = true)
 |    |    |    |-- element: struct (containsNull = true)
 |    |    |    |    |-- contributorId: string (nullable = true)
 |    |    |    |    |-- name: string (nullable = true)
 |    |    |    |    |-- order: long (nullable = true)

我需要根据独特的Actors进行统计,找出最受欢迎的演员。 我的代码如下:

val castCounts = airing.groupBy("program.detail.contributors.name").count().sort(desc("count")).take(10)

令我震惊的是,我得到了重复项,如下面的快照所示。我希望每个演员都出现一次,并且有不同的计数:

正在打印以下结果:

[WrappedArray(),4344]
[WrappedArray(Matt Smith),16]
[WrappedArray(Phil Keoghan),15]
[WrappedArray(Don Adams, Barbara Feldon, Edward Platt),10]
[WrappedArray(Edward Platt, Don Adams, Barbara Feldon),10]

有2个步骤 使用 explode 函数使您的数据扁平化,这样每行数据只有 1 个贡献者。

  val df = airing.withColumn("contributor", explode(col("program.detail.contributors"))))

从新的 df 中获取结果,其中贡献者已爆炸。

  val castCounts = df.groupBy("contributor.name").count().sort(desc("count")).take(10)