Java UDF - 图1tip

Java UDF is supported starting from Doris version 1.2.

Introduction to Java UDF

Java UDF provides users with a Java interface for writing UDFs, making it convenient for users to execute custom functions using the Java language.

Doris supports writing UDFs, UDAFs, and UDTFs using JAVA. Unless otherwise specified, UDF is used as a general term for all user-defined functions in the following text.

Creating UDF

The implemented jar package can be placed locally or stored on a remote server for download via HTTP, but each FE and BE node must be able to access the jar package. “file”=” file:///path/to/java-udf-demo-jar-with-dependencies.jar “ “file”=” http://IP:port/udf-code.jar

Otherwise, an error message Couldn't open file ...... will be returned.

For more syntax help, refer to CREATE FUNCTION.

UDF

  1. CREATE FUNCTION java_udf_add_one(int) RETURNS int PROPERTIES (
  2. "file"="file:///path/to/java-udf-demo-jar-with-dependencies.jar",
  3. "symbol"="org.apache.doris.udf.AddOne",
  4. "always_nullable"="true",
  5. "type"="JAVA_UDF"
  6. );

UDAF

  1. CREATE AGGREGATE FUNCTION middle_quantiles(DOUBLE,INT) RETURNS DOUBLE PROPERTIES (
  2. "file"="file:///pathTo/java-udaf.jar",
  3. "symbol"="org.apache.doris.udf.demo.MiddleNumberUDAF",
  4. "always_nullable"="true",
  5. "type"="JAVA_UDF"
  6. );

UDTF

Java UDF - 图2tip

UDTF is supported starting from Doris version 3.0.

  1. CREATE TABLES FUNCTION java-utdf(string, string) RETURNS array<string> PROPERTIES (
  2. "file"="file:///pathTo/java-udaf.jar",
  3. "symbol"="org.apache.doris.udf.demo.UDTFStringTest",
  4. "always_nullable"="true",
  5. "type"="JAVA_UDF"
  6. );

Using UDF

To utilize UDFs, users must possess the SELECT privilege for the corresponding database.

The usage of UDFs is identical to standard functions, with the primary distinction being that built-in functions have a global scope, while UDFs are scoped within the DB.

When the session is linked within the database, directly using the UDF name will search for the corresponding UDF within the current DB. Otherwise, users must explicitly specify the UDF’s database name, for example, dbName.funcName.

Dropping UDF

If a UDF is no longer needed, it can be dropped using the following command, as detailed in DROP FUNCTION.

Type Correspondence

TypeUDF Argument Type
BoolBoolean
TinyIntByte
SmallIntShort
IntInteger
BigIntLong
LargeIntBigInteger
FloatFloat
DoubleDouble
DateLocalDate
DatetimeLocalDateTime
StringString
DecimalBigDecimal
array<Type>ArrayList<Type>
map<Type1,Type2>HashMap<Type1,Type2>
struct<Type…>ArrayList<Object> (from version 3.0.0)

Java UDF - 图3tip

array/map/struct types can be nested with other types. For instance, Doris: array<array<int>> corresponds to JAVA UDF Argument Type: ArrayList<ArrayList<Integer>>. Other types follow the same pattern.

Java UDF - 图4Warning

When creating functions, avoid using varchar in place of string, as this may cause the function to fail.

Writing UDF

This section mainly introduces how to develop a Java UDF. Examples are provided in samples/doris-demo/java-udf-demo/ for reference. Click here to view them.

When writing a UDF in Java, the main entry point must be the evaluate function. This is consistent with other engines like Hive. In this example, we write an AddOne UDF to perform an increment operation on integer inputs.

It is worth mentioning that this example not only supports Java UDFs in Doris but is also a UDF supported by Hive. This means that Hive UDFs can be directly migrated to Doris.

Additionally, if the UDF being defined needs to load large resource files or if you want to define global static variables, you can refer to the static variable loading method described at the bottom of the document.

UDF

  1. public class AddOne extends UDF {
  2. public Integer evaluate(Integer value) {
  3. return value == null ? null : value + 1;
  4. }
  5. }

UDAF

When writing a UDAF using Java code, there are some required functions (marked as required) and an inner class State that must be implemented. Below is a specific example to illustrate.

Example 1

