所以我有这个数据框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/