Adding an OPTIONAL clause to a SPARQL query using Jena ARQ

老子叫甜甜 提交于 2019-12-24 05:41:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!