The following SimpleDemo will implement a simple function similar to sum, with the input parameter being INT and the output parameter being INT.

  1. package org.apache.doris.udf.demo;
  2. import java.io.DataInputStream;
  3. import java.io.DataOutputStream;
  4. import java.io.IOException;
  5. import java.util.logging.Logger;
  6. public class SimpleDemo {
  7. Logger log = Logger.getLogger("SimpleDemo");
  8. //Need an inner class to store data
  9. /*required*/
  10. public static class State {
  11. /*some variables if you need */
  12. public int sum = 0;
  13. }
  14. /*required*/
  15. public State create() {
  16. /* here could do some init work if needed */
  17. return new State();
  18. }
  19. /*required*/
  20. public void destroy(State state) {
  21. /* here could do some destroy work if needed */
  22. }
  23. /*Not Required*/
  24. public void reset(State state) {
  25. /*if you want this udaf function can work with window function.*/
  26. /*Must impl this, it will be reset to init state after calculate every window frame*/
  27. state.sum = 0;
  28. }
  29. /*required*/
  30. //first argument is State, then other types your input
  31. public void add(State state, Integer val) throws Exception {
  32. /* here doing update work when input data*/
  33. if (val != null) {
  34. state.sum += val;
  35. }
  36. }
  37. /*required*/
  38. public void serialize(State state, DataOutputStream out) {
  39. /* serialize some data into buffer */
  40. try {
  41. out.writeInt(state.sum);
  42. } catch (Exception e) {
  43. /* Do not throw exceptions */
  44. log.info(e.getMessage());
  45. }
  46. }
  47. /*required*/
  48. public void deserialize(State state, DataInputStream in) {
  49. /* deserialize get data from buffer before you put */
  50. int val = 0;
  51. try {
  52. val = in.readInt();
  53. } catch (Exception e) {
  54. /* Do not throw exceptions */
  55. log.info(e.getMessage());
  56. }
  57. state.sum = val;
  58. }
  59. /*required*/
  60. public void merge(State state, State rhs) throws Exception {
  61. /* merge data from state */
  62. state.sum += rhs.sum;
  63. }
  64. /*required*/
  65. //return Type you defined
  66. public Integer getValue(State state) throws Exception {
  67. /* return finally result */
  68. return state.sum;
  69. }
  70. }

Example 2

  1. package org.apache.doris.udf.demo;
  2. import java.io.DataInputStream;
  3. import java.io.DataOutputStream;
  4. import java.math.BigDecimal;
  5. import java.util.Arrays;
  6. import java.util.logging.Logger;
  7. /* UDAF to calculate the median */
  8. public class MedianUDAF {
  9. Logger log = Logger.getLogger("MedianUDAF");
  10. // State storage
  11. public static class State {
  12. // Precision of the return result
  13. int scale = 0;
  14. // Whether it is the first time to execute the add method for a certain aggregation condition under a certain tablet
  15. boolean isFirst = true;
  16. // Data storage
  17. public StringBuilder stringBuilder;
  18. }
  19. // Initialize the state
  20. public State create() {
  21. State state = new State();
  22. // Pre-initialize based on the amount of data that needs to be aggregated under each aggregation condition of each tablet to increase performance
  23. state.stringBuilder = new StringBuilder(1000);
  24. return state;
  25. }
  26. // Process each data under respective aggregation conditions for each tablet
  27. public void add(State state, Double val, int scale) {
  28. try {
  29. if (val != null && state.isFirst) {
  30. state.stringBuilder.append(scale).append(",").append(val).append(",");
  31. state.isFirst = false;
  32. } else if (val != null) {
  33. state.stringBuilder.append(val).append(",");
  34. }
  35. } catch (Exception e) {
  36. // If it cannot be guaranteed that there will be no exceptions, it is recommended to maximize exception capture in each method, as handling of exceptions thrown by Java is currently not supported
  37. log.info("Data acquisition exception: " + e.getMessage());
  38. }
  39. }
  40. // Data needs to be output for aggregation after processing
  41. public void serialize(State state, DataOutputStream out) {
  42. try {
  43. // Currently, only DataOutputStream is provided. If serialization of objects is required, methods such as concatenating strings, converting to JSON, or serializing into byte arrays can be considered
  44. // If the State object needs to be serialized, it may be necessary to implement a serialization interface for the State inner class
  45. // Ultimately, everything needs to be transmitted via DataOutputStream
  46. out.writeUTF(state.stringBuilder.toString());
  47. } catch (Exception e) {
  48. log.info("Serialization exception: " + e.getMessage());
  49. }
  50. }
  51. // Obtain the output data from the data processing execution unit
  52. public void deserialize(State state, DataInputStream in) {
  53. try {
  54. String string = in.readUTF();
  55. state.scale = Integer.parseInt(String.valueOf(string.charAt(0)));
  56. StringBuilder stringBuilder = new StringBuilder(string.substring(2));
  57. state.stringBuilder = stringBuilder;
  58. } catch (Exception e) {
  59. log.info("Deserialization exception: " + e.getMessage());
  60. }
  61. }
  62. // The aggregation execution unit merges the processing results of data under certain aggregation conditions for a given key. The state1 parameter is the initialized instance during the first merge of each key
  63. public void merge(State state1, State state2) {
  64. try {
  65. state1.scale = state2.scale;
  66. state1.stringBuilder.append(state2.stringBuilder.toString());
  67. } catch (Exception e) {
  68. log.info("Merge result exception: " + e.getMessage());
  69. }
  70. }
  71. // Output the final result after merging the data for each key
  72. public Double getValue(State state) {
  73. try {
  74. String[] strings = state.stringBuilder.toString().split(",");
  75. double[] doubles = new double[strings.length];
  76. for (int i = 0; i < strings.length - 1; i++) {
  77. doubles[i] = Double.parseDouble(strings[i + 1]);
  78. }
  79. Arrays.sort(doubles);
  80. double n = doubles.length;
  81. if (n == 0) {
  82. return 0.0;
  83. }
  84. double index = (n - 1) / 2.0;
  85. int low = (int) Math.floor(index);
  86. int high = (int) Math.ceil(index);
  87. double value = low == high ? (doubles[low] + doubles[high]) / 2 : doubles[high];
  88. BigDecimal decimal = new BigDecimal(value);
  89. return decimal.setScale(state.scale, BigDecimal.ROUND_HALF_UP).doubleValue();
  90. } catch (Exception e) {
  91. log.info("Calculation exception: " + e.getMessage());
  92. }
  93. return 0.0;
  94. }
  95. // Executed after each execution unit completes
  96. public void destroy(State state) {
  97. }
  98. }

