下面是我简单的sparql查询。我想更改我的sparql查询uri,但我不知道如何在不使用输入/输出的情况下更改此特定内容。
输入字符串:
PREFIX ab: <http://learningsparql.com/ns/addressbook#>
SELECT ?craigEmail
WHERE
{ ab:craig ab:email ?craigEmail . }
输出字符串:
PREFIX ab: <http://example.com#>
SELECT ?craigEmail
WHERE
{ ab:craig ab:email ?craigEmail . }
请你在jena中为我提供这个简单的代码...
答案 0 :(得分:0)
您可以使用Jena ARQ API并通过迭代SPARQL查询的三元模式元素以编程方式替换前缀ab
的命名空间:
import org.apache.jena.graph.Node;
import org.apache.jena.graph.NodeFactory;
import org.apache.jena.graph.Triple;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.sparql.core.TriplePath;
import org.apache.jena.sparql.syntax.ElementPathBlock;
import org.apache.jena.sparql.syntax.ElementTriplesBlock;
import org.apache.jena.sparql.syntax.ElementVisitorBase;
import org.apache.jena.sparql.syntax.ElementWalker;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Test {
public static void main(String[] args) {
Query query = QueryFactory.create("" +
"PREFIX ab: <http://learningsparql.com/ns/addressbook#> " +
"SELECT ?craigEmail WHERE { ab:craig ab:email ?craigEmail . }");
// This will walk through all parts of the query// This will walk through all parts of the query
final String ns = "http://example.com#";
ElementWalker.walk(query.getQueryPattern(), new ElementVisitorBase() { // ...when it's a block of triples...
public void visit(ElementPathBlock el){ // ...go through all the triples...
Iterator<TriplePath> triples = el.patternElts();
List<Triple> newTriples = new ArrayList<>();
while (triples.hasNext()) {
TriplePath triple = triples.next();
if(triple.isTriple()) {
Node s = triple.getSubject();
if(s.isURI()) {
String localName = s.getLocalName();
s = NodeFactory.createURI(ns + localName);
}
Node p = triple.getPredicate();
if(p.isURI()) {
String localName = p.getLocalName();
p = NodeFactory.createURI(ns + localName);
}
Node o = triple.getSubject();
if(o.isURI()) {
String localName = o.getLocalName();
o = NodeFactory.createURI(ns + localName);
}
newTriples.add(Triple.create(s, p, o));
} else {
// TODO handle triple path
}
triples.remove();
}
for(Triple t : newTriples) {
el.addTriple(t);
}
}
@Override
public void visit(ElementTriplesBlock el) {
Iterator<Triple> triples = el.patternElts();
List<Triple> newTriples = new ArrayList<>();
while (triples.hasNext()) {
Triple triple = triples.next();
Node s = triple.getSubject();
if(s.isURI()) {
String localName = s.getLocalName();
s = NodeFactory.createURI(ns + localName);
}
Node p = triple.getPredicate();
if(p.isURI()) {
String localName = p.getLocalName();
p = NodeFactory.createURI(ns + localName);
}
Node o = triple.getSubject();
if(o.isURI()) {
String localName = o.getLocalName();
o = NodeFactory.createURI(ns + localName);
}
newTriples.add(Triple.create(s, p, o));
triples.remove();
}
for(Triple t : newTriples) {
el.addTriple(t);
}
}
});
query.setPrefix("ab", ns);
System.out.println(query);
}
}