Create a user-defined function (UDF)
Write custom functions using Java or JavaScript to use in SELECT, INSERT, and UPDATE statements or as a building block for a user-defined aggregate (UDA). Functions are only available within the keyspace where it is defined. To preserve fast performance, use user-defined functions for short computations, and create Java UDFs instead of Javascript UDFs.
You can define functions that are executed against data stored in a table as part of a query result. The function must be created prior to its use in a SELECT statement. The function is performed on each row of the table.
Enable and create a UDF
-
Create a keyspace or use an existing one.
-
In
cassandra.yaml
, enable UDFs, which are disabled by default:-
Java: Set enable_user_defined_functions to
true
. -
JavaScript (in addition to Java): Set enable_scripted_user_defined_functions to
true
.
-
-
Use
CREATE FUNCTION
to create a UDF, specifying the data type of the returned value, the language, and the actual code of the function to be performed.The following function,
fLog()
, computes the logarithmic value of each input. It is a built-injava
function and used to generate linear plots of non-linear data. For this example, it presents a simple math function to show the capabilities of user-defined functions.CREATE OR REPLACE FUNCTION cycling.flog ( input double ) CALLED ON NULL INPUT RETURNS double LANGUAGE java AS $$ return Double.valueOf(Math.log(input.doubleValue())); $$ ;
Results
CREATE FUNCTION cycling.flog(input double) CALLED ON NULL INPUT RETURNS double LANGUAGE java AS $$ return Double.valueOf(Math.log(input.doubleValue())); $$;
Options
-
Actions when the input from the target column is null:
-
CALLED ON NULL INPUT
ensures the function always executes when called. -
RETURNS NULL ON NULL INPUT
ensures the function always returnsNULL
if any of the input arguments areNULL
.
-
-
RETURNS <type>
defines the CQL data type of the value returned by the function. -
OR REPLACE
replaces an existing function with a new function definition. -
IF NOT EXISTS
keywords can be used to create the function only if another function with the same signature doesn’t already exist in the keyspace. If a function with the same signature already exists, the command silently does nothing. IfIF NOT EXISTS
is omitted, then an error is returned if a function with the same name already exists.
OR REPLACE
and IF NOT EXISTS
are mutually exclusive.