更新时间:2026-07-03 GMT+08:00
分享

Scalar UDF

Scalar UDF是最基本的行处理函数, 它接受零个或多个输入参数,并对这一行数据进行操作,最终返回一行结果。

通常Scalar UDF适用于数学运算、复杂类型转换和自定义格式化等行处理的场景。

Scalar UDF的行为与内置函数非常相似,但其具体实现由用户自定义。

示例

  1. 建立连接。
    import os
    from aura_frame.multimodal import ai_lake
    
    target_database = "test"
    conn = ai_lake.connect(
        aura_endpoint=os.getenv("AURA_ENDPOINT"),
    
        aura_endpoint_name=os.getenv("AURA_ENDPOINT_NAME"),
        aura_workspace_id=os.getenv("AURA_WORKSPACE"),
        lf_catalog_name=os.getenv("AURA_CATALOG"),
        access_key=os.getenv("access_key"),
        secret_key=os.getenv("secret_key"),
        default_database=target_database,
        use_single_cn_mode=True
    )
  2. 定义并注册UDF。
    def add_udf(lhs: int, rhs: int) -> int:
        return lhs + rhs
    
    def calculate_product(price: float, quantity: int) -> float:    
        return price * quantity
    
    conncreate_scalar_function(
        add_udf,
        database=db,
        comment="To test create_scalar_function"
    )
  3. 获取UDF。
    udf = conn.get_function("add_udf", database=target_database)
  4. 使用UDF并执行。
    # 使用UDF
    ds = connload_dataset(name="your-table", schema="your-schema")
    ds = ds.map(fn=udf, on=[ds.price, ds.quantity], as_col="sum_column")
    ds.select_columns([ds.price, ds.quantity, ds.sum_column])
    ds.show(limit=1)

相关文档