How jena SPARQL results in RDF XML format rather than triple - sparql

I wrote SPARQL in String queryString
"SELECT DISTINCT ?dog ?p ?o " +
"WHERE {" +
"?dog <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://test#dog>. " +
"?dog ?p ?o. " +
"}";
...
while (rs_s.hasNext()) {
QuerySolution qs = rs_s.next();
String s1 = qs.get("dog").toString();
String s2 = qs.get("p").toString();
String s3 = qs.get("o").toString();
As a result, I got a triple format.
How do I get it with RDF XML?

Related

Jena SPARQL Query Execution stuck

I am running the Virtuoso SPARQL endpoint for executing the query. but while I am executing the query my execution stuck.
QueryExecution qexec = null;
try {
System.out.println("now inside");
String queryString = "PREFIX ns: <http://example.org/ns#>" +
"PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\r\n" +
"SELECT ?title ?price" +
" {" +
" ?x ns:price ?p ." +
" ?x ns:discount ?discount ." +
" ?x <http://purl.org/dc/elements/1.1/title> ?title . " +
" BIND ('12'^^xsd:integer AS ?price)" +
" FILTER( ?price < 20 )" +
" }";
System.out.println(queryString);
System.out.println("inside the sparql just before call");
qexec = QueryExecutionFactory.sparqlService("http://192.168.99.100:8890/sparql", queryString);
ResultSet results = qexec.execSelect();
System.out.println("inside the sparql just after call");
// write to a ByteArrayOutputStream
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ResultSetFormatter.outputAsJSON(outputStream, results);
String json = outputStream.toString();
System.out.println(json);
return json;
} catch (Exception e) {
e.printStackTrace();
}finally {
qexec.close();
}
return "Error";
sample data
#prefix dc: <http://purl.org/dc/elements/1.1/> .
#prefix : <http://example.org/book/> .
#prefix ns: <http://example.org/ns#> .
:book1 dc:title "SPARQL Tutorial" .
:book1 ns:price 42 .
:book1 ns:discount 0.2 .
:book2 dc:title "The Semantic Web" .
:book2 ns:price 23 .
:book2 ns:discount 0.25 .
While executing qexec.execSelect() it shouldn't give any error nor output result. But it will happen occasionally.
As while tracing it will print all the details up to below statement
System.out.println("inside the sparql just before call");
but not after that.
How do I trace it? How do I figure out what causes the issue?
Note: My query is very small so there is no time issue.
Also, I notice that after updating the new updated version of Jena 3.7.0 I am getting this issue
If I read the comments correctly, I think that the issue was resolved by changing --
qexec = QueryExecutionFactory.sparqlService("http://192.168.99.100:8890/sparql", queryString);
-- to --
QueryEngineHTTP qexec = new QueryEngineHTTP ("http://192.168.99.100:8890/sparql", queryString);
-- which is a workaround that doesn't reveal the cause of the original problem, but nonetheless got past it successfully.

DBpedia query giving me error when using jena

When i run this query on dbpedia.org
SELECT DISTINCT ?resource ?label ?location
WHERE
{
<http://dbpedia.org/resource/New_York_City> geo:geometry ?sourcegeo .
?resource geo:geometry ?location ;
rdfs:label ?label .
FILTER( bif:st_intersects( ?location, ?sourcegeo, 20 ) ) .
FILTER( lang( ?label ) = "en" )
}
it is producing results fine but same query gives me error when using java jena api.
String s2 = "SELECT DISTINCT ?resource ?label ?location \r\n" +
"WHERE \r\n" +
" { \r\n" +
" <http://dbpedia.org/resource/New_York_City> geo:geometry ?sourcegeo . \r\n" +
" ?resource geo:geometry ?location ; \r\n" +
" rdfs:label ?label . \r\n" +
" FILTER( bif:st_intersects( ?location, ?sourcegeo, 20 ) ) . \r\n" +
" FILTER( lang( ?label ) = \"en\" ) \r\n" +
" }\r\n" +
"";
Query query = QueryFactory.create(s2); //s2 = the query above
QueryExecution qExe = QueryExecutionFactory.sparqlService( "http://dbpedia.org/sparql", query );
ResultSet results = qExe.execSelect();
ResultSetFormatter.out(System.out, results, query) ;
it gives me the following errors
Exception in thread "main" org.apache.jena.query.QueryParseException: Line 4, column 49: Unresolved prefixed name: geo:geometry
at org.apache.jena.sparql.lang.ParserBase.throwParseException(ParserBase.java:521)
at org.apache.jena.sparql.lang.ParserBase.resolvePName(ParserBase.java:286)
at org.apache.jena.sparql.lang.sparql_11.SPARQLParser11.PrefixedName(SPARQLParser11.java:4857)
at org.apache.jena.sparql.lang.sparql_11.SPARQLParser11.iri(SPARQLParser11.java:4841) and it goes on
DBPedia has a number of Predefined Namespace Prefixes, which includes
PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>,
which Jena does not have. Hence you have to specify it for use Jena before your SELECT. I.e.
String s2 = "PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>\r\n" +
"SELECT DISTINCT ?resource ?label ?location \r\n" +
... etc

Make a query in SPARQL with DataType Property

I'm working with an ontology OWL and making a query about it.
My query is:
"PREFIX a: http://www.owl-ontologies.com/Indoor.owl# "
+ "SELECT ?X "
+ "WHERE { ?X a:hasDay a:" + day + " . "
+ " ?X a:hasRoom a:" + room + " . "
+ " ?X a:hasStartTime a:" + startTime +" }";
At the moment to make the query, the console of NetBeans throw me:
Undefined object property used in query: http://www.owl-ontologies.com/Indoor.owl#hasStartTime
But hasStartTime in the ontology isn't an object property, it is a data type (int).
Assuming that the value of the Java variable startTime is e.g. 420 (7am), if you look at your SPARQL query, the last triple pattern is made by
?X a:hasStartTime a: plus value of ``startTime,
i.e. it results in
?X a:hasStartTime a:420
RDF literals have to be put in quotes without a prefix - it's a literal and not a prefixed URI, e.g.
?X a:hasStartTime 420
or to make the datatype more explicit (for integer values the above is just a shortcut)
?X a:hasStartTime "420"^^<http://www.w3.org/2001/XMLSchema#integer>

German DBpedia endpoint in HTTP Sparql Queries returns no result

I am using the Jena Java framework for querying DBpedia end point using SPARQL, to get the type for all points of interest in German cities. I am facing no issue for places that have English DBpedia entries. But, when it comes to place names to be queried from the German DBpedia endpoint (http://de.dbpedia.org/resource/Schloß_Nymphenburg), this query returns no result. This problem is also mentioned over here (http://mail-archives.apache.org/mod_mbox/jena-users/201110.mbox/%3C4E877C8A.4050705#apache.org%3E). Even after referring to this, I am unable to solve the problem. I don't know how to work with QueryEngineHTTP. I am adding two code snippets - one that works (first one - query for Allianz Arena : which has an English entry in DBpedia) and one that doesn't work (second one - for Schloß Nymphenburg, that has a German entry).
This might be a very trivial issue, but I am unable to solve it. Any pointers to a solution would be very very helpful.
Thanks a lot!
Code 1 - working :
String service = "http://dbpedia.org/sparql";
final ParameterizedSparqlString query = new ParameterizedSparqlString(
"PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>" +
"PREFIX dbo: <http://dbpedia.org/ontology/>" +
"PREFIX dcterms: <http://purl.org/dc/terms/>" +
"SELECT * WHERE {" +
"?s geo:lat ?lat ." +
"?s geo:long ?long ." +
"?s dcterms:subject ?sub}");
query.setIri("?s", "http://dbpedia.org/resource/Allianz_Arena");
QueryExecution qe = QueryExecutionFactory.sparqlService(service, query.toString());
ResultSet results = qe.execSelect();
ResultSetFormatter.out(System.out, results);
Code 2 - not working :
String service = "http://dbpedia.org/sparql";
final ParameterizedSparqlString query = new ParameterizedSparqlString(
"PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>" +
"PREFIX dbo: <http://dbpedia.org/ontology/>" +
"PREFIX dcterms: <http://purl.org/dc/terms/>" +
"SELECT * WHERE {" +
"?s geo:lat ?lat ." +
"?s geo:long ?long ." +
"?s dcterms:subject ?sub}");
query.setIri("?s", "http://de.dbpedia.org/resource/Schloß_Nymphenburg");
QueryExecution qe = QueryExecutionFactory.sparqlService(service, query.toString());
ResultSet results = qe.execSelect();
ResultSetFormatter.out(System.out, results);
I don't think this is an issue with jena at all. Trying:
SELECT * WHERE {
<http://de.dbpedia.org/resource/Schloß_Nymphenburg> ?p ?o }
at http://dbpedia.org/sparql I get no results: try it yourself.
SELECT * WHERE {
<http://de.dbpedia.org/resource/Schloss_Nymphenburg> ?p ?o }
by contrast returns something, even if it's just a bunch of cross links.

get latitude and longitude of a place dbpedia

I want to get the latitude and longitude of a place whose name I already know by
PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>
PREFIX dbo: <http://dbpedia.org/ontology/>
SELECT * WHERE {
?s a dbo:Place .
?s geo:lat ?lat .
?s geo:long ?long .
}
where the name of the place (?s) is something like Graves Park.
How would one go about implementing the same in Jena where the name of the place might vary?
You can use Jena's ARQ to execute queries against remote SPARQL endpoints. The process is described in ARQ — Querying Remote SPARQL Services.
Using ParameterizedSparqlStrings in SELECT queries
To do this for different places that you might not know until it is time to execute the query, you can use a ParameterizedSparqlString to hold the query and then inject the value(s) once you have them. Here's an example. The query is the one you provided. I put it into a ParameterizedSparqlString, and then used setIri to set ?s to http://dbpedia.org/resource/Mount_Monadnock.
import com.hp.hpl.jena.query.ParameterizedSparqlString;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFormatter;
public class DBPediaQuery {
public static void main( String[] args ) {
final String dbpedia = "http://dbpedia.org/sparql";
final ParameterizedSparqlString queryString
= new ParameterizedSparqlString(
"PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>"+
"PREFIX dbo: <http://dbpedia.org/ontology/>" +
"SELECT * WHERE {" +
" ?s a dbo:Place ." +
" ?s geo:lat ?lat ." +
" ?s geo:long ?long ." +
"}" );
queryString.setIri( "?s", "http://dbpedia.org/resource/Mount_Monadnock");
QueryExecution exec = QueryExecutionFactory.sparqlService( dbpedia, queryString.toString() );
ResultSet results = exec.execSelect();
ResultSetFormatter.out( System.out, results );
}
}
The results printed by this are:
--------------------------------------------------------------------------------------------------------------
| lat | long |
==============================================================================================================
| "42.8608"^^<http://www.w3.org/2001/XMLSchema#float> | "-72.1081"^^<http://www.w3.org/2001/XMLSchema#float> |
--------------------------------------------------------------------------------------------------------------
Once you have the ResultSet, you can iterate through the rows of the solution and extract the values. The values here are Literals, and from a Literal you can extract the lexical form (the string value), or the value as the corresponding Java type (in the case of numbers, strings, booleans, &c.). You could do the the following to print the latitude and longitude instead of using the ResultSetFormatter:
while ( results.hasNext() ) {
QuerySolution solution = results.next();
Literal latitude = solution.getLiteral( "?lat" );
Literal longitude = solution.getLiteral( "?long" );
String sLat = latitude.getLexicalForm();
String sLon = longitude.getLexicalForm();
float fLat = latitude.getFloat();
float fLon = longitude.getFloat();
System.out.println( "Strings: " + sLat + "," + sLon );
System.out.println( "Floats: " + fLat + "," + fLon );
}
The output after this change is:
Strings: 42.8608,-72.1081
Floats: 42.8608,-72.1081
Using ParameterizedSparqlStrings in CONSTRUCT queries
Based some of the comments, it may also be useful to use CONSTRUCT queries to save the results from each query, and to aggregate them into a larger model. Here's code that uses a construct query to retrieve the latitude and longitude of Mount Monadnock and Mount Lafayette, and stores them in a single model. (Here we're just using CONSTRUCT WHERE {…}, so the model that is returned is exactly the same as the part of the graph that matched. You can get different results by using CONSTRUCT {…} WHERE {…}.)
import com.hp.hpl.jena.query.ParameterizedSparqlString;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
public class DBPediaQuery {
public static void main( String[] args ) {
final String dbpedia = "http://dbpedia.org/sparql";
final ParameterizedSparqlString queryString
= new ParameterizedSparqlString(
"PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>"+
"PREFIX dbo: <http://dbpedia.org/ontology/>" +
"CONSTRUCT WHERE {" +
" ?s a dbo:Place ." +
" ?s geo:lat ?lat ." +
" ?s geo:long ?long ." +
"}" );
Model allResults = ModelFactory.createDefaultModel();
for ( String mountain : new String[] { "Mount_Monadnock", "Mount_Lafayette" } ) {
queryString.setIri( "?s", "http://dbpedia.org/resource/" + mountain );
QueryExecution exec = QueryExecutionFactory.sparqlService( dbpedia, queryString.toString() );
Model results = exec.execConstruct();
allResults.add( results );
}
allResults.setNsPrefix( "geo", "http://www.w3.org/2003/01/geo/wgs84_pos#" );
allResults.setNsPrefix( "dbo", "http://dbpedia.org/ontology/" );
allResults.setNsPrefix( "dbr", "http://dbpedia.org/resource/" );
allResults.write( System.out, "N3" );
}
}
The output shows triples from both queries:
#prefix dbr: <http://dbpedia.org/resource/> .
#prefix geo: <http://www.w3.org/2003/01/geo/wgs84_pos#> .
#prefix dbo: <http://dbpedia.org/ontology/> .
dbr:Mount_Lafayette
a dbo:Place ;
geo:lat "44.1607"^^<http://www.w3.org/2001/XMLSchema#float> ;
geo:long "-71.6444"^^<http://www.w3.org/2001/XMLSchema#float> .
dbr:Mount_Monadnock
a dbo:Place ;
geo:lat "42.8608"^^<http://www.w3.org/2001/XMLSchema#float> ;
geo:long "-72.1081"^^<http://www.w3.org/2001/XMLSchema#float> .