Skip to content

Instantly share code, notes, and snippets.

@bshambaugh
Created January 25, 2018 10:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bshambaugh/7b75bc762f660ae73df821fe629a631d to your computer and use it in GitHub Desktop.
Save bshambaugh/7b75bc762f660ae73df821fe629a631d to your computer and use it in GitHub Desktop.
Example jena select from https://www.youtube.com/watch?v=nUdHneViLp4&t=132s [Apache jena tutorial - using sparql with jena to query rdf document)
import org.apache.jena.util.FileManager;
import org.apache.jena.rdf.model.Model;
// We need to import other parts of the library. The paths are suggested here.
// https://stackoverflow.com/questions/38640091/retrieve-items-from-a-model-in-jena
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSet;
import org.apache.jena.rdf.model.Literal;
public class Main {
public static void main(String args[])
{
/* Reading a turtle file using the FOAF Ontology
* Foaf ontology: http://xmlns.com/foaf/spec/
*/
sparqlTest();
}
static void sparqlTest()
{
FileManager.get().addLocatorClassLoader(Main.class.getClassLoader());
Model model = FileManager.get().loadModel("/home/brent/JenaApplication/jena-two/src/foaf3.rdf");
String queryString =
"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>" +
"PREFIX foaf: <http://xmlns.com/foaf/0.1/>" +
"SELECT * WHERE { " +
" ?person foaf:name ?x . " +
"}";
Query query = QueryFactory.create(queryString);
QueryExecution qexec = QueryExecutionFactory.create(query, model);
try {
ResultSet results = qexec.execSelect();
while ( results.hasNext() ) {
QuerySolution soln = results.nextSolution();
Literal name = soln.getLiteral("x");
System.out.println(name);
}
} finally {
qexec.close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment