Spark:检查嵌套数组中是否存在值而不爆炸

丽雅B

我有一个如下所示的数据集:

val df = Seq(("beatles", Seq(Seq("help", "hey jude"))), 
            ("romeo", Seq(Seq("help2", "hey judge"),Seq("help3", "they judge")))).toDF("col1", "col2")

root
 |-- col1: string (nullable = true)
 |-- col2: array (nullable = true)
 |    |-- element: array (containsNull = true)
 |    |    |-- element: string (containsNull = true)

我想在数据hasHitSong框中添加一列,它将迭代 col2 下的热门歌曲序列,检查是否存在热门歌曲,例如。“嘿裘德”并将其标记为 1,否则标记为 0。

| col1    | col2                                            | hasHitSongs |
|---------|-------------------------------------------------|-------------|
| beatles | ["help", "hey jude"]                            | 1           |
| romeo   | [["help2", "hey judge"],["help3", "hey judge"]] | 0           |

有没有办法在不爆炸列 col2 并且只迭代 col2 下的嵌套数组的情况下执行此操作?

贝尔瓦尔

如果您使用的是 spark 2.4 或更高版本:

使用内置函数

df.withColumn("hasHitSongs", array_contains(flatten(col("col2")), "hey jude"))

使用高阶函数

df.withColumn("hasHitSongs, expr("exists(col2, a -> exists(a, b -> b = 'hey jude'))"))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章