【问题标题】:How to implement Python UDF in dbt如何在dbt中实现Python UDF
【发布时间】:2023-01-20 17:18:49
【问题描述】:

我需要一些帮助来应用 python UDF 在我的 dbt 模型上运行。 我成功地在 snowflake (DWH) 中创建了一个 python 函数并针对一个表运行它。这似乎按预期工作,但在 dbt 上实现它似乎很困难。一些建议/帮助/指导会让我开心。

这是我在雪花上创建的 python UDF

create or replace function "077"."Unity".sha3_512(str varchar)
returns varchar
language python
runtime_version = '3.8'
handler = 'hash'
as

$$
import hashlib
 
def hash(str):
    # create a sha3 hash object
    hash_sha3_512 = hashlib.new("sha3_512", str.encode())

    return hash_sha3_512.hexdigest()
$$
;

目标是在 dbt 中创建 python 函数并将其应用于下面的模型

{{ config(materialized = 'view') }}

WITH SEC AS(
    SELECT 
         A."AccountID" AS AccountID,
         A."AccountName" AS AccountName , 
         A."Password" AS Passwords,
 apply function here (A."Password") As SHash
    FROM {{ ref('Green', 'Account') }} A
   )

----------------VIEW RECORD------------------------------ 

SELECT * 
FROM SEC

有没有办法做到这一点。谢谢

【问题讨论】:

    标签: python snowflake-cloud-data-platform dbt


    【解决方案1】:

    假设 UDF 已经存在于 Snowflake 中:

    {{ config(materialized = 'view') }}
    
    WITH SEC AS(
        SELECT 
             A."AccountID" AS AccountID,
             A."AccountName" AS AccountName , 
             A."Password" AS Passwords,
             {{target.schema}}.sha3_512(A."Password") As SHash
        FROM {{ ref('Green', 'Account') }} A
       )
    SELECT * 
    FROM SEC;
    

    该函数可以使用on-run-start创建:

    on-run-start:
      - '{{ creating_udf()}}'
    

    和宏:

    {% macro creating_udf() %}
    
    create function if not exists {{target.schema}}.sha3_512(str varchar)
    returns varchar
    language python
    runtime_version = '3.8'
    handler = 'hash'
    as
    
    $$
    import hashlib
     
    def hash(str):
        # create a sha3 hash object
        hash_sha3_512 = hashlib.new("sha3_512", str.encode())
    
        return hash_sha3_512.hexdigest()
    $$
    ;
    
    {% endmacro %}
    

    【讨论】:

    • 请问如何在我的模型中引用宏
    • 您不需要在模型中引用宏。在通过 dbt_project.yml 中的 on-run-start 自动执行 dbt run 之前,宏会创建 Python UDF (sha3_512)。之后,您只需在 SQL 模型中使用 Python UDF。
    【解决方案2】:

    上面的答案有效,但如果您只想为特定模型运行宏,最好在模型配置中使用 pre_hook(而不是运行时启动)运行宏。

    【讨论】:

      猜你喜欢
      • 2021-07-27
      • 1970-01-01
      • 2022-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-15
      • 2021-04-03
      • 2019-07-11
      相关资源
      最近更新 更多