首页 > 解决方案 > PySpark 中是否有相当于 SnowFlake 的“REGEXP_SUBSTR”?

问题描述

是否有相当于雪花的REGEXP_SUBSTRin PySpark/ spark-sql

REGEXP_EXTRACT存在,但它不支持REGEXP_SUBSTR.

这是REGEXP_SUBSTR的链接。

这是REGEXP_EXTRACT的链接。

更具体地说,我正在寻找 的替代品positionoccurrence并且regex parameters由 Snowflake 的REGEXP_SUBSTR.

position:函数开始搜索匹配的字符串开头的字符数。

occurrence:指定要匹配的模式的哪个出现。该函数跳过第一次出现 - 1 个匹配项。

regex_parameters:我正在专门寻找参数“e”,它执行以下操作: 提取子匹配

所以查询是这样的:

REGEXP_SUBSTR(string, pattern, 1, 2, 'e', 2).

样本输入It was the best of times, it was the worst in times.

预期输出worst

假设string1 =It was the best of times, it was the worst in times.

等效 SF 查询:

SELECT regexp_substr(string1, 'the(\\W+)(\\w+)', 1, 2, 'e', 2)

标签: sqlregexpysparksnowflake-cloud-data-platform

解决方案


Spark 的一大优点是您不必依赖供应商为您创建函数库。您可以在 python 中创建用户定义函数并在 Spark SQL 语句中使用它。EG凝视着

import pandas as pd
from pyspark.sql.functions import pandas_udf, PandasUDFType
from pyspark.sql.functions import broadcast,col, lit, concat, udf
from pyspark.sql.types import StructField, StructType, IntegerType, StringType

import re

def regexp_substr(subject:str, pattern:str, position:int,occurance:int) -> str:
    s = subject[position:]
    searchResult = re.search(pattern,s)
    if searchResult:
        return searchResult.group(occurance)
    return None

#bench testing the python function
string1 = 'It was the best of times, it was the worst in times.'
pattern = 'the(\W+)(\w+)'

# print(pattern)
rv = regexp_substr(string1, pattern, 1,2)
print(rv)

# register for use in python
regexp_substr_udf = udf(regexp_substr , StringType())

# register for use in Spark SQL
spark.udf.register("REGEXP_SUBSTR", regexp_substr, StringType())

#craeate a spark DataFrame
df = spark.range(100).withColumn("s",lit(string1))
df.createOrReplaceTempView("df")

然后您可以运行 Spark SQL 查询,例如

%%sql

select *, REGEXP_SUBSTR(s,'the(\\W+)(\\w+)',1,2) ex from df

推荐阅读