Skip to main content
VeloDB Cloud 26.x is based on Apache Doris 4.x. See Version Mapping.

Java UDF, UDAF, UDWF, UDTF

Overview​

Java user-defined functions let you run custom scalar, aggregate, window, and table logic in SQL when built-in functions do not meet your needs. In this guide, UDF refers to all four types unless a specific type is named.

Java UDFs are available for BYOC warehouses and are not available for SaaS warehouses. See Warehouse deployment models. Before using this guide, contact VeloDB Cloud support to confirm that Java UDFs are enabled and arrange JAR distribution and any runtime configuration for your warehouse. The release-sensitive behavior described in this guide applies to Core 26.1.3.

The definitions and typical examples of the four types of custom functions are as follows:

TypeFunction typeBehaviorSimilar built-in functions
UDFScalar functionReturns one value for each input rowABS, LENGTH
UDAFAggregate functionCombines multiple input rows into one resultMIN, MAX, COUNT
UDWFWindow functionReturns a value for each row within a windowROW_NUMBER, RANK, DENSE_RANK
UDTFTable functionReturns zero or more rows for each input row and is called with LATERAL VIEWEXPLODE, EXPLODE_SPLIT

For Hive migration, you can reuse compatible Java implementation logic. Check the method signatures, supported types, dependencies, and null handling before registering a function. A Hive UDF or UDAF is not guaranteed to work unchanged.

When to use Java UDFs​

  • Implement scalar computation, aggregation, or row expansion that built-in functions cannot express.
  • Reuse compatible Java function logic when migrating from Hive.
  • Reuse large resources, such as dictionaries or models, within a backend process.

Data type mapping​

Use the following mappings for Java UDF arguments and return values:

SQL data typeJava type
BOOLEANBoolean
TINYINTByte
SMALLINTShort
INTInteger
BIGINTLong
LARGEINTBigInteger
FLOATFloat
DOUBLEDouble
DATELocalDate
DATETIMELocalDateTime
IPV4 / IPV6InetAddress
STRINGString
DECIMALBigDecimal
ARRAY<Type>ArrayList<Type>, List<Type> (nesting supported)
MAP<Type1,Type2>HashMap<Type1,Type2>, Map<Type1,Type2> (nesting supported)
STRUCT<Type...>ArrayList<Object>, List<Object>
VARBINARYbyte[] (recommended), Byte[]

Tip:

The ARRAY, MAP, and STRUCT types can contain nested types. For example, ARRAY<ARRAY<INT>> maps to ArrayList<ArrayList<Integer>>. The listed collection and binary mappings are implemented in Core 26.1.3.

Warning:

Use STRING rather than VARCHAR for string arguments and return values when registering a Java function.

Limitations​

  1. HLL, BITMAP, and QUANTILE_STATE are not supported as arguments or return types, including inside nested types.
  2. Java functions consume JVM memory on the backend compute nodes. Large aggregate states and resources can cause out-of-memory errors. Contact VeloDB Cloud support for heap sizing and runtime changes. Use the memory settings confirmed for your warehouse.
  3. To update function code, use a new class name and immutable JAR artifact, then register and verify the new function before replacing callers. If an update requires classpath changes or a backend restart, arrange it with VeloDB Cloud support.
  4. Built-in functions take precedence over user-defined functions by default. Qualify a function with its database, such as db.function(), to select a database function. To prefer user-defined functions in the current session, set prefer_udf_over_builtin = true.

Get started​

The Apache Doris Java UDF examples provide additional implementation examples. Use a warehouse SQL user with the ADMIN privilege to create functions, and select a database before running the examples. Database-scoped function lookup requires SELECT on that database.

Only register code that you trust. A Java UDF executes application code on warehouse compute nodes. Prepare an immutable JAR that includes its dependencies and make it accessible to the frontend and backend nodes using the distribution method agreed with VeloDB Cloud support. In the SQL below, replace each https://<jar-host>/... URL with your JAR URL. The URL must return the same artifact to all relevant nodes. Do not embed credentials in the URL.

