Using JavaScript to define SPIN/SPARQL Functions

DEPRECATED: As of TopBraid 6.1 we no longer recommend using this feature. Its functionality has been replaced with an equivalent SHACL-JS implementation.

SPIN provides various mechanisms to define new SPARQL functions. In addition to the user-defined functions that wrap other SPARQL queries (as described in Understanding SPIN Functions), it is also possible to define new SPARQL function using JavaScript. When executed, these BIND/FILTER functions will call JavaScript code that may use any of the constructs provided by that rich iterative programming language.

In order to use JavaScript-based functions, you need to import the SPINx namespace http://spinrdf.org/spinx. This is part of the standard system ontologies of TopBraid. Once you have imported this, you should see the properties spinx:javaScriptFile and spinx:javaScriptCode.

Here is one mechanism to define your functions using an external .js file:

  1. Create a new JavaScript file such as myFunctions.js
  2. Edit this file to define your functions (e.g., function square(x) { return x * x; }).
  3. Create a SPIN file in the same folder, importing spinx
  4. Create a subclass of spin:Functions, e.g. called my:square
  5. In the subclass, define the arguments like for any other SPIN function
  6. Also specify a spin:returnType such as xsd:integer or rdfs:Resource
  7. Leave the spin:body empty
  8. Enter the name of the .js file as spinx:javaScriptFile, e.g. myFunctions.js
  9. You can now test the function in the SPARQL window, e.g. BIND (my:square(3) AS ?x)

Another mechanism can be used to define functions inline:

  1. Create a new SPIN file, importing spinx
  2. Create a subclass of spin:Functions, e.g. called my:square
  3. In the subclass, define the arguments like for any other SPIN function
  4. Also specify a spin:returnType such as xsd:integer or rdfs:Resource
  5. Leave the spin:body empty
  6. Enter the code to execute as spinx:javaScriptCode, e.g. return arg1 * arg1;
  7. You can now test the function in the SPARQL window, e.g. BIND (my:square(3) AS ?x)

More information on this capability, including an example, can be found on the official SPINx web page.