在 Spark 的 where 子句中将多个条件作为字符串传递

Pass multiple conditions as a string in where clause in Spark

我正在使用 DataFrame API.

在 Spark 中编写以下代码
val cond = "col("firstValue") >= 0.5 & col("secondValue") >= 0.5 & col("thirdValue") >= 0.5"
val Output1 = InputDF.where(cond)

我将所有条件作为来自外部参数的字符串传递,但它抛出一个解析错误,因为 cond 应该是 Column.

类型

例如:

col("firstValue") >= 0.5 & col("secondValue") >= 0.5 & col("thirdValue") >= 0.5

因为我想动态传递多个条件,我怎样才能将 String 转换为 Column

编辑

有什么东西可以让我从外部读取条件列表作为 Column,因为我没有找到任何东西可以使用 Scala 代码将 String 转换为 Column

我相信您可能想要执行以下操作:

InputDF.where("firstValue >= 0.5 and secondValue >= 0.5 and thirdValue >= 0.5")

您遇到的错误是 运行 时的解析错误,如果错误是由传入的错误类型引起的,它甚至不会编译。

正如您在 official documentation 中看到的(这里为 Spark 2.3.0 提供),where 方法可以采用一系列 Column s(就像在后面的代码片段中) 或表示 SQL 谓词的字符串(如我的示例所示)。

SQL 谓词将由 Spark 解释。但是,我相信值得一提的是,您可能对组合 Column 而不是连接字符串感兴趣,因为前一种方法通过消除整个 类 可能的错误(例如解析错误)。

您可以使用以下代码实现相同的目的:

InputDF.where(col("firstValue") >= 0.5 and col("secondValue") >= 0.5 and col("thirdValue") >= 0.5)

或更简洁:

import spark.implicits._ // necessary for the $"" notation
InputDF.where($"firstValue" >= 0.5 and $"secondValue" >= 0.5 and $"thirdValue" >= 0.5)

Columns 很容易组合,而且比原始字符串更健壮。如果你想应用一组条件,你可以很容易地 and 它们在一个函数中,甚至在你 运行 程序之前就可以验证:

def allSatisfied(condition: Column, conditions: Column*): Column =
    conditions.foldLeft(condition)(_ and _)

InputDF.where(allSatisfied($"firstValue" >= 0.5, $"secondValue" >= 0.5, $"thirdValue" >= 0.5))

你当然可以用字符串实现同样的效果,但这最终会变得不那么健壮:

def allSatisfied(condition: String, conditions: String*): String =
    conditions.foldLeft(condition)(_ + " and " + _)

InputDF.where(allSatisfied("firstValue >= 0.5", "secondValue >= 0.5", "thirdValue >= 0.5"))

我试图实现类似的事情,对于 Scala,下面的代码对我有用。

导入 org.apache.spark.sql.functions.{col, _}

val cond = (col("firstValue") >= 0.5 & 
            col("secondValue") >= 0.5 & 
            col("thirdValue") >= 0.5)

val Output1 = InputDF.where(cond)