Anthony Hughes
Anthony Hughes

Reputation: 586

Adding an OPTIONAL clause to a SPARQL query using Jena ARQ

Is it possible to programmatically add an OPTIONAL clause to a SPARQL query using the Jena ARQ API? I would like to programmatically take this query:

select ?concept ?p ?o where {?s ?p ?o . } limit 10

To this:

SELECT  ?concept ?p ?o ?test WHERE
{ 
 ?s ?p ?o
 OPTIONAL { ?concept <http://www.test.com/test> ?test }
}
LIMIT   10

Through ARQ it's simple to add the additional result variable ?test:

Query q = QueryFactory.create(query)    
query.addResultVar(var);

But from what I've found in the API docs and trawling across the net it's not possible to add an OPTIONAL clause. Do I need to use a different library?

Upvotes: 2

Views: 592

Answers (1)

user205512
user205512

Reputation: 8888

Yes you can. See this introduction to the topic on the apache jena site.

Your starting point is getting the query pattern:

Element pattern = q.getQueryPattern();

That will be an ElementGroup if I remember correctly. Add the optional in there:

((ElementGroup) pattern).addElement(new ElementOptional(...));

The ... bit will be an ElementTriplesBlock, which is pretty straightforward.

Inelegant, however. In general I'd recommend using visitors and the algebra representation, but this direct route should work.

Upvotes: 2

Related Questions