A user-defined scalar function (UDSF) maps zero, one, or more scalar values to a new scalar value, producing a one-to-one relationship between input rows and output values. Use a UDSF when built-in Flink SQL functions cannot express your custom logic.
For an overview of all user-defined function (UDF) types, see User-defined functions.
How it works
A UDSF extends Apache Flink's ScalarFunction class and implements one or more eval() methods. Flink calls eval() once per input row and uses the return value as the output scalar.
public class SubstringFunction extends ScalarFunction {
public String eval(String s, Integer begin, Integer end) {
return s.substring(begin, end);
}
}
eval() method requirements:
-
Must be declared
public -
Supports method overloading — define multiple
eval()signatures for different input types -
Supports varargs (e.g.,
eval(Integer...)) -
Use boxed primitives (e.g.,
Integerinstead ofint) to handleNULLinputs correctly
Prerequisites
Before you begin, make sure you have:
-
IntelliJ IDEA installed
-
Apache Maven installed
-
Access to a Realtime Compute for Apache Flink workspace
Asynchronous scalar functions (AsyncScalarFunction)
Unlike a regular scalar function, a custom asynchronous scalar function must extend AsyncScalarFunction and return results through a CompletableFuture.
Use an asynchronous scalar function when the function performs operations that involve I/O waits, such as querying an external database or calling an HTTP interface. The function processes multiple records concurrently, which reduces the impact of waiting on job throughput. For operations that do not wait for external services, such as string truncation and numeric computation, a synchronous scalar function is usually sufficient.
Configuration parameters
The following parameters control the runtime behavior of asynchronous scalar functions. Set them before you submit a query or generate an execution plan.
|
Parameter |
Default value |
Description |
|
|
|
The maximum number of concurrent asynchronous operations allowed for each asynchronous operator instance. A larger value increases the concurrency pressure on the external service. |
|
|
|
The timeout period for asynchronously processing a single record, including retries. |
|
|
|
|
|
|
|
The wait time between fixed-interval retries. This parameter takes effect only when the retry strategy is |
|
|
|
The maximum number of retries. This parameter takes effect only when the retry strategy is |
|
|
|
|
Configure unordered output
By default, asynchronous functions run concurrently, but a completed result for a subsequent record is still emitted only after the preceding records are complete. When external request latencies differ significantly and your business tolerates unordered results, enable unordered output to reduce the waiting caused by slow requests.
Asynchronous invocation and unordered output are two independent concepts. By default, an asynchronous scalar function invokes concurrently and emits results in the input order. After you allow unordered output, the system decides whether to enable it based on the change type of the input data.
Add the following configuration before you run the query:
SET 'table.exec.async-scalar.output-mode' = 'ALLOW_UNORDERED';
Example of a custom asynchronous scalar function
The following example queries product names through the HTTP interface of a product service. The function creates and reuses an HttpClient in open, calls sendAsync() in eval to send the request, and returns the result through the completion callback. sendAsync() returns a CompletableFuture, which suits connecting HTTP calls to asynchronous scalar functions. For more information, see JDK HttpClient documentation.
The example uses a 3-second connection timeout and a 5-second request timeout, which suits product name queries with small response bodies. Adjust the values based on the actual response time of your interface.
package com.example.udf;
import org.apache.flink.table.functions.AsyncScalarFunction;
import org.apache.flink.table.functions.FunctionContext;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
/**
* Queries a product name through an asynchronous HTTP interface.
*
* <p>Interface contract: 200 returns a UTF-8 product name, and 404 indicates that the product does not exist.
* This example suits read-only queries that return short text. Other status codes are treated as invocation failures and handed over to the engine.
*/
public class AsyncProductName extends AsyncScalarFunction {
private transient HttpClient client;
private transient URI serviceBaseUri;
@Override
public void open(FunctionContext context) {
String baseUrl = context.getJobParameter("product.service.base-url", null);
if (baseUrl == null || baseUrl.isBlank()) {
throw new IllegalArgumentException("Configure product.service.base-url.");
}
serviceBaseUri = URI.create(baseUrl);
if (!("https".equalsIgnoreCase(serviceBaseUri.getScheme())
|| "http".equalsIgnoreCase(serviceBaseUri.getScheme()))
|| serviceBaseUri.getHost() == null
|| serviceBaseUri.getRawQuery() != null
|| serviceBaseUri.getRawFragment() != null
|| !baseUrl.endsWith("/")) {
throw new IllegalArgumentException("The service URL must be an HTTP(S) base URL that ends with a forward slash (/).");
}
client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(3)).build();
}
@Override
public boolean isDeterministic() {
// Product information may change. The same ID may return different results at different times.
return false;
}
public void eval(CompletableFuture<String> result, Long productId) {
if (productId == null) {
result.complete(null);
return;
}
try {
HttpRequest request =
HttpRequest.newBuilder(
serviceBaseUri.resolve("products/" + productId + "/name"))
.timeout(Duration.ofSeconds(5))
.header("Accept", "text/plain")
.GET()
.build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8))
.thenApply(
response -> {
if (response.statusCode() == 200) {
return response.body();
}
if (response.statusCode() == 404) {
return null;
}
throw new CompletionException(
new IOException(
"Failed to query the product. HTTP status code: " + response.statusCode()));
})
.whenComplete(
(name, error) -> {
if (error != null) {
result.completeExceptionally(error);
} else {
result.complete(name);
}
});
} catch (RuntimeException e) {
result.completeExceptionally(e);
}
}
}
Take note of the following items during development:
-
Call
result.complete(value)to return a result. To return a SQLNULL, callresult.complete(null). -
When a call fails, call
result.completeExceptionally(exception)to return the exception. The engine then handles it based on the retry strategy. -
evalreturns immediately after the request is sent. Pass results through the completion callback ofsendAsync(). Do not call the blockingsend(),get(), orjoin()methods, or perform time-consuming computations inevalor in the callback. -
Each function instance initializes and reuses the client in
opento avoid creating a client for each record. TheHttpClientin JDK 11 and JDK 17 has no publicclose()method, and its internal resources are managed by the JDK. If you use another asynchronous client that provides a close method, release the client in theclosemethod of the function. -
Product information changes over time, so the example sets
isDeterministic()tofalse. When update streams are involved, handle non-deterministic results based on the query semantics.
Develop a UDSF
Flink provides UDF examples that pre-configure the development environment. The examples cover UDSFs, user-defined aggregate functions (UDAFs), and user-defined table-valued functions (UDTFs).
-
Download and decompress the ASI_UDX_Demo example to your local machine. After decompression, the
ASI_UDX-mainfolder is created with the following structure:-
pom.xml: The Maven project configuration file. It defines the project's coordinates, dependencies, build rules, and related metadata. -
\ASI_UDX-main\src\main\java\ASI_UDF\ASI_UDF.java: The sample Java implementation of the UDSF.
ASI_UDX_Demo is hosted on a third-party website. You may experience access failures or delays.
-
-
In IntelliJ IDEA, click File > Open and select the
ASI_UDX-mainfolder. -
Open
\ASI_UDX-main\src\main\java\ASI_UDF\ASI_UDF.javaand update theeval()method with your custom logic. The sample implementation extracts characters from thebeginposition to theendposition of each input string:package ASI_UDF; import org.apache.flink.table.functions.ScalarFunction; public class ASI_UDF extends ScalarFunction { public String eval(String s, Integer begin, Integer end) { return s.substring(begin, end); } } -
Open
\ASI_UDX-main\pom.xmland configure the Maven dependencies for your Flink version. If your UDSF depends on other JAR packages, add the required JAR package dependencies to the pom.xml file. The following example shows the main JAR package dependencies for Flink 1.11. If your UDSF does not depend on additional JAR packages, skip this step.<dependencies> <dependency> <groupId>org.apache.flink</groupId> <artifactId>flink-streaming-java_2.12</artifactId> <version>1.11.0</version> <!--<scope>provided</scope>--> </dependency> <dependency> <groupId>org.apache.flink</groupId> <artifactId>flink-table</artifactId> <version>1.11.0</version> <type>pom</type> <!--<scope>provided</scope>--> </dependency> <dependency> <groupId>org.apache.flink</groupId> <artifactId>flink-core</artifactId> <version>1.11.0</version> </dependency> <dependency> <groupId>org.apache.flink</groupId> <artifactId>flink-table-common</artifactId> <version>1.11.0</version> </dependency> </dependencies> -
In the directory that contains the
pom.xmlfile, run the following command to package the project:mvn package -Dcheckstyle.skipAfter the build completes,
ASI_UDX-1.0-SNAPSHOT.jaris created in the\ASI_UDX-main\target\directory.
Register a UDSF
To register the JAR package as a UDSF, see Manage user-defined functions (UDFs).
Use a UDSF
After registration, call the UDSF in a Flink SQL job.
-
Create a Flink SQL job. For guidance, see Job development map. The following sample SQL extracts characters from the second to the fourth position of the string in the
afield ofASI_UDSF_Sourceand writes the results toASI_UDSF_Sink:CREATE TEMPORARY TABLE ASI_UDSF_Source ( a VARCHAR, b INT, c INT ) WITH ( 'connector' = 'datagen' ); CREATE TEMPORARY TABLE ASI_UDSF_Sink ( a VARCHAR ) WITH ( 'connector' = 'blackhole' ); INSERT INTO ASI_UDSF_Sink SELECT ASI_UDSF(a, 2, 4) FROM ASI_UDSF_Source; -
On the Operation Center > Job O&M page, find your job and click Start in the Actions column. After the job starts, the characters from the second to the fourth position of the
afield in each row ofASI_UDSF_Sourceare inserted intoASI_UDSF_Sink.