我正在使用数据框
root
|-- c: long (nullable = true)
|-- data: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- key: string (nullable = true)
| | |-- value: string (nullable = true)
我试图基于数组数据中的元素[“ value1”,“ key1”]来过滤此数据帧,即如果该元素存在于df的数据中,请保留它,否则将其删除,我尝试过
df.filter(col("data").contain("["value1", "key1"])
但是没有用。我也试图
将val f=Array("value1", "key1")
放在df.filter(col("data").contain(f))
上也没用。
请帮忙吗?
答案 0 :(得分:4)
直接方法是使用udf
函数,因为udf
函数有助于逐行和以原始数据类型执行逻辑(这是您的要求建议检查的内容) 数组数据列中的struct
元素的每个键和值)
import org.apache.spark.sql.functions._
//udf to check for key1 in key and value1 in value of every struct in the array field
def containsUdf = udf((data: Seq[Row])=> data.exists(row => row.getAs[String]("key") == "key1" && row.getAs[String]("value") == "value1"))
//calling the udf function in the filter
val filteredDF = df.filter(containsUdf(col("data")))
因此filteredDF
应该是您想要的输出