表之间的 PySpark 正则表达式匹配

PySpark regex match between tables

我正在尝试使用 PySpark 从列中提取正则表达式模式。我有一个包含正则表达式模式的数据框,然后是一个包含我想要匹配的字符串的 table。

columns = ['id', 'text']
vals = [
 (1, 'here is a Match1'),
 (2, 'Do not match'),
 (3, 'Match2 is another example'),
 (4, 'Do not match'),
 (5, 'here is a Match1')
]

df_to_extract = sql.createDataFrame(vals, columns)


columns = ['id', 'Regex', 'Replacement']
vals = [
(1, 'Match1', 'Found1'),
(2, 'Match2', 'Found2'),
]

df_regex = sql.createDataFrame(vals, columns)

我想匹配 'df_to_extract' 的 'text' 列中的 'Regex' 列。我想针对每个 id 提取术语,结果 table 包含 id 和 'replacement' 对应于 'Regex'。例如:

+---+------------+
| id| replacement|
+---+------------+
|  1|      Found1|
|  3|      Found2|
|  5|      Found1|
+---+------------+

谢谢!

一种方法是在连接条件中使用 pyspark.sql.functions.expr, which allows you to

例如:

from pyspark.sql.functions import expr
df_to_extract.alias("e")\
    .join(
        df_regex.alias("r"), 
        on=expr(r"e.text LIKE concat('%', r.Regex, '%')"),
        how="inner"
    )\
    .select("e.id", "r.Replacement")\
    .show()
#+---+-----------+
#| id|Replacement|
#+---+-----------+
#|  1|     Found1|
#|  3|     Found2|
#|  5|     Found1|
#+---+-----------+

这里我使用了sql表达式:

e.text LIKE concat('%', r.Regex, '%')

这将连接所有行,其中 text 列类似于 Regex 列,% 充当通配符以捕获前后的任何内容。