【问题标题】:Count(*) equivalent for Spark SQL in ScalaScala 中 Spark SQL 的 Count(*) 等效项
【发布时间】:2020-12-25 02:28:27
【问题描述】:

我想在聚合一些超过 1 列的数据集后计算行数, 例如

val iWantToCount = someDataSet
      .groupBy($"x", $"y")
      .agg(count().as("Num_of_rows"))
      

count 没有重载,它不接受任何参数。

我还有其他选择吗?

编辑:

count("*") 是正确的方法吗?

【问题讨论】:

  • count("1") 怎么样?
  • @GordonLinoff 我在另一个线程上读到,如果我使用 count(lit(1)) 就像写 count($"x") 这不是我想要的
  • 不是完全相同的副本,但可能会有所帮助:behavior of count function inside agg

标签: sql scala apache-spark apache-spark-sql


【解决方案1】:
import spark.implicits._

val df = Seq((1, "qwe", 1200),
    (1, "qwe", 1234),
    (1, "rte", 4673),
    (2, "ewr", 4245), (2, "ewr", 8973)
).toDF("col1", "col2", "col3")

println(df.groupBy("col1", "col2").count().count())

【讨论】:

  • 我想使用计数的结果作为聚合结果中的一列,所以生成的架构看起来像 col1 | col2 |行数
【解决方案2】:

试试这个脚本(使用lit需要下面的导入):

import.spark.implicits._

//dummy data    
val df = Seq((1, "qwe", 1200),
    (1, "qwe", 1234),
    (1, "rte", 4673),
    (2, "ewr", 4245), (2, "ewr", 8973)
).toDF("col1", "col2", "col3")

df.groupBy("col1","col2").agg(count(lit(1)).alias("num_of_rows")).show

数据根据第一两列进行分组,并推导出新列中的计数。

【讨论】:

  • 嗨 Rocky 欢迎来到堆栈溢出。仅代码答案有时会吸引反对票,为避免这种情况,我建议您添加一些词,例如“给定这样的数据框,我们可以执行如下所示的聚合”之类的东西。
【解决方案3】:

是的,您可以在agg() 中使用count("*")。同count(lit(1))

来源(见// Turn count(*) into count(1)下面源代码中的注释: https://github.com/apache/spark/blob/v3.2.1/sql/core/src/main/scala/org/apache/spark/sql/functions.scala

/**
   * Aggregate function: returns the number of items in a group.
   *
   * @group agg_funcs
   * @since 1.3.0
   */
  def count(e: Column): Column = withAggregateFunction {
    e.expr match {
      // Turn count(*) into count(1)
      case s: Star => Count(Literal(1))
      case _ => Count(e.expr)
    }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2010-12-07
    • 2015-01-18
    相关资源
    最近更新 更多