Warm tip: This article is reproduced from serverfault.com, please click

Custom functions in a SPARQL BIND expression in JENA

发布于 2021-01-06 16:05:40

I want to use custom functions in BIND expressions in Jena, but it does not work.

To take a small example, I have an Owl ontology with one Human class, having the following int data properties:

  • Age
  • BirthDate

My query is the following:

prefix human: <http://www.semanticweb.org/scdsahv/ontologies/2021/0/human#>
prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
prefix xsd: <http://www.w3.org/2001/XMLSchema#>
prefix fn: <http://www.w3.org/2005/xpath-functions#>
prefix owl: <http://www.w3.org/2002/07/owl#>
prefix da: <http://www.my.namespace/test>
SELECT ?elt ?value
WHERE {
?elt rdf:type human:Human .
?elt human:Age ?age .
?elt human:BirthDate ?birthDate .
BIND (da:testFunction(?age, ?birthDate) as ?value)
}

I used the Jena documentation about filter functions here

So I created a custom factory:

public class MyFactory implements FunctionFactory {
   @Override
   public Function create(String fctName) {
      return new testFunction();
   }
}

With the following code for the function:

public class testFunction extends FunctionBase2 {
   public testFunction() {
      super();
   }
   
   @Override
   public NodeValue exec(NodeValue nv, NodeValue nv1) {
      float f1 = nv.getFloat();
      float f2 = nv1.getFloat();
      float f = f1 + f2;
      return NodeValue.makeFloat(f);
   }
}

And I registered the factory:

MyFactory theFactory = new MyFactory();
FunctionRegistry.get().put("http://www.my.namespace/test#testFunction", theFactory);

I don't have any exception when I execute the query in Jena, but each result only contains the ?elt element, not the ?value. In the debugger, I see that no testFunction instance is ever created. What did I do wrong?

Of course if I use the same BIND expression but with a simpler expression such has:

BIND (?age as ?value)

I have the ?value in the results.

Questioner
Hervé Girod
Viewed
0
Hervé Girod 2021-01-07 00:11:33

My mistake was:

prefix da: <http://www.my.namespace/test>

But it should have been:

prefix da: <http://www.my.namespace/test#>