Java UDF

SinceVersion 1.2.0

Java UDF

Java UDF provides users with a Java interface written in UDF to facilitate the execution of user-defined functions in Java language. Compared with native UDF implementation, Java UDF has the following advantages and limitations:

  1. The advantages
  • Compatibility: Using Java UDF can be compatible with different Doris versions, so when upgrading Doris version, Java UDF does not need additional migration. At the same time, Java UDF also follows the same programming specifications as hive / spark and other engines, so that users can directly move Hive / Spark UDF jar to Doris.
  • Security: The failure or crash of Java UDF execution will only cause the JVM to report an error, not the Doris process to crash.
  • Flexibility: In Java UDF, users can package the third-party dependencies together in the user jar.
  1. Restrictions on use
  • Performance: Compared with native UDF, Java UDF will bring additional JNI overhead, but through batch execution, we have minimized the JNI overhead as much as possible.
  • Vectorized engine: Java UDF is only supported on vectorized engine now.

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>
  • Array/Map types can nested other types, Eg: In Doris: array<array<int>> corresponds to JAVA UDF Argument Type: ArrayList<ArrayList<Integer>>, and so on.

Write UDF functions

This section mainly introduces how to develop a Java UDF. Samples for the Java version are provided under samples/doris-demo/java-udf-demo/ for your reference, Check it out here

To use Java UDF, the main entry of UDF must be the evaluate function. This is consistent with other engines such as Hive. In the example of AddOne, we have completed the operation of adding an integer as the UDF.

It is worth mentioning that this example is not only the Java UDF supported by Doris, but also the UDF supported by Hive, that’s to say, for users, Hive UDF can be directly migrated to Doris.

Create UDF

  1. CREATE FUNCTION
  2. name ([,...])
  3. [RETURNS] rettype
  4. PROPERTIES (["key"="value"][,...])

Instructions:

  1. symbol in properties represents the class name containing UDF classes. This parameter must be set.
  2. The jar package containing UDF represented by file in properties must be set.
  3. The UDF call type represented by type in properties is native by default. When using java UDF, it is transferred to Java_UDF.
  4. In PROPERTIES always_nullable indicates whether there may be a NULL value in the UDF return result. It is an optional parameter. The default value is true.
  5. name: A function belongs to a DB and name is of the formdbName.funcName. When dbName is not explicitly specified, the db of the current session is useddbName.

Sample:

  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. );
  • “file”=” http://IP:port/udf -code. Jar “, you can also use http to download jar packages in a multi machine environment.

  • The “always_nullable” is optional attribute, if there is special treatment for the NULL value in the calculation, it is determined that the result will not return NULL, and it can be set to false, so that the performance may be better in the whole calculation process.

  • If you use the local path method, the jar package that the database driver depends on, the FE and BE nodes must be placed here

Create UDAF

