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

Writing the UDAF Code and Exporting the JAR File

Step 1: Writing the UDAF Code

Pay attention to the following requirements when you implement the UDAF:

  • The UDAF must inherit the UDAFHandler class, write the UDAF function in the class, and implement the following methods:
    public abstract Writable newBuffer();
    public abstract void iterate(Writable buffer, Object[] args) throws FuncException;
    public abstract void merge(Writable buffer, Writable partial) throws FuncException;
    public abstract Object terminate(Writable buffer) throws FuncException;
  • The @TypeResolve annotation is added to the method to indicate the input and output parameters of the function.
    Input and output parameters are separated by an arrow (->). For details about the input and output parameter types (resolveType) and the corresponding SQL and Java data types, see Table 1.
    Table 1 resolveType

    SQL type

    Java type

    resolveType

    BooleanType

    Boolean.class

    BOOLEAN

    ByteType

    Byte.class

    BYTE

    ShortType

    Short.class

    SHORT

    IntegerType

    Integer.class

    INT

    LongType

    Long.class

    LONG

    FloatType

    Float.class

    FLOAT

    DoubleType

    Double.class

    DOUBLE

    StringType

    String.class

    STRING

    BinaryType

    byte[].class

    BINARY

    DecimalType.Fixed(precision, scale)

    BigDecimal.class

    DECIMAL

    DateType

    LocalDate.class

    DATE

    TimestampType

    ZonedDateTime.class

    TIMESTAMP

    TimestampNTZType

    LocalDateTime.class

    TIMESTAMP_NTZ

    YearMonthIntervalType

    Period.class

    INTERVAL_YEAR_MONTH

    DayTimeIntervalType

    Duration.class

    INTERVAL_DAY_TIME

    List

    List.class

    LIST

    Map

    Map.class

    MAP

    Struct

    Map.class

    STRUCT

  • Add the @deterministic annotation.

    The @deterministic annotation indicates that the function is deterministic, that is, it always returns the same result for the same input.

    For details about how to implement the UDAF, see the following sample code:

    • Function description:

      This function is used to calculate the average value of data. The design process is as follows: Initialization > Iterative calculation > Result combination > Final calculation.

    • Example code
      package com.huawei.demo;
      
      import com.huawei.spark.function.FuncException;
      import com.huawei.spark.function.handlers.UDAFHandler;
      import com.huawei.spark.function.requests.Writable;
      import com.huawei.spark.function.types.TypeResolve;
      
      import java.io.IOException;
      import java.io.ObjectInput;
      import java.io.ObjectOutput;
      
      // get average
      @TypeResolve("int->double")
      public class UDAFDemo extends UDAFHandler {
          private static class Buffer implements Writable {
              private double sum = 0.d;
      
              private int count = 0;
      
              public Buffer() {
              }
      
              @Override
              public void writeExternal(ObjectOutput out) throws IOException {
                  out.writeDouble(sum);
                  out.writeInt(count);
              }
      
              @Override
              public void readExternal(ObjectInput in) throws IOException {
                  sum = in.readDouble();
                  count = in.readInt();
              }
          }
      
          public Writable newBuffer() {
              return new com.huawei.demo.UDAFDemo.Buffer();
          }
      
          public void iterate(Writable buffer, Object[] args) throws FuncException {
              com.huawei.demo.UDAFDemo.Buffer buf = (com.huawei.demo.UDAFDemo.Buffer) buffer;
              Integer arg = (Integer) args[0];
              buf.sum += arg;
              buf.count++;
          }
      
          public void merge(Writable buffer, Writable partial) throws FuncException {
              com.huawei.demo.UDAFDemo.Buffer buf = (com.huawei.demo.UDAFDemo.Buffer) buffer;
              com.huawei.demo.UDAFDemo.Buffer par = (com.huawei.demo.UDAFDemo.Buffer) partial;
              buf.sum += par.sum;
              buf.count += par.count;
          }
      
          public Object terminate(Writable buffer) throws FuncException {
              com.huawei.demo.UDAFDemo.Buffer buf = (com.huawei.demo.UDAFDemo.Buffer) buffer;
              if (buf.count == 0) {
                  return 0;
              }
              return buf.sum / buf.count;
          }
      }
  • Detailed description:
    • newBuffer() initializes the buffer.

      The Buffer class implements the Writable interface and is used to store intermediate results temporarily during aggregation. It supports serialization and deserialization.

      It contains two core variables:

      • sum: The cumulative total.
      • count: The cumulative count, which records the number of elements involved in the computation.

      It implements two serialization methods:

      • writeExternal: Writes the sum and count to the output stream.
      • readExternal: Reads sum and count from the input stream.
  • iterate(): Iterates the input data.

    Purpose: Iterates over the input data and updates the intermediate state in the buffer.

    Parameters:

    • buffer: The current buffer.
    • args: An input parameter array, where args[0] is the integer to be calculated.

    Logic: Adds the input integer to sum and increments count by 1.

  • merge(): Merges intermediate results from distributed computations.

    Purpose: Merges intermediate results from multiple subtasks in distributed computing scenarios.

    Parameters:

    • buffer: The main buffer, which is used to store the final merged result.
    • partial: The buffer of other subtasks, which is used to store the partial results to be merged.

    Logic: Adds the sum and count of each subtask to the main buffer.

  • terminate(): Calculates the final result.

    Purpose: Calculates the final average value after all data is processed.

    Logic: Calculates the average by dividing the total sum by the total count. If there is no data (count=0), 0 is returned to avoid division by zero.

Step 2: Exporting the JAR Package

Use IntelliJ IDEA to compile the code and pack it into the JAR package.

  1. Click Build. On the displayed page, click Build Project and Build Artifacts... to compile and pack the code, respectively.
    Figure 1 Compiling and packing
  1. In the displayed dialog box, click Build.
    Figure 2 Compiling and packing
  1. After the preceding steps are complete, locate the out folder in the project directory and expand it.

    The MyRemoteUDAF.jar file is the JAR file to be uploaded to FunctionGraph.

    Figure 3 Viewing MyRemoteUDAF.jar
  2. Right-click MyRemoteUDAF.jar and choose Copy Path/Reference from the shortcut menu to copy its path.

    In this example, the MyRemoteUDAF.jar file is generated in the D:\UDAFTest\MyRemoteUDAF\out\artifacts\MyRemoteUDAF_jar\ directory.

    Figure 4 Copying the file path