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.
Prerequisites
By default, the ability to add user-defined functions is disabled.
To enable, change the following settings in the cassandra.yaml
file:
-
Java: Set enable_user_defined_functions to
true
. -
JavaScript (in addition to Java): Set enable_scripted_user_defined_functions to
true
.
Create a function, 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-in java
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
WARNING: cqlsh was built against 5.0-beta1, but this server is 5.0. All features may not work!
CREATE FUNCTION cycling.flog(input double)
CALLED ON NULL INPUT
RETURNS double
LANGUAGE java
AS $$ return Double.valueOf(Math.log(input.doubleValue())); $$;
|
See also: