使用正则表达式在 spark 中连接两个数据帧

mar*_*inr 5 regex scala apache-spark

假设我有一个数据框 df1,其中列“color”包含一堆颜色,另一个数据框 df2 包含包含各种短语的列“phrase”。

我想加入两个数据帧,其中 d1 中的颜色出现在 d2 中的短语中。我不能使用d1.join(d2, d2("phrases").contains(d1("color")),因为它会加入该词出现在短语中的任何地方。例如,我不想匹配像 scaRED 这样的词,其中 RED 是另一个词的一部分。我只想在颜色在短语中作为一个单独的词出现时加入。

我可以使用正则表达式来解决这个问题吗?当我需要引用表达式中的列时,我可以使用什么函数以及语法如何?

the*_*tom 2

没有看到你的数据,但这是一个入门,有一点变化。据我所知,不需要正则表达式,但谁知道:

// You need to do some parsing like stripping of . ? and may be lowercase or uppercase
// You did not provide an example on the JOIN

import org.apache.spark.sql.functions._
import scala.collection.mutable.WrappedArray

val checkValue = udf { (array: WrappedArray[String], value: String) => array.iterator.map(_.toLowerCase).contains(value.toLowerCase() ) }

//Gen some data
val dfCompare = spark.sparkContext.parallelize(Seq("red", "blue", "gold", "cherry")).toDF("color")
val rdd = sc.parallelize( Array( (("red","hello how are you red",10)), (("blue", "I am fine but blue",20)), (("cherry", "you need to do some parsing and I like cherry",30)), (("thebluephantom", "you need to do some parsing and I like fanta",30)) ))
//rdd.collect
val df = rdd.toDF()
val df2 = df.withColumn("_4", split($"_2", " ")) 
df2.show(false)
dfCompare.show(false)
val res = df2.join(dfCompare, checkValue(df2("_4"), dfCompare("color")), "inner")
res.show(false)
Run Code Online (Sandbox Code Playgroud)

返回:

+------+---------------------------------------------+---+--------------------------------------------------------+------+
|_1    |_2                                           |_3 |_4                                                      |color |
+------+---------------------------------------------+---+--------------------------------------------------------+------+
|red   |hello how are you red                        |10 |[hello, how, are, you, red]                             |red   |
|blue  |I am fine but blue                           |20 |[I, am, fine, but, blue]                                |blue  |
|cherry|you need to do some parsing and I like cherry|30 |[you, need, to, do, some, parsing, and, I, like, cherry]|cherry|
+------+---------------------------------------------+---+--------------------------------------------------------+------+
Run Code Online (Sandbox Code Playgroud)