创建一个Spark exists用户定义函数,该函数与Scala Array#exists函数类似
Scala有一个数组#exists函数,其工作原理如下:创建一个Spark exists用户定义函数,该函数与Scala Array#exists函数类似,scala,apache-spark,apache-spark-sql,user-defined-functions,Scala,Apache Spark,Apache Spark Sql,User Defined Functions,Scala有一个数组#exists函数,其工作原理如下: Array(1, 2, 5).exists(_ % 2 == 0) // true val actualDF = sourceDF.withColumn( "nums_has_even", exists(col("nums"), (x: Int) => x % 2 == 0) ) 我想创建一个类似的Spark exists函数。假设我们有以下sourceDF: +---------+ |努姆斯| +---------+
Array(1, 2, 5).exists(_ % 2 == 0) // true
val actualDF = sourceDF.withColumn(
"nums_has_even",
exists(col("nums"), (x: Int) => x % 2 == 0)
)
我想创建一个类似的Spark exists函数。假设我们有以下sourceDF
:
+---------+
|努姆斯|
+---------+
|[1, 4, 9]|
|[1, 3, 5]|
+---------+
我希望能够写出这样的东西:
Array(1, 2, 5).exists(_ % 2 == 0) // true
val actualDF = sourceDF.withColumn(
"nums_has_even",
exists(col("nums"), (x: Int) => x % 2 == 0)
)
以下是我编写的代码:
def existsInt(arr: Array[Int], f: (Int => Boolean)): Boolean = {
arr.exists(f(_))
}
val exists = udf[Boolean, Array[Int], (Int => Boolean)](existsInt)
我理解为什么我的代码不起作用。UDF需要列参数,匿名函数不是列对象。在lit
中包装匿名函数无效:
exists(col("nums"), lit((x: Int) => x % 2 == 0)) // doesn't work
我如何才能让这段代码正常工作?您非常接近:
def existsInt(f: (Int => Boolean)) = udf {
(arr: Seq[Int]) => arr.exists(f(_)) // Not Array!
}
用法:
existsInt((x: Int) => x % 2 == 0)(col("nums"))
你甚至可以:
scala.reflect.runtime.universe._
def exists[T : TypeTag](f: (T => Boolean)) = udf[Boolean, Seq[T]]{
(arr: Seq[T]) => arr.exists(f(_)) // Not Array!
}
exists[Int]((x: Int) => x % 2 == 0).apply(col("nums"))