Skip to content

程序员灯塔

Menu
  • Download
  • sitemap
  • 文章归档
  • 标签归档
  • 示例页面
Menu

org.apache.spark.sql.Column的构造并且设置别名

Posted on 2020 年 11 月 6 日

想通过配置调用agg方法, 不知如何构造spark.sql.Column, 所以研究了下, 记录下:

 

agg方法:

def agg(expr: Column, exprs: Column*): DataFrame = {
  toDF((expr +: exprs).map {
    case typed: TypedColumn[_, _] =>
      typed.withInputType(df.exprEnc, df.logicalPlan.output).expr
    case c => c.expr
  })
}


传的参数是Column, 但是我用的时候可以这样用:

aggDF = selectDF.groupBy(keysArr: _*).agg(countDistinct("num") as "cd", sum("num") as "sum")

所以有点疑惑  countDistinct(“num”) as “cd” 是Column么?

经过研究发现可以这样写:

先看图, 清晰点, 后面贴代码:

 

scala> var cc: Column = countDistinct("num")
cc: org.apache.spark.sql.Column = count(DISTINCT num)

scala> cc.as("distinctVal")
res25: org.apache.spark.sql.Column = count(DISTINCT num) AS `distinctVal`

scala> spark.table("t").groupBy("str").agg(cc, sum("num")).show
+---+-------------------+--------+
|str|count(DISTINCT num)|sum(num)|
+---+-------------------+--------+
|  f|                  1|      30|
|  e|                  1|       5|
|  z|                  2|     122|
|  d|                  1|       4|
|  c|                  1|       6|
|  b|                  1|       2|
|  a|                  1|       1|
+---+-------------------+--------+


scala> cc=cc.as("distinctVal")
cc: org.apache.spark.sql.Column = count(DISTINCT num) AS `distinctVal`

scala> spark.table("t").groupBy("str").agg(cc, sum("num")).show
+---+-----------+--------+
|str|distinctVal|sum(num)|
+---+-----------+--------+
|  f|          1|      30|
|  e|          1|       5|
|  z|          2|     122|
|  d|          1|       4|
|  c|          1|       6|
|  b|          1|       2|
|  a|          1|       1|
+---+-----------+--------+


近期文章

  • 技术网站
  • 世界,您好!
  • Git学习记录(learngitbranching.js.org)
  • 阿里职场潜规则
  • 寻找两个正序数组的中位数

近期评论

  1. 一位 WordPress 评论者 发表在 世界,您好!

归档

  • 2024 年 9 月
  • 2024 年 3 月
  • 2022 年 12 月
  • 2021 年 8 月
  • 2021 年 6 月
  • 2021 年 3 月
  • 2021 年 2 月
  • 2020 年 11 月
  • 2020 年 5 月
  • 2020 年 3 月
  • 2019 年 11 月
  • 2019 年 10 月
  • 2019 年 9 月
  • 2019 年 7 月
  • 2019 年 6 月
  • 2019 年 5 月
  • 2019 年 3 月
  • 2018 年 9 月
  • 2018 年 8 月
  • 2018 年 7 月
  • 2018 年 4 月
  • 2018 年 2 月
  • 2018 年 1 月
  • 2017 年 12 月
  • 2017 年 11 月
  • 2017 年 10 月
  • 2017 年 8 月
  • 2017 年 7 月

分类目录

  • 未分类
©2025 程序员灯塔 | Design: Newspaperly WordPress Theme