When using Java code to write UDAF, there are some functions that must be implemented (mark required) and an inner class State, which will be explained with a specific example below. The following SimpleDemo will implement a simple function similar to sum, the input parameter is INT, and the output parameter is INT

  1. package org.apache.doris.udf.demo;
  2. import java.io.DataInputStream;
  3. import java.io.DataOutputStream;
  4. import java.io.IOException;
  5. public class SimpleDemo {
  6. //Need an inner class to store data
  7. /*required*/
  8. public static class State {
  9. /*some variables if you need */
  10. public int sum = 0;
  11. }
  12. /*required*/
  13. public State create() {
  14. /* here could do some init work if needed */
  15. return new State();
  16. }
  17. /*required*/
  18. public void destroy(State state) {
  19. /* here could do some destroy work if needed */
  20. }
  21. /*Not Required*/
  22. public void reset(State state) {
  23. /*if you want this udaf function can work with window function.*/
  24. /*Must impl this, it will be reset to init state after calculate every window frame*/
  25. state.sum = 0;
  26. }
  27. /*required*/
  28. //first argument is State, then other types your input
  29. public void add(State state, Integer val) throws Exception {
  30. /* here doing update work when input data*/
  31. if (val != null) {
  32. state.sum += val;
  33. }
  34. }
  35. /*required*/
  36. public void serialize(State state, DataOutputStream out) {
  37. /* serialize some data into buffer */
  38. try {
  39. out.writeInt(state.sum);
  40. } catch (Exception e) {
  41. /* Do not throw exceptions */
  42. log.info(e.getMessage());
  43. }
  44. }
  45. /*required*/
  46. public void deserialize(State state, DataInputStream in) {
  47. /* deserialize get data from buffer before you put */
  48. int val = 0;
  49. try {
  50. val = in.readInt();
  51. } catch (Exception e) {
  52. /* Do not throw exceptions */
  53. log.info(e.getMessage());
  54. }
  55. state.sum = val;
  56. }
  57. /*required*/
  58. public void merge(State state, State rhs) throws Exception {
  59. /* merge data from state */
  60. state.sum += rhs.sum;
  61. }
  62. /*required*/
  63. //return Type you defined
  64. public Integer getValue(State state) throws Exception {
  65. /* return finally result */
  66. return state.sum;
  67. }
  68. }
  1. CREATE AGGREGATE FUNCTION simple_sum(INT) RETURNS INT PROPERTIES (
  2. "file"="file:///pathTo/java-udaf.jar",
  3. "symbol"="org.apache.doris.udf.demo.SimpleDemo",
  4. "always_nullable"="true",
  5. "type"="JAVA_UDF"
  6. );
  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 for calculating the median*/
  8. public class MedianUDAF {
  9. Logger log = Logger.getLogger("MedianUDAF");
  10. // State storage
  11. public static class State {
  12. // Precision of the result
  13. int scale = 0;
  14. // Whether this is the first time to execute add() for the data under a certain aggregation condition of a certain tablet
  15. boolean isFirst = true;
  16. //Data storage
  17. public StringBuilder stringBuilder;
  18. }
  19. //State initialization
  20. public State create() {
  21. State state = new State();
  22. //Pre-initialize based on the amount of data to be aggregated for each aggregation condition under each tablet, for improved performance
  23. state.stringBuilder = new StringBuilder(1000);
  24. return state;
  25. }
  26. // Handle the data for each unit under each aggregation condition 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 is not guaranteed that there will be no exceptions, it is recommended to maximize the exception capture for each method, as the processing of java-thrown exceptions is currently not supported
  37. log.info("Exception encountered while retrieving data: " + e.getMessage());
  38. }
  39. }
  40. // Output the data after processing for aggregation
  41. public void serialize(State state, DataOutputStream out) {
  42. try {
  43. // Only DataOutputStream is currently provided, if object serialization is required, consider methods such as concatenating strings, converting to json, serializing to byte arrays, etc.
  44. // If you want to serialize the State object, you may need to implement the serialization interface for the inner class State yourself
  45. // In the end, it will be transmitted through DataOutputStream
  46. out.writeUTF(state.stringBuilder.toString());
  47. } catch (Exception e) {
  48. log.info("Exception encountered while serializing data:" + e.getMessage());
  49. }
  50. }
  51. // Retrieve the data output by each data processing 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("Exception encountered while deserializing data: " + e.getMessage());
  60. }
  61. }
  62. // Merge the processing results of data under a certain key according to the aggregation condition, where state1 is the initialized instance for 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("Exception encountered while merging results: " + e.getMessage());
  69. }
  70. }
  71. // Aggregate the data for each key after merging and output the final result
  72. public Double getValue(State state) {
  73. try {
  74. String[] strings = state.stringBuilder.toString( ).split(",");
  75. double[] doubles = new double[strings.length + 1];
  76. doubles = Arrays.stream(strings).mapToDouble(Double::parseDouble).toArray();
  77. Arrays.sort(doubles);
  78. double n = doubles.length - 1;
  79. double index = n * 0.5;
  80. int low = (int) Math.floor(index);
  81. int high = (int) Math.ceil(index);
  82. double value = low == high ? (doubles[low] + doubles[high]) * 0.5 : doubles[high];
  83. BigDecimal decimal = new BigDecimal(value);
  84. return decimal.setScale(state.scale, BigDecimal.ROUND_HALF_UP).doubleValue();
  85. } catch (Exception e) {
  86. log.info("Exception encountered while calculating result:" + e.getMessage());
  87. }
  88. return 0.0;
  89. }
  90. //This method is executed after each processing unit is completed
  91. public void destroy(State state) {
  92. }
  93. }
  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. );
  • The implemented jar package can be stored at local or in a remote server and downloaded via http, And each BE node must be able to obtain the jar package; Otherwise, the error status message “Couldn’t open file…” will be returned

Currently, UDTF are not supported.

Use UDF

Users must have the SELECT permission of the corresponding database to use UDF/UDAF.

The use of UDF is consistent with ordinary function methods. The only difference is that the scope of built-in functions is global, and the scope of UDF is internal to DB. When the link session is inside the data, directly using the UDF name will find the corresponding UDF inside the current DB. Otherwise, the user needs to display the specified UDF database name, such as dbName.funcName.

Delete UDF

When you no longer need UDF functions, you can delete a UDF function by the following command, you can refer to DROP FUNCTION.

Example

Examples of Java UDF are provided in the samples/doris-demo/java-udf-demo/ directory. See the README.md in each directory for details on how to use it, Check it out here

Instructions

  1. Complex data types (HLL, bitmap) are not supported.
  2. Currently, users are allowed to specify the maximum heap size of the JVM themselves. The configuration item is jvm max heap_ size. The configuration item is in the global configuration file ‘be.conf’ under the installation directory of the BE. The default value is 512M. If data aggregation is required, it is recommended to increase the value to improve performance and reduce the risk of memory overflow.
  3. The udf of char type needs to use the String type when creating a function.
  4. Due to the problem that the jvm loads classes with the same name, do not use multiple classes with the same name as udf implementations at the same time. If you want to update the udf of a class with the same name, you need to restart be to reload the classpath.