Functions are database-scoped unless you register them with CREATE GLOBAL FUNCTION. In the current database, call a database function by name. From another database, qualify it as database_name.function_name. A global function is visible across databases in the same warehouse.

The examples use the following test_table and show the expected function results.

CREATE TABLE `test_table` (
id int NULL,
d1 double NULL,
str string NULL
) ENGINE=OLAP
DUPLICATE KEY(`id`)
DISTRIBUTED BY HASH(`id`) BUCKETS 1;

insert into test_table values (1, 111.11, "a,b,c");
insert into test_table values (6, 666.66, "d,e");

Java UDF example​

Add one to an integer

When writing a UDF in Java, the main entry point must be the evaluate function, which is consistent with other engines such as Hive. The following example writes an AddOne UDF that adds one to an integer input.

  1. Write the Java code and package it into a JAR file:

    package org.apache.doris.udf;

    public class AddOne {
    public Integer evaluate(Integer value) {
    return value == null ? null : value + 1;
    }
    }
  2. Register the Java UDF in your warehouse. For more syntax, see CREATE FUNCTION.

    CREATE FUNCTION java_udf_add_one(int) RETURNS int PROPERTIES (
    "file"="https://<jar-host>/java-udf-demo-jar-with-dependencies.jar",
    "symbol"="org.apache.doris.udf.AddOne",
    "always_nullable"="true",
    "type"="JAVA_UDF",
    "volatility"="immutable"
    );

Warning:

Function registration reads the JAR to calculate a checksum. Execution loads the same artifact on backend nodes and validates its checksum. A URL that is unreachable from any required node, or returns different content, causes registration or execution to fail. A file:// path refers to a warehouse node, not your client computer. Use local paths only when VeloDB Cloud support has arranged the same artifact at the required path.

  1. Call the UDF. Calling a UDF requires the SELECT privilege on the corresponding database. To view registered UDFs, use the SHOW FUNCTIONS command.

    select id,java_udf_add_one(id) from test_table;
    +------+----------------------+
    | id | java_udf_add_one(id) |
    +------+----------------------+
    | 1 | 2 |
    | 6 | 7 |
    +------+----------------------+
  2. When a UDF is no longer needed, use the DROP FUNCTION command to delete it.

For large resource files and static state, see Reuse static resources.

Java UDAF example​

Implement sum and median aggregates

When writing a UDAF in Java, you need to implement a set of required functions (marked as required) and an inner class State. The following two examples illustrate this.

  1. Write the corresponding Java UDAF code and package it into a JAR file.

Sum aggregation​

SimpleDemo accepts and returns INT, and implements a sum-like aggregate.

package org.apache.doris.udf;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.logging.Logger;

public class SimpleDemo {

Logger log = Logger.getLogger("SimpleDemo");

//Need an inner class to store data
/*required*/
public static class State {
/*some variables if you need */
public int sum = 0;
}

/*required*/
public State create() {
/* here could do some init work if needed */
return new State();
}

/*required*/
public void destroy(State state) {
/* here could do some destroy work if needed */
}

/*Not Required*/
public void reset(State state) {
/*if you want this udaf function can work with window function.*/
/*Must impl this, it will be reset to init state after calculate every window frame*/
state.sum = 0;
}

/*required*/
//first argument is State, then other types your input
public void add(State state, Integer val) throws Exception {
/* here doing update work when input data*/
if (val != null) {
state.sum += val;
}
}

/*required*/
public void serialize(State state, DataOutputStream out) throws IOException {
/* serialize some data into buffer */
out.writeInt(state.sum);
}

/*required*/
public void deserialize(State state, DataInputStream in) throws IOException {
/* deserialize get data from buffer before you put */
int val = in.readInt();
state.sum = val;
}

/*required*/
public void merge(State state, State rhs) throws Exception {
/* merge data from state */
state.sum += rhs.sum;
}

/*required*/
//return Type you defined
public Integer getValue(State state) throws Exception {
/* return finally result */
return state.sum;
}
}

