scala - 为什么在使用 Spark sql 过滤特定聚合的行时出现类型不匹配?

标签 scala dataframe apache-spark parquet

所以我有这个数据框sheepDF:

--------------------------------------
| sheep_id | sheep_age | sheep_color |
--------------------------------------
|    1     |     1     |    gray     |
|    2     |     2     |    grey     |
|    3     |     2     |             |
|    4     |     3     |    white    |
|    5     |     3     |             |
--------------------------------------

我想按 sheep_age 分组,但从聚合中排除空字符串。所以结果应该是这样的:

--------------------------------------
| sheep_id | sheep_age | sheep_color |
--------------------------------------
|    1     |     1     |    gray     |
|   2,3    |     2     |    grey     |
|   4,5    |     3     |    white    |
--------------------------------------

而不是这个:

--------------------------------------
| sheep_id | sheep_age | sheep_color |
--------------------------------------
|    1     |     1     |    gray     |
|   2,3    |     2     |   grey,     |
|   4,5    |     3     |   white,    |
--------------------------------------

我尝试关注this solution来解决我的问题。

这是我的代码:

def get: DataFrame = {
  sheepDF
    .select(
      $"sheep_id".as("sheep_id"),
      $"sheep_age".as("sheep_age"),
      $"sheep_color".as("sheep_color")
    )
    .groupBy(
      $"sheep_age"
    )
    .agg(
      concat_ws(",",
        collect_list(
          $"sheep_id"
        ))
        .as("sheep_ids"),
      concat_ws(",",
        collect_list(
          when($"sheep_color" != "", $"sheep_color")
        ))
        .as("sheep_colors")
    )
}

但是,我收到了这个错误:

type mismatch;
[error]  found   : Boolean
[error]  required: org.apache.spark.sql.Column
[error]             when($"sheep_color" != "",
[error]                                      ^

为什么它告诉我required: org.apache.spark.sql.Column?我缺少什么? When 函数应该需要 Boolean 对吗?

最佳答案

这里你想要的是一列 bool 值,而 != 返回一个 bool 值而不是一列。 Spark 为列定义了两个相等运算符:等于 === 和不等于 =!=。这两者都返回一列 bool 值,它们是被比较的两列的元素的比较结果。

简而言之,将 $"sheep_color"!= "" 更改为 $"sheep_color"=!= "" 即可解决该错误。


关于为什么使用 === 而不是 == 的更多见解可以在这里找到:Difference between == and === in Scala, Spark

关于scala - 为什么在使用 Spark sql 过滤特定聚合的行时出现类型不匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57689558/

相关文章:

scala - 生成器/ block 到迭代器/流的转换

scala - 榕树配置加载通用

scala - 在 Scala 的构造函数中扩展具有隐式参数的类的惯用方法是什么?

java - Spark : Saving filtered rows in FilterFunction

scala - 包命名结构

r - 如何将变量从 data.frame 循环到另一个 data.frame 中并放入单个列中

r - 将 dfmSparse 从 Quanteda 包转换为 R 中的数据框或数据表

python - Pyspark-当从已经具有(错误)模式的Parquet文件读取时,如何强制spark再次推断模式?

python - PySpark:基于 array_contains 加入数据框列

java - (Apache Beam) 无法增加执行程序内存 - 尽管使用了多个设置,它仍固定为 1024M