JavaScript functions¶
What’s in this document?
In addition to supporting internal functions such as NOW(), RAND(), UUID(), and STRUUID(), GraphDB lets you define and execute your own functions using JavaScript.
JavaScript functions are implemented within the special namespace <http://www.ontotext.com/js#>.
Registering JavaScript functions¶
JavaScript functions are initialized by an INSERT DATA request where the subject is a blank node [], <http://www.ontotext.com/js#register> is a reserved predicate, and an object of type literal defines your JavaScript code. You can add multiple function definitions at once.
The following example registers two JavaScript functions — isPalindrome(str) and reverse(str):
prefix extfn:<http://www.ontotext.com/js#>
INSERT DATA {
[] <http://www.ontotext.com/js#register> '''
function isPalindrome(str) {
if (!(str instanceof java.lang.String)) return false;
rev = reverse(str);
return str.equals(rev);
}
function reverse(str) {
return str.split("").reverse().join("");
}
'''
}
This query shows how to retrieve a list of registered JavaScript functions:
PREFIX jsfn:<http://www.ontotext.com/js#>
SELECT ?s ?o {
?s jsfn:enum ?o
}
http://www.ontotext.com/js#enum is a reserved predicate IRI for listing the available JavaScript functions.
The following example registers a single function to return yesterday’s date:
PREFIX jsfn:<http://www.ontotext.com/js#>
INSERT DATA {
[] jsfn:register '''
function getDateYesterday() {
var date = new Date();
date.setDate(date.getDate() - 1);
return date.toJSON().slice(0,10);
}
'''
}
We can then use this function in a regular SPARQL query. The following retrieves data created yesterday:
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX jsfn:<http://www.ontotext.com/js#>
PREFIX pubo: <http://ontology.ontotext.com/publishing#>
SELECT ?s ?date WHERE {
?s pubo:creationDate ?date
FILTER (?date = strdt(jsfn:getDateYesterday(), xsd:date))
}
Note
The projected ?date is filtered by type and dynamically assigned value — xsd:date and the output of the JavaScript function, respectively.
Removing JavaScript functions¶
De-registering a JavaScript function is similar to registering one. The only difference is the predicate used in the INSERT statement: http://www.ontotext.com/js#remove.
PREFIX jsfn:<http://www.ontotext.com/js#>
INSERT DATA {
[] jsfn:remove "getDateYesterday"
}
Once removed, the function should be listed as UNDEFINED:
Note
If multiple function definitions have been registered by a single INSERT, removing one of these functions will remove the rest of the functions added by that insert request.