# AGSparqlOrderBy.java

`package com.franz.agbase.examples;
import com.franz.agbase.*;
public class AGSparqlOrderBy {
/**
* Demonstrates basics of using ORDER BY in SPARQL
*
* @param args unused
* @throws AllegroGraphException
*/
public static void main(String[] args) throws AllegroGraphException {
// Connect to server, which must already be running.
AllegroGraphConnection ags = new AllegroGraphConnection();
try {
ags.enable();
} catch (Exception e) {
throw new AllegroGraphException("Server connection problem", e);
}
// Create a fresh triple store
AllegroGraph ts = ags.renew("sparqlorderby", AGPaths.TRIPLE_STORES);
// Load the Kennedy data
AGLoadNtriples.loadNTriplesWithTiming(ts,AGPaths.dataSources("kennedy.ntriples"));
// Index the store for querying, wait until indexing is complete.
ts.indexAllTriples(true);
// Query for people ordered by birth year (oldest first)
String query =
"PREFIX ex: <http://example.org/kennedy/> " +
"SELECT ?fname ?lname ?year " +
"WHERE { ?person ex:last-name ?lname . " +
"?person ex:first-name ?fname . " +
"?person ex:birth-year ?year " +
"}" +
"ORDER BY ?year ";
// Query the store and show the results
SPARQLQuery sq = new SPARQLQuery();
sq.setTripleStore(ts);
sq.setQuery(query);
AGSparqlSelect.doSparqlSelect(sq);
// Query for people ordered by last name, then birth
// year (youngest first)
query =
"PREFIX ex: <http://example.org/kennedy/> " +
"SELECT ?fname ?lname ?year " +
"WHERE { ?person ex:last-name ?lname . " +
"?person ex:first-name ?fname . " +
"?person ex:birth-year ?year " +
"}" +
"ORDER BY ?lname DESC(?year) ";
// Query the store and show the results
sq.setQuery(query);
AGSparqlSelect.doSparqlSelect(sq);
// Close the triple store and disconnect from the server
ts.closeTripleStore();
ags.disable();
}
}
`

Up | Next