Median aggregation​

MedianUDAF accepts DOUBLE values and an INT output scale, and returns a DOUBLE. This in-memory example retains all values and uses string-based serialization, so use it only for small groups. A production implementation needs bounded state and a serialization format suited to its data size. The scale must be non-NULL and constant within each group.

package org.apache.doris.udf.demo;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.logging.Logger;

/*UDAF that calculates the median*/
public class MedianUDAF {
Logger log = Logger.getLogger("MedianUDAF");

// State storage
public static class State {
// Precision of the returned result
int scale = 0;
// Whether this is the first time the add method is executed for the data under a certain aggregation condition of a tablet
boolean isFirst = true;
// Data storage
public StringBuilder stringBuilder;
}

// State initialization
public State create() {
State state = new State();
// Pre-initialize the buffer based on the volume of data to be aggregated under each aggregation condition of each tablet, to improve performance
state.stringBuilder = new StringBuilder(1000);
return state;
}


// The execution unit processes each piece of data under each aggregation condition of each tablet
public void add(State state, Double val, int scale) throws IOException {
if (val != null && state.isFirst) {
state.scale = scale;
state.stringBuilder.append(val).append(",");
state.isFirst = false;
} else if (val != null) {
state.stringBuilder.append(val).append(",");
}
}

// Output data after processing, waiting for aggregation
public void serialize(State state, DataOutputStream out) throws IOException {
// Currently only DataOutputStream is provided. To serialize an object, consider concatenating strings, converting to JSON, or serializing into a byte array.
// To serialize the State object, you may need to implement the Serializable interface on the State inner class yourself.
// Ultimately, everything must be transmitted via DataOutputStream.
out.writeInt(state.scale);
out.writeUTF(state.stringBuilder.toString());
}

// Get the data output by the data-processing execution unit
public void deserialize(State state, DataInputStream in) throws IOException {
state.scale = in.readInt();
state.stringBuilder = new StringBuilder(in.readUTF());
state.isFirst = state.stringBuilder.length() == 0;
}

// The aggregation execution unit merges the processing results of data under a certain key according to the aggregation condition. The first time each key is merged, the state1 parameter is the initialized instance.
public void merge(State state1, State state2) throws IOException {
if (state2.stringBuilder.length() > 0) {
state1.scale = state2.scale;
state1.stringBuilder.append(state2.stringBuilder);
state1.isFirst = false;
}
}

// Process the merged data for each key and output the final result
public Double getValue(State state) throws IOException {
if (state.stringBuilder.length() == 0) {
return null;
}
String[] strings = state.stringBuilder.toString().split(",");
double[] doubles = Arrays.stream(strings).mapToDouble(Double::parseDouble).toArray();

Arrays.sort(doubles);
double n = doubles.length - 1;
double index = n * 0.5;

int low = (int) Math.floor(index);
int high = (int) Math.ceil(index);

double value = low == high ? doubles[low] : (doubles[low] + doubles[high]) * 0.5;

BigDecimal decimal = BigDecimal.valueOf(value);
return decimal.setScale(state.scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}

// Executed after each execution unit finishes
public void destroy(State state) {
}

}

Register and call the aggregate​

  1. Register the Java UDAF in your warehouse. For more syntax, see CREATE FUNCTION.

    CREATE AGGREGATE FUNCTION simple_demo(INT) RETURNS INT PROPERTIES (
    "file"="https://<jar-host>/java-udaf.jar",
    "symbol"="org.apache.doris.udf.SimpleDemo",
    "always_nullable"="true",
    "type"="JAVA_UDF",
    "volatility"="immutable"
    );
  2. Call the Java UDAF. You can aggregate by group, or aggregate over all results:

