使用Jena ARQ向SPARQL查询添加OPTIONAL子句 [英] Adding an OPTIONAL clause to a SPARQL query using Jena ARQ
问题描述
是否可以使用Jena ARQ API以编程方式向SPARQL查询添加OPTIONAL子句? 我想以编程方式接受此查询:
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
对此:
SELECT ?concept ?p ?o ?test WHERE
{
?s ?p ?o
OPTIONAL { ?concept <http://www.test.com/test> ?test }
}
LIMIT 10
通过ARQ,添加其他结果变量?test
很简单:
Through ARQ it's simple to add the additional result variable ?test
:
Query q = QueryFactory.create(query)
query.addResultVar(var);
但是从我在API文档中发现并在网上拖网的内容来看,不可能添加OPTIONAL子句.我需要使用其他库吗?
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?
推荐答案
可以.请参阅apache jena网站上的对本主题的介绍.
Yes you can. See this introduction to the topic on the apache jena site.
您的起点是获取查询模式:
Element pattern = q.getQueryPattern();
如果我没记错的话,那将是ElementGroup
.在其中添加可选内容:
That will be an ElementGroup
if I remember correctly. Add the optional in there:
((ElementGroup) pattern).addElement(new ElementOptional(...));
...
位将是 ElementTriplesBlock ,这非常简单.
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.
这篇关于使用Jena ARQ向SPARQL查询添加OPTIONAL子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!