[英]How to get all of the subjects of a Jena Query?
假設我有一些 jena 查詢對象:
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 ),但我似乎找不到任何可以具體獲取查詢主題的內容(所有結果變量的列表也將返回謂詞和對象)。
任何幫助表示贊賞。
有趣的問題。 您需要做的是通過查詢,並為每個三元組塊迭代並查看第一部分。
最健壯的方法是通過一個元素遍歷器,它會遍歷查詢的每個部分。 在您的情況下,它可能看起來過於重要,但查詢可以包含各種內容,包括FILTERs
、 OPTIONALs
和嵌套的SELECTs
。 使用 walker 意味着你可以忽略那些東西,只關注你想要的東西:
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());
}
}
}
);
可能為時已晚,但另一種方法是利用 Jena ARQ 庫並創建給定查詢的代數。 一旦創建了代數,就可以對其進行編譯,並且可以遍歷所有三元組(在 where 子句中給出)。 這是代碼,我希望它有幫助:
Query query = qExec.getQuery(); //qExec is an object of QueryExecutionFactory
// Generate algebra of the query
Op op = Algebra.compile(query);
CustomOpVisitorBase opVisitorBase = new CustomOpVisitorBase();
opVisitorBase.opVisitorWalker(op);
List<Triple> queryTriples = opVisitorBase.triples;
CustomOpVisitor 類如下所示:
public class CustomOpVisitorBase extends OpVisitorBase {
List<Triple> triples = null;
void opVisitorWalker(Op op) {
OpWalker.walk(op, this);
}
@Override
public void visit(final OpBGP opBGP) {
triples = opBGP.getPattern().getList();
}
}
遍歷三元組列表並使用給定的屬性函數,如triple.getSubject() 等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.