问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/17594304/adding-an-optional-clause-to-a-sparql-query-using-jena-arq