Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
创建一个Spark exists用户定义函数,该函数与Scala Array#exists函数类似_Scala_Apache Spark_Apache Spark Sql_User Defined Functions - Fatal编程技术网

创建一个Spark exists用户定义函数,该函数与Scala Array#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: +---------+ |努姆斯| +---------+

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

+---------+
|努姆斯|
+---------+
|[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"))