Search code examples
javasparqlrdfjenaarq

How to set a property path in Jena's Sparql API?


I would like to avoid passing SPARQL queries around as Strings. Therefore I use Jena's API for creating my queries. Now I need a PropertyPath in my query, but I can't find any Java class supporting this. Can you give me a hint?

Here's some example code where I would like to insert this (Jena 3.0.1):

private Query buildQuery(final String propertyPath) {
    ElementTriplesBlock triplesBlock = new ElementTriplesBlock();
    triplesBlock.addTriple(
            new Triple(NodeFactory.createURI(this.titleUri.toString()),
                    //How can I set a property path as predicate here?
                    NodeFactory.???,
                    NodeFactory.createVariable("o"))
    );
    final Query query = buildSelectQuery(triplesBlock);
    return query;
}

private Query buildSelectQuery(final ElementTriplesBlock queryBlock) {
    final Query query = new Query();
    query.setQuerySelectType();
    query.setQueryResultStar(true);
    query.setDistinct(true);
    query.setQueryPattern(queryBlock);
    return query;
}

Solution

  • You can use PathFactory to create property paths

    Consider the graph below:

    @prefix dc: <http://purl.org/dc/elements/1.1/>.
    @prefix ex: <http://example.com/>.
    
        ex:Manager ex:homeOffice ex:HomeOffice
        ex:HomeOffice dc:title "Home Office Title"
    

    Suppose you want to create a pattern like:

    ?x ex:homeOffice/dc:title ?title
    

    The code below achieves it:

     //create the path
    Path exhomeOffice = PathFactory.pathLink(NodeFactory.createURI("http://example.com/homeOffice"));
     Path dcTitle = PathFactory.pathLink(NodeFactory.createURI("http://purl.org/dc/elements/1.1/title"));
    Path fullPath = PathFactory.pathSeq(exhomeOffice,dcTitle);
    TriplePath t = new TriplePath(Var.alloc("x"),fullPath,Var.alloc("title"));