package com.franz.agbase.examples;
import com.franz.agbase.*;
public class AGSparqlOptionals {
/**
* Demonstrates some basics of using OPTIONAL 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 fresh triple-store for this example.
AllegroGraph ts = ags.renew("sparql", AGPaths.TRIPLE_STORES);
// Register any namespaces
ts.registerNamespace("foaf", "http://xmlns.com/foaf/0.1/");
// Define blank nodes
BlankNode a = (BlankNode)ts.createBNode("_:a");
BlankNode b = (BlankNode)ts.createBNode("_:b");
// Add some data to the store
ts.addStatement(a,"!rdf:type","!foaf:Person");
ts.addStatement(a,"!foaf:name",ts.createLiteral("Alice"));
ts.addStatement(a,"!foaf:mbox","<mailto:[email protected]>");
ts.addStatement(a,"!foaf:mbox","<mailto:[email protected]>");
ts.addStatement(b,"!rdf:type","!foaf:Person");
ts.addStatement(b,"!foaf:name",ts.createLiteral("Bob"));
ts.addStatement(b,"!foaf:homepage","<http://work.example.org/alice/>");
// This query finds the names of people in the data. If there is a
// triple with predicate mbox and the same subject, a solution will
// contain the object of that triple as well.
String query =
"PREFIX foaf: <http://xmlns.com/foaf/0.1/> " +
"SELECT ?name ?mbox " +
"WHERE { ?x foaf:name ?name . " +
"OPTIONAL { ?x foaf:mbox ?mbox } " +
"}";
// Query the store and show the results
SPARQLQuery sq = new SPARQLQuery();
sq.setTripleStore(ts);
sq.setQuery(query);
AGSparqlSelect.doSparqlSelect(sq);
// A graph pattern may have zero or more optional graph patterns.
// In this example, there are two optional graph patterns.
query =
"PREFIX foaf: <http://xmlns.com/foaf/0.1/> " +
"SELECT ?name ?mbox ?hpage " +
"WHERE { ?x foaf:name ?name . " +
"OPTIONAL { ?x foaf:mbox ?mbox } . " +
"OPTIONAL { ?x foaf:homepage ?hpage } " +
"}";
// 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();
}
}
Copyright © 2023 Franz Inc., All Rights Reserved | Privacy Statement |