How do I create custom functions in Cassandra with a custom Java class?
I couldn't find this anywhere on the internet. How do I create a custom user defined function in cassandra ?.
For Ex:
CREATE OR REPLACE FUNCTION customfunc(custommap map<text, int>)
CALLED ON NULL INPUT
RETURNS map<int,bigint>
LANGUAGE java AS 'return MyClass.mymethod(custommap);';
Where is "MyClass" a class that I can register with the Classpath?
source to share
Just adding my 2 cents to this thread as I tried to create an outer class method to support something like this. After hours of working with Datastax Sandbox 5.1, I couldn't get this to work as it couldn't find my class and was constantly raising type errors.
My guess is that external JAR for UDF is not supported (see http://koff.io/posts/hll-in-cassandra/ and https://issues.apache.org/jira/browse/CASSANDRA-9892 ) ... Support for TRUSTED JARs is in the planning stages for Cassandra 4. It may work in earlier versions up to 3.0, but I am using the latest version of Datastax.
To work around this problem, I had to abandon the Javascript version (I was trying to convert a JSON string to a Map object).
While I understand that Java UDFs perform better, the code I tested used Nashorn's javascript support anyway, so using Javascript might not be all that bad. The result is a simpler one-liner UDF.
source to share
1. First, create a java project that contains your class. Remember you need to add the package name to your class.
Example:
package exp;
import java.lang.Math;
import java.util.*;
public class MyClass
{
public static Map<Integer,Long> mymethod(Map<String, Integer> data) {
Map<Integer,Long> map = new HashMap<>();
map.put(1, 10L);
map.put(2, 20L);
map.put(3, 30L);
return map;
}
}
After compiling and building, I have a jar test.jar
2. Copy the jar file to all cassandra node $CASSANDRA_HOME/lib
directories
3. Restart all Cassandra Nodes
4. Create your own function
Example:
CREATE OR REPLACE FUNCTION customfunc(custommap map<text, int>)
CALLED ON NULL INPUT
RETURNS map<int,bigint>
LANGUAGE java
AS 'return exp.MyClass.mymethod(custommap);';
Now you can use the function:
cassandra@cqlsh:test> SELECT * FROM test_fun ;
id | data
----+------------------
1 | {'a': 1, 'b': 2}
(1 rows)
cassandra@cqlsh:test> SELECT customfunc(data) FROM test_fun ;
test.customfunc(data)
-----------------------
{1: 10, 2: 20, 3: 30}
(1 rows)
source to share