While the command-line sparql tool is useful for running standalone queries, Java applications can call on Jena’s SPARQL capabilities directly. SPARQL queries are created and executed with Jena via classes in the com.hp.hpl.jena.query package. Using QueryFactory is the simplest approach. QueryFactory has various create() methods to read a textual query from a file or from a String. These create() methods return a Query object, which encapsulates a parsed query.

The next step is to create an instance of QueryExecution, a class that represents a single execution of a query. To obtain a QueryExecution, call QueryExecutionFactory.create(query, model), passing in the Query to execute and the Model to run it against. Because the data for the query is provided programmatically, the query does not need a FROM clause.

There are several different execute methods on QueryExecution, each performing a different type of query (see the sidebar entitled “Other types of SPARQL queries” for more information). For a simple SELECT query, call execSelect(), which returns a ResultSet. The ResultSet allows you to iterate over each QuerySolution returned by the query, providing access to each bound variable’s value. Alternatively, ResultSetFormatter can be used to output query results in various formats.

Example :

// Open the bloggers RDF graph from the filesystem
InputStream in = new FileInputStream(new File(“bloggers.rdf”));

// Create an empty in-memory model and populate it from the graph
Model model = ModelFactory.createMemModelMaker().createModel();
model.read(in,null); // null base URI, since model URIs are absolute
in.close();

// Create a new query
String queryString =
“PREFIX foaf: <http://xmlns.com/foaf/0.1/&gt; ” +
“SELECT ?url ” +
“WHERE {” +
”      ?contributor foaf:name \”Jon Foobar\” . ” +
”      ?contributor foaf:weblog ?url . ” +
”      }”;

Query query = QueryFactory.create(queryString);

// Execute the query and obtain results
QueryExecution qe = QueryExecutionFactory.create(query, model);
ResultSet results = qe.execSelect();

// Output query results
ResultSetFormatter.out(System.out, results, query);

// Important – free up resources used running the query
qe.close();

Source : http://www-128.ibm.com/developerworks/library/j-sparql/

Advertisements