GLOBAL keyword in the related SQL statements (CREATE/SHOW/DROP).
This topic how to develop and use various UDFs.
Currently, the database supports scalar UDFs, user-defined aggregate functions (UDAFs), user-defined window functions (UDWFs), and user-defined table functions (UDTFs).
Prerequisites
- You have installed Apache Maven, so you can create and compile Java projects.
- You have installed JDK 17 on your servers.
-
The Java UDF feature is enabled. You can set the FE configuration item
enable_udftotruein the FE configuration file fe/conf/fe.conf to enable this feature, and then restart the FE nodes to make the settings take effect. For more information, see Parameter configuration.
Develop and use UDFs
You need to create a Maven project and compile the UDF you need by using the Java programming language.Step 1: Create a Maven project
Create a Maven project, whose basic directory structure is as follows:Step 2: Add dependencies
Add the following dependencies to the pom.xml file:Step 3: Compile a UDF
Use the Java programming language to compile a UDF.Compile a scalar UDF
A scalar UDF operates on a single row of data and returns a single value. When you use a scalar UDF in a query, each row corresponds to a single value in the result set. Typical scalar functions includeUPPER, LOWER, ROUND, and ABS.
Suppose that the values of a field in your JSON data are JSON strings rather than JSON objects. When you use an SQL statement to extract JSON strings, you need to run GET_JSON_STRING twice, for example, GET_JSON_STRING(GET_JSON_STRING('{"key":"{\\"k0\\":\\"v0\\"}"}', "$.key"), "$.k0").
To simplify the SQL statement, you can compile a scalar UDF that can directly extract JSON strings, for example, MY_UDF_JSON_GET('{"key":"{\\"k0\\":\\"v0\\"}"}', "$.key.k0").
NOTE
The data types of the request parameters and return parameters in the method must be the same as those declared in the CREATE FUNCTION statement that is to be executed in Step 6 and conform to the mapping that is provided in the “Mapping between SQL data types and Java data types” section of this topic.
Compile a UDAF
A UDAF operates on multiple rows of data and returns a single value. Typical aggregate functions includeSUM, COUNT, MAX, and MIN, which aggregate multiple rows of data specified in each GROUP BY clause and return a single value.
Suppose that you want to compile a UDAF named MY_SUM_INT. Unlike the built-in aggregate function SUM, which returns BIGINT-type values, the MY_SUM_INT function supports only request parameters and returns parameters of the INT data type.
NOTE
The data types of the request parameters and return parameters in the methods must be the same as those declared in the CREATE FUNCTION statement that is to be executed in Step 6 and conform to the mapping that is provided in the “Mapping between SQL data types and Java data types” section of this topic.
During compilation, you must also use the buffer class
java.nio.ByteBuffer and the local variable serializeLength, which are described in the following table.
Take note of the following points for the deserialization of intermediate results stored in the
java.nio.ByteBuffer class:
- The remaining() method that is dependent on the
ByteBufferclass cannot be called to deserialize a state. - The clear() method cannot be called on the
ByteBufferclass. - The value of
serializeLengthmust be the same as the length of the written-in data. Otherwise, incorrect results are generated during serialization and deserialization.
Compile a UDWF
Unlike regular aggregate functions, a UDWF operates on a set of multiple rows, which are collectively called a window, and returns a value for each row. A typical window function includes anOVER clause that divides rows into multiple sets. It performs a calculation across each set of rows and returns a value for each row.
Suppose that you want to compile a UDWF named MY_WINDOW_SUM_INT. Unlike the built-in aggregate function SUM, which returns BIGINT-type values, the MY_WINDOW_SUM_INT function supports only request parameters and returns parameters of the INT data type.
NOTE
The data types of the request parameters and return parameters in the method must be the same as those declared in the CREATE FUNCTION statement that is to be executed in Step 6 and conform to the mapping that is provided in the “Mapping between SQL data types and Java data types” section of this topic.
Compile a UDTF
A UDTF reads one row of data and returns multiple values that can be considered to be a table. Table-valued functions are typically used to transform rows into columns.NOTE The database allows a UDTF to return a table that consists of multiple rows and one column.Suppose that you want to compile a UDTF named
MY_UDF_SPLIT. The MY_UDF_SPLIT function allows you to use spaces as delimiters and supports request parameters and return parameters of the STRING data type.
NOTE
The data types of the request parameters and return parameters in the method must be the same as those declared in the CREATE FUNCTION statement that is to be executed in Step 6 and conform to the mapping that is provided in the “Mapping between SQL data types and Java data types” section of this topic.
Step 4: Package the Java project
Run the following command to package the Java project:Step 5: Upload the Java project
Upload the JAR file udf-1.0-SNAPSHOT-jar-with-dependencies.jar to an HTTP server that keeps up and running and is accessible to all FEs and BEs in your cluster. Then, run the following command to deploy the file:NOTE In Step 6, the FEs will check the JAR file that contains the code for the UDF and calculate the checksum, and the BEs will download and execute the JAR file.
Step 6: Create the UDF in the database
The database allows you to create UDFs in two types of namespaces: database namespaces and global namespaces.- If you do not have visibility or isolation requirements for a UDF, you can create it as a global UDF. Then, you can reference the global UDF by using the function name without including the catalog and database names as prefixes to the function name.
- If you have visibility or isolation requirements for a UDF, or if you need to create the same UDF in different databases, you can create it in each individual database. As such, if your session is connected to the target database, you can reference the UDF by using the function name. If your session is connected to a different catalog or database other than the target database, you need to reference the UDF by including the catalog and database names as prefixes to the function name, for example,
catalog.database.function.
NOTICE Before you create and use a global UDF, you must contact the system administrator to grant you the required permissions. For more information, see GRANT.After you upload the JAR package, you can create UDFs in the database. For a global UDF, you must include the
GLOBAL keyword in the creation statement.
Syntax
Parameters
Create a scalar UDF
Run the following command to create the scalar UDF you have compiled in the preceding example:Vectorized (Arrow) input
Setting"input" = "arrow" switches a Java UDF from the per-row boxed calling convention to a
vectorized one: your method receives one Apache Arrow
FieldVector per argument covering the whole batch, and
(for scalar/UDTF) returns a FieldVector. Columns are exchanged with the backend zero-copy over the
Arrow C Data Interface, avoiding the
per-row boxing/unboxing of the default path.
Add the Arrow dependency to your Maven project (the version must match the one bundled with your
The database release), scoped provided since the BE already ships it:
arg.getAllocator() so the engine
owns their lifecycle.
Note
The BE runs the UDF in an embedded JVM that must expose java.nio to Arrow’s off-heap memory
layer. The shipped conf/be.conf already sets this via
JAVA_OPTS="... --add-opens=java.base/java.nio=ALL-UNNAMED ..."; if you customize JAVA_OPTS,
keep that flag or arrow-input UDFs fail to initialize.
Scalar — evaluate(FieldVector...) returns a FieldVector:
process(FieldVector...) returns T[][] (one T[] of output rows per input row; only the
input is vectorized):
update(State, FieldVector...) receives the whole batch destined for one state;
create/merge/serialize/finalize keep their normal (boxed) signatures.
LIMITATIONSMapping between SQL types and the Arrow
- Arrow-input UDAFs are supported only for global aggregation and sorted-streaming aggregation (a whole batch belongs to one state). A query that routes an arrow UDAF through a hash
GROUP BYfails with a clear error — use the default (boxed) input forGROUP BYUDAFs.- Arrow input is not supported for window functions (
analytic = "true") yet.
FieldVector your method receives:
Create a UDAF
Run the following command to create the UDAF you have compiled in the preceding example:Create a UDWF
Run the following command to create the UDWF you have compiled in the preceding example:analytic: Whether the UDF is a window function. Set the value to true. The descriptions of other properties are the same as those in Create a scalar UDF.
Create a UDTF
Run the following command to create the UDTF you have compiled in the preceding example:Step 7: Use the UDF
After you create the UDF, you can test and use it based on your business needs.Use a scalar UDF
Run the following command to use the scalar UDF you have created in the preceding example:Use a UDAF
Run the following command to use the UDAF you have created in the preceding example:Use a UDWF
Run the following command to use the UDWF you have created in the preceding example:Use a UDTF
Run the following command to use the UDTF you have created in the preceding example:NOTE
- The first
MY_UDF_SPLITin the preceding code snippet is the alias of the column that is returned by the secondMY_UDF_SPLIT, which is a function.- You cannot use
AS t2(f1)to specify the aliases of the table and its columns that are to be returned.
View UDFs
Run the following command to query UDFs:Drop a UDF
Run the following command to drop a UDF:Mapping between SQL data types and Java data types
NOTE Scalar UDFs, UDAFs, and UDTFs all support nestedARRAY,MAP, andSTRUCTparameter/return types — including arbitrary nesting such asARRAY<ARRAY<INT>>,ARRAY<MAP<INT, STRING>>,MAP<INT, ARRAY<STRING>>,STRUCT<a INT, b ARRAY<STRING>>, andARRAY<STRUCT<a INT, b STRING>>. The leaf element type must still be one of the scalar types listed below. Because of Java type erasure, the Java method signature only needs the rawjava.util.List/java.util.Mapfor ARRAY / MAP slots whose subtree contains no STRUCT; the database drives the per-row conversion from the SQL signature. STRUCT slots, on the other hand, must be bound to a concrete Javarecordclass so the analyzer can preserve the formal record type through the JNI boundary (see STRUCT type binding below).
NOTE ForDECIMALparameters, BigDecimal values produced by the UDF are rescaled to the column’s declared(precision, scale)usingRoundingMode.HALF_UPbefore they are written back. If the rescaled value does not fit in the declared(precision, scale), the behavior follows the sessionoverflow_mode:
OUTPUT_NULL(default): the offending row is written asNULL.REPORT_ERROR: the query aborts with anArithmeticException.
STRUCT type binding
STRUCT parameters and return types must be bound to a Java record
class (JDK 14+) declared by the UDF author. The mapping is positional:
- The record’s component count must match the SQL
STRUCTfield count. - Each component’s type must match the corresponding SQL field type by
position; component names are not enforced (Java identifiers cannot
represent every legal SQL field name, and CREATE FUNCTION binds by
position regardless of the session’s
STRUCT_CAST_BY_NAMEsetting). - Nested
STRUCTis supported in any position: as a record component, as anARRAYelement (List<MyRecord>), or as aMAPkey/value (Map<String, MyRecord>).
update(State, ...)
arguments and the finalize(State) return type. For UDTF, the record
class is supplied for the process(...) arguments and the
TYPE[] process(...) element return type.