【问题标题】:BigQuery function to remove words in string by lookup tableBigQuery 函数通过查找表删除字符串中的单词
【发布时间】:2023-01-11 17:51:36
【问题描述】:

给定一个字符串,我想创建一个函数来删除字符串中存在于查找表中的任何单词/词组。

例如,给定一个字符串s1 s2 s3 s4 s5 s6 和一个查找表

word
s2
s4 s5

预期结果:

select fn.remove_substring('s1 s2 s3 s4 s5 s6')

-- Expected output: 's1  s3  s6'

在 PostgreSQL 中,我实际上实现了一个工作函数,但是,我不确定如何在 BigQuery 中重写它,因为 BigQuery UDF 不允许游标和循环。

CREATE OR REPLACE FUNCTION fn.remove_substring(s text)
 RETURNS text
 LANGUAGE plpgsql
AS $function$
declare
    replaced_string text := s;
    t_cur cursor for
        select word from public.lookup order by word desc;
begin
    for row in t_cur loop
        replaced_string := regexp_replace(replaced_string, '\y'||row.word||'\y', '', 'gi');
    end loop;
    return replaced_string;
end;
$function$
;

【问题讨论】:

    标签: sql google-bigquery


    【解决方案1】:

    您可以考虑以下。

    WITH sample_table AS (
      SELECT 's1 s2 S3 S4 s5 s6' str
    ),
    lookup_table AS (
      SELECT 's2' word UNION ALL
      SELECT 's4 s5'
    )
    SELECT str, 
           REGEXP_REPLACE(
             str, (SELECT '(?i)(' || STRING_AGG(word, '|' ORDER BY LENGTH(word) DESC) || ')' FROM lookup_table), ''
           ) AS removed_str
      FROM sample_table;
    

    查询结果

    如果在 UDF 中实现,

    CREATE TEMP TABLE lookup_table AS 
      SELECT 's2' word UNION ALL
      SELECT 's4 s5'
    ;
    
    CREATE TEMP FUNCTION remove_substring(str STRING) AS (
      REGEXP_REPLACE(
        str, (SELECT '(?i)(' || STRING_AGG(word, '|' ORDER BY LENGTH(word) DESC) || ')' FROM lookup_table), ''
      )
    );
    
    SELECT remove_substring('s1 s2 s3 s4 s5 s6');
    

    【讨论】:

      【解决方案2】:

      使用与@jaytiger 相同的方法。但是,您也可以通过只执行一次 select string_agg 来创建正则表达式,这样如果您的查找表太大,您就不必为每一行执行相同的查询。
      例子:

      declare regex String default '';
       
      create temp table main AS (
       select 's1 s2 s3 s4 s5 s6' str
      );
      create temp table lookup_table AS (
       select 's2' word union all
       select 's4' union all
       select 's5'
      );
       
      set regex = ( select string_agg(word, '|' order by length(word) desc) from lookup_table ) ;
       
      select regexp_replace(str, regex, '')new_str from main;
      

      输出:

      N.B 以上查询区分大小写。您应该根据您的要求修改它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-15
        • 1970-01-01
        • 1970-01-01
        • 2014-12-16
        • 2022-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多