如何获取Jena查询的所有主题?

假设我有一些jena查询对象:

String query = "SELECT * WHERE{ ?s  ?o ...etc. }"; Query q = QueryFactory.create(query, Syntax.syntaxARQ); 

在查询中获取三元组的所有主题的最佳方法是什么? 优选地,不必手动进行任何字符串解析/操作。

例如,给定一个查询

 SELECT * WHERE { ?s ?p ?o; ?p2 ?o2. ?s2 ?p3 ?o3. ?s3 ?p4 ?o4.  ?p5 ?o5. } 

我希望能够返回一些看起来像的列表

 [?s, ?s2, ?s3, ] 

换句话说,我想要查询中所有主题的列表。 即使只有那些变量或文字/ uris的主题也会有用,但我想在查询中找到所有主题的列表。

我知道有方法可以返回结果变量( Query.getResultVars )和其他一些信息(参见http://jena.apache.org/documentation/javadoc/arq/com/hp/hpl/jena/query/Query.html ),但我似乎找不到任何具体的查询主题(所有结果变量的列表也将返回谓词和对象)。

任何帮助赞赏。

有趣的问题。 你需要做的是完成查询,并为每个三元组迭代并查看第一部分。

最强大的方法是通过元素walker来完成查询的每个部分。 在您的情况下,它可能看起来过于顶部,但查询可以包含各种事物,包括FILTERsOPTIONALs和嵌套SELECTs 。 使用walker意味着您可以忽略这些内容并仅关注您想要的内容:

 Query q = QueryFactory.create(query); // SPARQL 1.1 // Remember distinct subjects in this final Set subjects = new HashSet(); // This will walk through all parts of the query ElementWalker.walk(q.getQueryPattern(), // For each element... new ElementVisitorBase() { // ...when it's a block of triples... public void visit(ElementPathBlock el) { // ...go through all the triples... Iterator triples = el.patternElts(); while (triples.hasNext()) { // ...and grab the subject subjects.add(triples.next().getSubject()); } } } );