You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala Spark中基于RLIKE实现两个DataFrame关联的方法问询

基于RLIKE关联DataFrame并保留匹配数据

核心思路

先将df2中的%通配符转换为RLIKE支持的正则表达式(%对应正则的.*),再通过过滤或关联的方式保留df1中匹配的行。


方法一:合并正则后过滤(性能更优)

把df2的所有匹配模式合并成一个正则表达式,直接在df1中过滤匹配行,适合df2模式较多的场景:

from pyspark.sql import SparkSession
from pyspark.sql.functions import col, regexp_replace, concat_ws

# 初始化Spark环境
spark = SparkSession.builder.appName("RLIKE_Match").getOrCreate()

# 构建示例DataFrame
df1 = spark.createDataFrame([("football is a game",), ("kids play games",)], ["content"])
df2 = spark.createDataFrame([("%football%",), ("%basketball%",)], ["pattern"])

# 将df2的通配符模式转为正则,再合并成|分隔的正则串
combined_regex = df2.select(regexp_replace(col("pattern"), "%", ".*").alias("regex")) \
                   .agg(concat_ws("|", col("regex")).alias("full_regex")) \
                   .collect()[0]["full_regex"]

# 过滤df1中匹配正则的行
result_df = df1.filter(col("content").rlike(combined_regex))

# 输出结果
result_df.show(truncate=False)

输出:

+---------------------+
|content              |
+---------------------+
|football is a game   |
+---------------------+

方法二:交叉连接+过滤(逻辑更直观)

通过交叉连接将df1和df2的所有行配对,再过滤匹配的行,适合df2模式较少的场景:

# 交叉连接后过滤匹配行,最后去重避免重复结果
result_df = df1.crossJoin(df2) \
            .filter(col("content").rlike(regexp_replace(col("pattern"), "%", ".*"))) \
            .select("content") \
            .distinct()

result_df.show(truncate=False)

注意事项

  • RLIKE默认区分大小写,如需忽略大小写,可在正则前添加(?i)标记,比如"(?i)" + combined_regex
  • 若df2模式数量庞大,交叉连接会产生大量中间数据,优先选择方法一

内容的提问来源于stack exchange,提问作者Rushabh Gujarathi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 12:15:56