Suppose I have some jena query object :
String query = "SELECT * WHERE{ ?s <some_uri> ?o ...etc. }";
Query q = QueryFactory.create(query, Syntax.syntaxARQ);
I would like to use an ElementWalker and add triples to the query like so:
Given a query
SELECT * WHERE {
?s ?p ?o;
?p2 ?o2.
?s2 ?p3 ?o3.
}
I would hope to add a triple s.t. the query looks something like:
SELECT * WHERE {
?s ?p ?o;
?p2 ?o2.
-->?s <some_url> "value". //added
?s2 ?p3 ?o3.
}
I know that there are ways to add to the top level (Jena Tutorial), but I'd like to somehow add the triples as I walk through them using an ElementWalker:
ElementWalker.walk(query.getQueryPattern(), new ElementVisitorBase(){
public void visit(ElementPathBlock el) {
// when it's a block of triples, add in some triple
ElementPathBlock elCopy = new ElementPathBlock();
Iterator<TriplePath> triples = el.patternElts();
int index = 0;
int numAdded = 0;
while (triples.hasNext()) {
TriplePath t = triples.next();
if(t.getSubject().equals(/*something*/)){
//add triple here, something like:
elCopy.addTriple(index+numAdded, /*someTriple*/);
numAdded++;
}
index++;
}
el = elCopy;
}
public void visit(ElementSubQuery el) {
// get the subquery and walk it
ElementGroup subQP = (ElementGroup) el.getQuery().getQueryPattern();
ElementWalker.walk(subQP, this);
}
public void visit(ElementOptional el) {
// get optional elements and walk them
Element optionalQP = el.getOptionalElement();
ElementWalker.walk(optionalQP, this);
}
});
The problem with the code above is that it successfully adds the triple to the ElementPathBlock (el
), but the change doesn't perpetuate up through to the query itself. My hope would be to successfully modify the query while visiting this specific ElementPathBlock inside of the query.
Any help appreciated.