    select simple_demo(id) from test_table group by id;
    +-----------------+
    | simple_demo(id) |
    +-----------------+
    | 1 |
    | 6 |
    +-----------------+
    select simple_demo(id) from test_table;
    +-----------------+
    | simple_demo(id) |
    +-----------------+
    | 7 |
    +-----------------+

Java UDWF example​

Use a Java aggregate in a window

The code structure of a Java UDWF is exactly the same as that of a Java UDAF; you only need to additionally implement the reset interface to reset all state to the initial value:

void reset(State state)
  1. Write and package the Java UDWF code (same as above).

  2. Register the Java UDWF in your warehouse. The registration is the same as for a Java UDAF. For more syntax, see CREATE FUNCTION.

    CREATE AGGREGATE FUNCTION simple_demo_window(INT) RETURNS INT PROPERTIES (
    "file"="https://<jar-host>/java-udaf.jar",
    "symbol"="org.apache.doris.udf.SimpleDemo",
    "always_nullable"="true",
    "type"="JAVA_UDF",
    "volatility"="immutable"
    );
  3. Call the Java UDWF to compute results within a specified window range. For more syntax, see Window Functions:

    select id, simple_demo_window(id) over(partition by id order by d1 rows between 1 preceding and 1 following) as res from test_table;
    +------+------+
    | id | res |
    +------+------+
    | 1 | 1 |
    | 6 | 6 |
    +------+------+

Java UDTF example​

Expand comma-separated strings into rows

Like a scalar UDF, a UDTF implements evaluate. Its return value must map to an SQL ARRAY.

  1. Write the corresponding Java UDTF code and package it into a JAR file:

    package org.apache.doris.udf.demo;

    import java.util.ArrayList;
    import java.util.Arrays;

    public class UDTFStringTest {
    public ArrayList<String> evaluate(String value, String separator) {
    if (value == null || separator == null) {
    return null;
    } else {
    return new ArrayList<>(Arrays.asList(value.split(separator)));
    }
    }
    }
  2. Register the Java UDTF in your warehouse. Registration creates two UDTFs at the same time: the version with the _outer suffix appended to the function name handles the case where the result has zero rows specially. For details, see the OUTER combinator. For more syntax, see CREATE FUNCTION.

    CREATE TABLES FUNCTION java_utdf(string, string) RETURNS array<string> PROPERTIES (
    "file"="https://<jar-host>/java-udtf.jar",
    "symbol"="org.apache.doris.udf.demo.UDTFStringTest",
    "always_nullable"="true",
    "type"="JAVA_UDF",
    "volatility"="immutable"
    );
  3. Call the Java UDTF. Use a UDTF with Lateral View to expand each input row into output rows:

    select id, str, e1 from test_table lateral view java_utdf(str,',') tmp as e1;
    +------+-------+------+
    | id | str | e1 |
    +------+-------+------+
    | 1 | a,b,c | a |
    | 1 | a,b,c | b |
    | 1 | a,b,c | c |
    | 6 | d,e | d |
    | 6 | d,e | e |
    +------+-------+------+

Reuse static resources​

Without static loading, each Java function executor loads its class metadata and closes its class loader when the executor ends. Concurrent executors can therefore create separate copies of static resources.

Large dictionaries, models, or connection pools can increase memory use when each executor initializes its own copy. The following methods can share class resources within a backend JVM. They do not create a warehouse-wide singleton or shared state across compute nodes. Prefer SQL built-in functions when they meet your needs, and size any retained resources for the available compute memory.

Split out a resource JAR​

Split the resource-loading code into a separate JAR, and have other business JARs reference this resource JAR.

Suppose the code has been split into two files: DictLibrary (resource class) and FunctionUdf (business class).

package org.apache.doris.udf;

import java.util.HashMap;

public class DictLibrary {
private static HashMap<String, String> res = new HashMap<>();

static {
// suppose we built this dictionary from a certain local file.
res.put("key1", "value1");
res.put("key2", "value2");
res.put("key3", "value3");
res.put("0", "value4");
res.put("1", "value5");
res.put("2", "value6");
}

public static String evaluate(String key) {
if (key == null) {
return null;
}
return res.get(key);
}
}
package org.apache.doris.udf;

public class FunctionUdf {
public String evaluate(String key) {
String value = DictLibrary.evaluate(key);
return value;
}
}

The steps are as follows:

