问题
is there any way to generate a SPARQL query in a dynamic way? what I'm trying to do is some thing like this: if I have a DBpedia resource r1 and another DBpedia resource r2, this query
SELECT * WHERE { <r1> ?pre <r2> }
will return the predicate between the 2 resources and this query
SELECT * WHERE { <r1> ?pre1 ?obj1 . ?obj1 ?pre2 <r2> }
will return all the predicates and object between these two resources ( in two steps) and so on I'm trying to build this query in such a way that it will automatically increase the number of objects and predicates between the two resources (for example in 4 steps)?
回答1:
I figure out how to solve this problem.. here is my solution:
private String completeQuery(String coreQuery){
String completeQuery = "";
completeQuery += "SELECT * WHERE {"+ "\n";
completeQuery += coreQuery + "\n";
completeQuery =completeQuery + "}" + "\n" +"limit 5" ;
return completeQuery;}
public String link(String object1, String object2, int distance){
if(distance == 1){
String Quer = "<http://dbpedia.org/resource/"+object1+">" + " ?pre1 " +"<http://dbpedia.org/resource/"+object2+">";
return completeQuery(Quer);
}
else {
String query = "<http://dbpedia.org/resource/"+object1+">" + " ?pre1 ?obj1 " + ".\n";
for(int i = 1; i < distance-1; i++){
query += "?obj" + i + " ?pre" + (i+1) + " ?obj" + (i+1) + ".\n" ;
}
query += "?obj" + (distance-1) + " ?pre" + distance + " " + "<http://dbpedia.org/resource/"+object2+">";
return completeQuery(query);
}}
来源:https://stackoverflow.com/questions/25692646/generate-an-incremental-sparql-query