UDTF

Similar to UDFs, UDTFs require users to implement an evaluate method. However, the return value of a UDTF must be of the Array type.

Additionally, table functions in Doris may exhibit different behaviors due to the _outer suffix. For more details, refer to OUTER combinator.

  1. public class UDTFStringTest {
  2. public ArrayList<String> evaluate(String value, String separator) {
  3. if (value == null || separator == null) {
  4. return null;
  5. } else {
  6. return new ArrayList<>(Arrays.asList(value.split(separator)));
  7. }
  8. }
  9. }

Best Practices

Loading static variables

Currently, in Doris, executing a UDF function, e.g., select udf(col) from table, will load the udf.jar package for each concurrent instance, and unload the udf.jar package when the instance ends. If the udf.jar file needs to load a file of several hundred MBs, the memory usage will increase sharply due to concurrency, potentially leading to OOM (Out of Memory).

The solution is to split the resource loading code, generate a separate jar package, and have other packages directly reference this resource jar package.

Assume the files have been split into DictLibrary and FunctionUdf.

  1. Compile the DictLibrary file separately to generate an independent jar package, resulting in a resource file DictLibrary.jar:

    1. javac ./DictLibrary.java
    2. jar -cf ./DictLibrary.jar ./DictLibrary.class
    1. public class DictLibrary {
    2. private static HashMap<String, String> res = new HashMap<>();
    3. static {
    4. // suppose we built this dictionary from a certain local file.
    5. res.put("key1", "value1");
    6. res.put("key2", "value2");
    7. res.put("key3", "value3");
    8. res.put("0", "value4");
    9. res.put("1", "value5");
    10. res.put("2", "value6");
    11. }
    12. public static String evaluate(String key) {
    13. if (key == null) {
    14. return null;
    15. }
    16. return res.get(key);
    17. }
    18. }
    1. public class FunctionUdf {
    2. public String evaluate(String key) {
    3. String value = DictLibrary.evaluate(key);
    4. return value;
    5. }
    6. }
  2. Then compile the FunctionUdf file, directly referencing the resource package from the previous step, resulting in the FunctionUdf.jar package:

    1. javac -cp ./DictLibrary.jar ./FunctionUdf.java
    2. jar -cvf ./FunctionUdf.jar ./FunctionUdf.class
  3. After the above two steps, you will get two jar packages. To allow the resource jar package to be referenced by all concurrent instances, place it in the deployment path fe/custom_libbe/custom_lib. After the restarting, it will be loaded with the JVM startup.

  4. Finally, use the create function statement to create a UDF function

    1. CREATE FUNCTION java_udf_dict(string) RETURNS string PROPERTIES (
    2. "symbol"="org.apache.doris.udf.FunctionUdf",
    3. "always_nullable"="true",
    4. "type"="JAVA_UDF"
    5. );

In this loading mode, both FunctionUdf.jar and DictLibrary.jar are in the custom_lib path of FE and BE. This way, the packages will be loaded and released with the service startup and shutdown.

You can also customize the path to FunctionUdf.jar using file:///, but only under custom_lib.

Usage Notes

  1. Complex data types (HLL, Bitmap) are not supported.

  2. Users are currently allowed to specify the maximum JVM heap size. The configuration item is the -Xmx part of JAVA_OPTS in be.conf. The default is 1024m. If you need to aggregate data, it is recommended to increase this value to enhance performance and reduce the risk of memory overflow.

  3. For Char type UDFs, use the String type when creating the function.

  4. Due to issues with JVM loading classes with the same name, do not use multiple classes with the same name as UDF implementations simultaneously. If you want to update a UDF with a class of the same name, you need to restart BE to reload the classpath.