Jena - SPARQL

From XennisWiki
Jump to: navigation, search

Jena comes with a build in SPARQL support.

SPARQL query engine

QueryEngine.java

import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.ResultSetFormatter;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.util.FileManager;

/**
 * SPARQL query engine
 * 
 * The program read an RDF graph and a SPARQL query from files.
 */
public class QueryEngine {

	private Model model;

	/**
	 * Create a QueryEngine.
	 * 
	 * @param modelFile
	 *            Create model from this file
	 * @throws Exception
	 */
	public QueryEngine(String modelFile) throws Exception {
		this.model = FileManager.get().loadModel(modelFile);
	}

	/**
	 * Run the query form the given file.
	 * 
	 * @param queryFile
	 *            Query file
	 * @throws Exception
	 */
	public void runQuery(String queryFile) throws Exception {
		Query q = QueryFactory.read(queryFile);
		QueryExecution qe = QueryExecutionFactory.create(q, model);

		switch (q.getQueryType()) {
		case Query.QueryTypeAsk:
			ResultSetFormatter.out(qe.execAsk());
			break;
		case Query.QueryTypeConstruct:
			qe.execConstruct().write(System.out, FileUtils.langTurtle);
			break;
		case Query.QueryTypeDescribe:
			qe.execDescribe().write(System.out, FileUtils.langTurtle);
			break;
		case Query.QueryTypeSelect:
			ResultSetFormatter.out(System.out, qe.execSelect());
			break;
		default:
			System.err.println("Unsupported query type!");
			break;
		}
	}

	public static void main(String[] args) {
		if (args.length < 2) {
			System.err.println("Less arguments");
			System.err.println("\tUsage: <model_file> <query_file>");
			System.err.println("\tExample: myModel.ttl myQuery.rd");
		}

		try {
			QueryEngine engine = new QueryEngine(args[0]);
			engine.runQuery(args[1]);
		} catch (Exception e) {
			System.err.println("Error:");
			e.printStackTrace();
		}
	}
}

Example CONSTRUCT query

prefix rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
prefix xsd:  <http://www.w3.org/2001/XMLSchema#>
prefix foaf: <http://xmlns.com/foaf/0.1/>
prefix fam:  <http://example.com/family#>
prefix sim:  <http://example.com/simpsons#>

CONSTRUCT {
	?spouse rdf:type foaf:Woman .
} WHERE {
	sim:Homer fam:hasSpouse ?spouse .
}

Use endpoint

String sparqlEndpoint = "http://example.com/api/sparql";
Query query = QueryFactory.read(queryFile);
QueryExecution qexec = QueryExecutionFactory.createServiceRequest(sparqlEndpoint, query);

See also