首页 > 解决方案 > Scala/Spark 聚合函数中的 lit(0) 和 lit(1) 有什么作用?

问题描述

我有这段代码:

val df = resultsDf
  .withColumn("data_exploded", explode(col("data_item")))
  .groupBy("data_id","data_count")
  .agg(
    count(lit(1)).as("aggDataCount"),
    sum(when(col("data_exploded.amount")==="A",col("data_exploded.positive_amount")).otherwise(lit(0))).as("aggAmount")
  )

lit(0)指位置 0 的索引,还是 number 的字面值0?我在https://mungingdata.com/apache-spark/spark-sql-functions/#:~:text=The%20lit()%20function%20creates,spanish_hi%20column%20to%20the%20DataFrame.&text看到的定义=%20lit()%20function%20is%20special%20useful%20when%20making%20boolean%20comparisons说“该lit()函数根据文字值创建一个 Column 对象。” 该定义使我认为它不是指索引位置,而是指文字值,例如数字或字符串。但是,在我看来,in 的用法count(lit(1)).as("aggDataCount")就像是指列的索引位置。谢谢你。

标签: scalaapache-spark

解决方案


lit(1)表示字面值1

count(lit(1)).as("aggDataCount")是一种计算行数的方法(每行都有一列,其值为1并对该列求和)


推荐阅读