如果一列是另一列的成员,如何过滤Spark数据帧

Rai*_*eld 4 scala dataframe apache-spark apache-spark-sql

我有一个包含两列的数据帧(一个字符串和一个字符串数组):

root
 |-- user: string (nullable = true)
 |-- users: array (nullable = true)
 |    |-- element: string (containsNull = true)
Run Code Online (Sandbox Code Playgroud)

如何才能筛选数据框,这样的结果数据框只包含行认为userusers

zer*_*323 11

快速简单:

import org.apache.spark.sql.functions.expr

df.where(expr("array_contains(users, user)")
Run Code Online (Sandbox Code Playgroud)


Alb*_*nto 5

当然,这是可能的,而不是那么难.为此,您可以使用UDF.

import org.apache.spark.sql.functions._
import org.apache.spark.sql.types._

val df = sc.parallelize(Array(
  ("1", Array("1", "2", "3")),
  ("2", Array("1", "2", "2", "3")),
  ("3", Array("1", "2"))
)).toDF("user", "users")

val inArray = udf((id: String, array: scala.collection.mutable.WrappedArray[String]) => array.contains(id), BooleanType)

df.where(inArray($"user", $"users")).show()
Run Code Online (Sandbox Code Playgroud)

输出是:

+----+------------+
|user|       users|
+----+------------+
|   1|   [1, 2, 3]|
|   2|[1, 2, 2, 3]|
+----+------------+
Run Code Online (Sandbox Code Playgroud)