Reputation: 71
Below is the sparql query to get places in united state, When I run this code on virtuoaso SPARQL I get the required output. But when I write this code in java its not giving the output.
select (str(?label) as ?strLabel) where {
?place a dbpedia-owl:PopulatedPlace ;
dbpedia-owl:country dbpedia:United_States ;
rdfs:label ?label
filter langMatches( lang(?label), 'en' )`
}
limit 100
To my knowledge I wrote it but its not giving any result.
public class TestDbpedia {
public static void main(String[] args) {
String sparqlQueryString = " select (str(?label) as ?strLabel) "+
"where {"+
"?place a dbpedia-owl:PopulatedPlace ;"+
"dbpedia-owl:country dbpedia:United_States ;"+
"rdfs:label ?label"+
"filter langMatches( lang(?label), 'en' )"+
"limit 10"+
"}";
Query query = QueryFactory.create(sparqlQueryString);
QueryExecution qexec = QueryExecutionFactory.sparqlService("http://dbpedia.org/sparql", query);
try {
ResultSet results = qexec.execSelect();
for ( ; results.hasNext() ; )
{
QuerySolution soln = results.nextSolution() ;
System.out.println(soln.get("?strLabel"));
}
}
catch(Exception e){
e.printStackTrace();
}
finally { qexec.close(); }
}
}
Upvotes: 0
Views: 1326
Reputation: 85813
One, you need to include the necessary prefixes in your SPARQL query. That is, you'll need to write
prefix dbpedia-owl: <http://dbpedia.org/ontology/>
and the rest at the beginning of your query. The predefined prefixes only get applied to queries you make with the browser-based web interface, as far as I know.
When you're constructing queries from strings, you need to be very careful with newlines and spaces and the like. For instance, the Java lines
"rdfs:label ?label"+
"filter langMatches( lang(?label), 'en' )"+
end up giving you a query string containing
rdfs:label ?labelfilter langMatches( lang(?label), 'en' )
You end up with an invalid query. Add some spaces or newlines to your strings.
Your query doesn't end correctly. You have
"filter langMatches( lang(?label), 'en' )"+
"limit 10"+
"}";
which will give you (once you add some newlines and spaces):
filter …
limit 10
}
That's not the right syntax. You need to have
filter …
}
limit 10
I'm surprised that DBpedia didn't give you a more useful error message (or maybe it did; you didn't show us the stacktrace, after all). You can test your queries at sparql.org's query validator, too. Also, if you used one of Jena's ParameterizedSparqlStrings, you could have parsed the query beforehand, which should have caught the syntax error.
Upvotes: 3