[英]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
,因为我还没有发现任何的转换String
为Column
使用Scala代码。
我相信您可能想要执行以下操作:
InputDF.where("firstValue >= 0.5 and secondValue >= 0.5 and thirdValue >= 0.5")
您面临的错误是运行时的解析错误,如果该错误是由传入的错误类型引起的,则甚至不会进行编译。
如您在官方文档 (Spark 2.3.0的此处提供)中所见, where
方法可以采用Column
序列(如您的后一片段),也可以采用表示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)
s Column
比原始字符串更容易组合且更可靠。 如果您想应用一组条件,则可以轻松地将它们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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.