Using Scalar UDFs to Process Data
This section describes how to register the custom calculation logic as a scalar UDF in the database and call it in Aura DataFrame to implement row-level data processing.
Scenario
In a sales data analysis scenario, it is necessary to calculate the final price including tax based on the original price, discount rate, and tax rate. The calculation logic involves the combined operations on multiple fields. Expressing this logic using built-in SQL functions is not intuitive and difficult to reuse. By encapsulating the calculation logic into a scalar UDF and registering it in the database, you can use it in the DataFrame like a built-in function. This makes the code clearer and the logic easier to maintain.
Notes and Constraints
- Only user-defined functions written in Python are supported.
- Users are responsible for managing Python environment dependencies. Compatibility among library versions must be ensured.
- The runtime environment requires Python 3.11.
- Input parameters and return values of scalar UDFs must have explicitly specified data types.
- It is recommended to call delete_function to clean up functions with the same name before registering a UDF to avoid errors during repeated execution.
Prerequisites
A table has been created and data has been written to it. For details, see Creating a Table and Writing Data to the Table.
Example
This example defines a scalar UDF to calculate the final tax-inclusive price. After registering it in the database, it is called in Aura DataFrame using the map method to perform row-level calculations on each row of the sales_line_items table.
- Define the scalar UDF calc_final_price, which calculates the final tax-inclusive price based on the unit price, discount rate, and tax rate.
- Connect to the AuraJobV2 endpoint and set the UDF workspace.
- Delete the existing UDF with the same name (repeated execution is supported).
- Register the scalar UDF to the target database.
- Load the sales_line_items dataset.
- Call the UDF using the map method to calculate the final_price column for each row of data.
- Select the related columns, execute the query, and print the results.
- Disable the AuraJobV2 endpoint connection.
import os
from aura_frame.multimodal import ai_lake
def calc_final_price(price: float, discount: float, tax: float) -> float:
return price * (1 - discount) * (1 + tax)
target_database = "test" #Create a database in LakeFormation, for example, test. For details, see Creating a DataArts Lake Formation Instance and Planning Metadata.
#Connect to the AuraJobV2 endpoint. For details about the parameters, see Establishing a Connection with the AuraJobV2 Endpoint.
con = ai_lake.connect(
aura_endpoint=os.getenv("aura_endpoint"), # Endpoint where the AuraJobV2 endpoint is located
aura_endpoint_id=os.getenv("aura_endpoint_id"), # AuraJobV2 endpoint ID
aura_endpoint_name=os.getenv("aura_endpoint_name"),# AuraJobV2 endpoint name
aura_workspace_id=os.getenv("aura_workspace_id"), # Workspace ID
lf_catalog_name=os.getenv("lf_catalog_name"), # LakeFormation Catalog name
access_key=os.getenv("access_key"), # Access Key ID (AK)
secret_key=os.getenv("secret_key"), # Secret Key (SK)
default_database=target_database, # LakeFormation database name
use_single_cn_mode=True, # Whether to enable the single-CN mode
logging_level=logging.INFO # Set the log level.
)
#Configure the UDF deployment workspace. For details about the parameters, see Configuring the UDF Deployment Workspace.
con.set_function_staging_workspace(
obs_directory_base=os.getenv("obs_directory_base"), # Path for storing UDFs in the parallel file system.
obs_bucket_name=os.getenv("obs_bucket_name"), # Name of the parallel file system.
obs_server=os.getenv("obs_server"), # OBS endpoint
access_key=os.getenv("access_key"), # Access Key ID (AK)
secret_key=os.getenv("secret_key"), # Secret Key (SK)
)
try:
# Delete the existing UDF with the same name (repeated execution is supported).
con.delete_function("calc_final_price", database=target_database, if_it_exists=True)
# Register the scalar UDF.
udf = con.create_scalar_function(
calc_final_price,
database=target_database,
)
# Use the UDF in DataFrame.
ds = con.load_dataset("sales_line_items", database=target_database)
ds = ds.map(fn=udf, on=[ds.unit_price, ds.discount_rate, ds.tax_rate], as_col="final_price")
ds = ds.select_columns(ds.unit_price, ds.discount_rate, ds.tax_rate, ds.final_price)
df = ds.execute()
print(df)
finally:
con.close() Helpful Links
What is your overall rating for this page?
Thank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot