-->

如何获得全部耶拿查询的科目?(How to get all of the subjects of a

2019-08-17 06:56发布

假设我有一些耶拿查询对象:

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

什么是让所有在查询中三元的主题的最佳方式? 优选地,而不必手动做任何字符串解析/处理。

例如,给定一个查询

SELECT * WHERE {
    ?s ?p ?o;
       ?p2 ?o2.
    ?s2 ?p3 ?o3.
    ?s3 ?p4 ?o4.
    <http://example.com> ?p5 ?o5.
}

我希望已经恢复了一些列表,它看起来像

[?s, ?s2, ?s3, <http://example.com>]

换句话说,我想在一个查询中的所有对象的列表。 甚至有只在那些它是文字/ URI的将是有益的变量或那些题材,但我想找到的所有查询对象的列表。

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

任何帮助表示赞赏。

Answer 1:

有趣的问题。 你需要做的是经过查询,并为三元的每个块遍历,并期待在第一部分。

最可靠的方法来做到这一点是通过一个元素学步车,将经过查询的每个部分。 这似乎在你的情况顶部,但查询可以包含各种各样的事情,包括FILTERsOPTIONALs和嵌套SELECTs 。 使用学步车意味着你可以忽略的东西,专注于你想要什么只:

Query q = QueryFactory.create(query); // SPARQL 1.1

// Remember distinct subjects in this
final Set<Node> subjects = new HashSet<Node>();

// 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<TriplePath> triples = el.patternElts();
            while (triples.hasNext()) {
                // ...and grab the subject
                subjects.add(triples.next().getSubject());
            }
        }
    }
);


文章来源: How to get all of the subjects of a Jena Query?