How to get all Jena Query items?
Suppose I have some jena request object:
String query = "SELECT * WHERE{ ?s <some_uri> ?o ...etc. }"; Query q = QueryFactory.create(query, Syntax.syntaxARQ); What would be the best way to get all items from triples in a query? Preferably, without the need for manual parsing / manipulation.
For example, given the request
SELECT * WHERE { ?s ?p ?o; ?p2 ?o2. ?s2 ?p3 ?o3. ?s3 ?p4 ?o4. <http://example.com> ?p5 ?o5. } I would hope to return a list that looks like
[?s, ?s2, ?s3, <http://example.com>] In other words, I need a list of all the topics in the request. Even having only those subjects that were variables, or those that were literals / uris, would be useful, but I would like to find a list of all the subjects in the query.
I know that there are methods for returning result variables ( Query.getResultVars ) and some other information (see http://jena.apache.org/documentation/javadoc/arq/com/hp/hpl/jena/query/Query. html ), but I can't seem to find anything that will be specifically designed for query objects (a list of all result variables will also return predicates and objects).
Any help was appreciated.
Interest Ask. What you need to do is go through the request, and for each block of triples, go through the first part. Look at the first part.
The most reliable way to do this is through an elemental walker that will go through each part of the request. In your case, this may appear from above, but queries can contain all kinds of things, including FILTERs , OPTIONALs and nested SELECTs . Using a walker means that you can ignore this stuff and focus only on what you want:
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 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()); } } } );