sql - PySpark 中是否有相当于 SnowFlake 的“REGEXP_SUBSTR”?
问题描述
是否有相当于雪花的REGEXP_SUBSTR
in PySpark
/ spark-sql
?
REGEXP_EXTRACT
存在,但它不支持REGEXP_SUBSTR
.
这是REGEXP_SUBSTR的链接。
这是REGEXP_EXTRACT的链接。
更具体地说,我正在寻找 的替代品position
,occurrence
并且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)
解决方案
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
推荐阅读
- ruby - 错误编译器 gem 'private-gem-server'
- c# - Abp 样板 Abp.Feature.AllFeatures 到 C#
- ios - 在 .xib 的 UICollectionViewCell 中使用 IBOutlet 时出现 NSUnknownKeyException
- html - 单独设置 h2-Element 样式,即使它位于受 flex 影响的 div 内
- android - 如何从静态类广播接收器访问意图值?
- ios - SWIFT:来自 webapi 的数据不是统计图
- typo3 - 在打字稿中使用特殊字符作为 CASE 键
- ms-access - MS Access 报告:如何根据显示的文本在文本框中添加换行符
- c# - 如何将一个文件多次上传到文件夹中
- python - 在Python中搜索特定模式并删除一行中的模式