我读过几篇关于使用“like”运算符通过包含字符串/表达式的条件来过滤 Spark 数据帧的文章,但想知道以下是否是在 %s 中使用 %s 的“最佳实践”期望的条件如下:
input_path = <s3_location_str>
my_expr = "Arizona.*hot" # a regex expression
dx = sqlContext.read.parquet(input_path) # "keyword" is a field in dx
# is the following correct?
substr = "'%%%s%%'" %my_keyword # escape % via %% to get "%"
dk = dx.filter("keyword like %s" %substr)
# dk should contain rows with keyword values such as "Arizona is hot."
注意
我正在尝试获取 dx 中包含表达式 my_keyword 的所有行。否则,为了精确匹配,我们不需要周围的百分号“%”。
最佳答案
根据 neeraj 的提示,在 pyspark 中执行此操作的正确方法似乎是:
expr = "Arizona.*hot"
dk = dx.filter(dx["keyword"].rlike(expr))
请注意,dx.filter($"keyword"...)
不起作用,因为(我的版本)pyspark 似乎不支持 $
命名法开箱即用。
关于regex - Pyspark:通过字符串格式的正则表达式过滤数据帧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45580057/