  1. Compile the DictLibrary file separately to generate a standalone resource JAR DictLibrary.jar:

    mkdir -p build-resource
    javac -d build-resource ./DictLibrary.java
    jar -cf ./DictLibrary.jar -C build-resource .
  2. Compile the FunctionUdf file, referencing the resource package from the previous step as a dependency, to obtain the UDF business package FunctionUdf.jar:

    mkdir -p build-function
    javac -cp ./DictLibrary.jar -d build-function ./FunctionUdf.java
    jar -cf ./FunctionUdf.jar -C build-function .
  3. Ask VeloDB Cloud support to deploy the resource JAR through the supported runtime extension mechanism on all required nodes and arrange any restart. This method changes the runtime classpath and is not a SQL-only operation.

  4. Publish the business JAR at an approved URL and register the UDF. The runtime-loaded resource classes remain available when an individual function executor closes:

    CREATE FUNCTION java_udf_dict(string) RETURNS string PROPERTIES (
    "file"="https://<jar-host>/FunctionUdf.jar",
    "symbol"="org.apache.doris.udf.FunctionUdf",
    "always_nullable"="true",
    "type"="JAVA_UDF",
    "volatility"="immutable"
    );

Use the backend class cache​

Set static_load = true when creating a function to reuse its class metadata and class loader within a backend JVM. The default is false.

In Core 26.1.3, cached class metadata remains until the function is dropped. expiration_time is still accepted for backward compatibility but does not cause time-based eviction. Do not use it to control resource lifetime.

Each executor still creates its own function object. Use static fields for resources intended to be shared by executors on the same backend, and make shared mutable state thread-safe. Dropping and recreating a function creates a new function identity and invalidates its old cache.

Example code:

package org.apache.doris.udf;

public class Print {
private static final java.util.concurrent.atomic.AtomicInteger val =
new java.util.concurrent.atomic.AtomicInteger();
public Integer evaluate() {
return val.incrementAndGet();
}
}
CREATE FUNCTION print_12() RETURNS int
PROPERTIES (
"file" = "https://<jar-host>/java-udf-demo-jar-with-dependencies.jar",
"symbol" = "org.apache.doris.udf.Print",
"always_nullable"="true",
"type" = "JAVA_UDF",
"static_load" = "true",
"volatility" = "volatile"
);

For repeated calls that use the same backend JVM and cached class, a possible sequence is shown below. Distributed execution can use different backends, so a monotonically increasing warehouse-wide sequence is not guaranteed. Because this example changes on each call, it must remain volatile.

mysql [test_query_qa]>select print_12();
+------------+
| print_12() |
+------------+
| 1 |
+------------+

mysql [test_query_qa]>select print_12();
+------------+
| print_12() |
+------------+
| 2 |
+------------+

mysql [test_query_qa]>select print_12();
+------------+
| print_12() |
+------------+
| 3 |
+------------+

Common errors​

SymptomCheck and resolution
java_udf has been disabled.Confirm that this is a BYOC warehouse and contact VeloDB Cloud support to check enablement.
Registration cannot compute the JAR checksum, or execution reports a checksum mismatchVerify that the approved JAR URL is reachable from the required nodes and serves one immutable artifact.
A class or method cannot be foundCheck the fully qualified symbol, package name, public method signature, no-argument constructor, and bundled dependencies.
The function cannot be resolvedCheck the current database, qualified function name, argument types, and database SELECT privilege.
The query runs out of JVM memoryReduce aggregate state or resource size. Contact VeloDB Cloud support for runtime sizing.

Clean up​

UDF queries consume warehouse compute and memory. Remove test functions with DROP FUNCTION and drop test_table when you finish. If support deployed runtime resource JARs, arrange their removal separately. See Billing overview for warehouse charges.