Class UDF
A class UDF uses object-oriented programming to enable stateful processing logic. To implement it, you must define methods such as __init__ and __call__.
Class UDF Registration
When registering a class UDF, you pass a Python class where __init__, __call__, and __del__ have specific meanings (refer to the table below for details). Other class attributes and instance methods can be freely added by you without restrictions.
| Python Class Method | Mandatory (Yes/No) | Parameter | Description | Applicable Scenarios |
|---|---|---|---|---|
| __init__(self, *args, **kwargs) | No | Parameters are passed through the with_arguments method. Only scalar values are allowed. | Constructor of the UDF. | Initializes UDF attributes (such as saving parameters, opening files, and establishing connections). |
| __call__(self, *args, **kwargs) | Yes | Parameters are passed through the UDF operator. Both scalar values and column names are allowed. | Entry point for the service logic of the UDF. | Processes data and performs calculations in the UDF. |
| __del__(self) | No | Parameters cannot be passed. | Destructor of the UDF. | Clears UDF resources (for example, closing files and disconnecting networks). |
Note: The life cycle of __init__ is called once for each batch. That is, the Aura kernel initializes variables each time it processes a batch.
Example
This example defines a class UDF with initialization parameters. It receives name parameters in __init__ and generates a welcome message combined with the city name in __call__. After registering it to the database, it uses the map method to generate greeting messages for each row of data in the city_list table.
- Define the class UDF class Hello. It receives the firstname and lastname parameters in __init__ and generates a welcome message combined with the city name in __call__.
- Connect to the Aura service and set the UDF workspace.
- Create the city_list table (containing the city column) and insert five city records.
- Delete the existing UDF with the same name (repeated execution is supported).
- Register the class UDF to the target database.
- Load the city_list dataset, call the UDF via the map method on the city column to generate greetings, passing the firstname and lastname parameters.
- Select the city and new_column columns, execute the query, and print the results.
- Disable the Aura connection.
import os import ibis from aura_frame.multimodal import ai_lake 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="postgres", # 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) ) # Define a class UDF: Greeting generator with initialization parameters. class Hello: def __init__(self, firstname: str, lastname: str): self.firstname = firstname self.lastname = lastname def __call__(self, location: str) -> str: return f"Hello {self.firstname} {self.lastname}! Welcome to {location}" try: # Create a test table and write data into it. table_name = "city_list" table_schema = ibis.schema({"city": "string"}) con.sql(f'DROP TABLE IF EXISTS "{target_database}"."{table_name}";') con.create_table( table_name, schema=table_schema, database=target_database, table_format="orc", if_not_exists=True, ) con.sql(f''' INSERT INTO "{target_database}"."{table_name}" (city) VALUES ('Beijing'), ('Shanghai'), ('New York'), ('London'), ('Tokyo') ''') # Delete the existing UDF with the same name (repeated execution is supported). con.delete_function("hello", database=target_database, if_it_exists=True) # Register the class UDF. hello_udf = con.create_scalar_function( Hello, name="hello", database=target_database, ) # Use the UDF to process data in the city_list table. ds = con.load_dataset("city_list", database=target_database) ds = ds.map( fn=hello_udf, on=[ds.city], as_col="new_column", firstname="Ethan", lastname="Carter", ) ds = ds.select_columns(ds.city, ds.new_column) print(ds.execute()) finally: con.close()
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