首页 > 解决方案 > 使用正则表达式连接火花中的两个数据帧

问题描述

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

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

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

标签: regexscalaapache-spark

解决方案


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

// 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)

返回:

+------+---------------------------------------------+---+--------------------------------------------------------+------+
|_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|
+------+---------------------------------------------+---+--------------------------------------------------------+------+

推荐阅读