Search code examples
sparqlrdf4j

Are typed literals "tricky" in RDF4J?


In RDF, I can have an entity that is bound by a single property to multiple literal values. Those values can also be typed to add clarity.

:dumpTruck :weight "heavy"^^xsd:string .
:dumpTruck :weight "36000"^^xsd:integer .

In SPARQL, I can query for just they type I want

SELECT  ?w
WHERE
  { :dumpTruck  :weight  ?w
    FILTER ( datatype(?w) = xsd:integer )
  }

Is there something like getStatement in RDF4J that can be constrained by datatype like that?


Solution

  • There's no a priori constraint possible, but you can post-process your result to filter on the datatype. For example you could use something along these lines (untested but you get the drift hopefully):

    QueryResults.stream(conn.getStatements(dumptruck, weight, null))
                .filter(s -> ((Literal)s.getObject()).getDatatype().equals(XMLSchema.INTEGER))
                .collect(Collectors.toList());
    

    Or alternatively, stick in a Model first and then filter:

    Model m = QueryResults.asModel(conn.getStatements(dumptruck, weight, null));
    List intValues = Models.objectLiterals(m).stream().filter(l -> l.getDatatype().equals(XMLSchema.INTEGER)).collect(Collectors.toList()); 
    

    I'm sure there's a couple of other/handier shortcuts available that I haven't thought of. The RDF4J docs have tutorials and examples to spare, however.