JavaScript functions

In addition to internal functions, such as NOW(), RAND(), UUID(), and STRUUID(), GraphDB allows users to define and execute JavaScript code, further enhancing data manipulation with SPARQL. JavaScript functions are implemented within the special namespace <http://www.ontotext.com/js#>.

How to register a JS function

JS 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. It is possible to 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("");
        }
    '''
}

Here is an example of how to retrieve a list of registered JS functions:

PREFIX jsfn:<http://www.ontotext.com/js#>
SELECT ?s ?o {
    ?s jsfn:enum ?o
}
_images/js-functions-enum.png

http://www.ontotext.com/js#enum is a reserved predicate IRI for listing the available JS 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, e.g., to retrieve 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 JS function, respectively.

How to remove a JS function

De-registering a JavaScript function is handled in the same fashion as registering one, with the only difference being 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:

_images/js-functions-remove.png

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.