Updated on 2026-11-06 GMT+08:00

Using UDAFs for Aggregation Statistics

User-defined aggregate functions (UDAFs) receive multiple rows of data and return a set of aggregated values. They are applicable to custom statistical scenarios where built-in aggregate functions cannot meet requirements.

Scenario

In a sales data analysis scenario, it is necessary to count the top K highest amounts for each product category. The built-in MAX function can only return the single maximum value and cannot return a Top-K list. By defining a custom UDAF PythonTopK, you can collect the amount values from each row in the accumulate method and sort them in descending order, merge the intermediate states from different partitions in the merge method, and output the Top-K list in JSON format in the finish method. This achieves flexible custom aggregation statistics.

Notes and Constraints

  • UDAFs must implement the aggregate_state, accumulate, merge, and finish methods.
  • The implemented accumulate, aggregate_state, and merge methods must be side-effect-free. This means their outputs should depend solely on input parameters and the current aggregation state, not on the factors such as invocation count, order, or external conditions.
  • UDAFs cannot be used as window functions, that is, they cannot be used in OVER clauses.
  • UDAFs do not support concurrent execution or vectorized computation.
  • It is recommended to call delete_function to clean up functions with the same name before registering a UDAF to avoid errors during repeated execution.

Prerequisites

Example

This example defines a UDAF that counts the top K highest amounts in each group. After registering it in the database, it performs grouping and aggregation on the category_sales table by product category, retrieving the top 3 amounts for each group.

  1. Define the UDAF class PythonTopK, implementing the aggregate_state, accumulate, merge, and finish methods to count the top K records with the highest amount values in each group.
  2. Connect to the AuraJobV2 endpoint and set the UDF workspace.
  3. Delete the existing UDF with the same name (repeated execution is supported).
  4. Register the UDAF to the target database.
  5. Load the category_sales dataset.
  6. Construct the aggregation expression using AggregateFnBuilder, grouping by category and taking the top 3 amount values.
  7. Execute the aggregation query and print the results.
  8. Disable the AuraJobV2 endpoint connection.
import os
import json
from aura_frame.multimodal import ai_lake
from aura_frame.multimodal.function import AggregateFnBuilder

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)
)

# Define a UDAF to count the top K highest amounts in each group.
class PythonTopK:
    def __init__(self, k: int):
        self.k = k
        self._agg_state = []
    @property
    def aggregate_state(self):
        return self._agg_state
    def accumulate(self, value: float) -> None:
        if value is not None:
            self._agg_state.append(value)
            self._agg_state.sort(reverse=True)
            self._agg_state = self._agg_state[: self.k]
    def merge(self, other_state) -> None:
        merged = self._agg_state + other_state
        merged.sort(reverse=True)
        self._agg_state = merged[: self.k]
    def finish(self) -> str:
        return json.dumps(self._agg_state)
try:
    # Delete the existing UDF with the same name (repeated execution is supported).
    con.delete_function("PythonTopK", database=target_database, if_it_exists=True)
    # Register a UDAF.
    udaf = con.create_agg_function(PythonTopK, database=target_database)
    # Use the UDAF in DataFrame: Group by category and take the top 3 highest amounts for each group.
    ds = con.load_dataset("category_sales", database=target_database)
    udaf_builder = AggregateFnBuilder(fn=udaf, on=[ds.amount], as_col="top3", constructor_kwargs={"k": 3})
    summary = ds.aggregate([udaf_builder], by=[ds.category])
    df = summary.execute()
    print(df)
finally:
    con.close()