# AGPrologRules.java

`package com.franz.agbase.examples;
import com.franz.agbase.*;
public class AGPrologRules {
/**
* Demonstrates some basics of using Horn rules in Prolog.
*
* @param 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 for this example.
AllegroGraph ts = ags.renew("prologrules", AGPaths.TRIPLE_STORES);
// Load the Kennedy data
AGLoadNtriples.loadNTriplesWithTiming(ts, AGPaths.dataSources("kennedy.ntriples"));
// Index the store for faster querying
AGIndexAllTriples.indexAllTriplesWithTiming(ts);
// Register any namespaces
ts.registerNamespace("ex", "http://example.org/kennedy/");
// Add some horn rules for use in queries. The <-- operator
// overwrites any previous definitions for the clause head.
// Note that these definitions take effect server-wide.
String[] rules = new String[4];
rules[0] = "(<-- (male ?x) (q ?x !ex:sex !ex:male))";
rules[1] = "(<-- (female ?x) (q ?x !ex:sex !ex:female))";
rules[2] = "(<-- (father ?x ?y) (male ?x) (q ?x !ex:has-child ?y))";
rules[3] = "(<-- (mother ?x ?y) (female ?x) (q ?x !ex:has-child ?y))";
ags.addPrologRules(rules);
// Set up a Prolog query object.
PrologSelectQuery q = new PrologSelectQuery();
q.setTripleStore(ts);
// Rules are applied "on top of" whatever entailment regime is in effect.
// Here we won't use RDFS++ entailment, so the rules will be applied over
// what's explicitly in the store.
q.setIncludeInferred(false);
// Query the store for all sons of person1.
String pquery = "(q !ex:person1 !ex:has-child ?x)" + "(male ?x)";
q.setVariables(new String[]{"x"});
q.setQuery(pquery);
ValueSetIterator it = q.run();
System.out.println("Results for " + pquery);
AGUtils.showResults(it);
// Query the store for mothers and sons
pquery = "(mother ?m ?s) (male ?s)";
q.setVariables(new String[]{"m","s"});
q.setQuery(pquery);
it = q.run();
System.out.println("Results for " + pquery);
AGUtils.showResults(it);
// Now for fathers and daughters
pquery = "(father ?f ?d) (female ?d)";
q.setVariables(new String[]{"f","d"});
q.setQuery(pquery);
it = q.run();
System.out.println("Results for " + pquery);
AGUtils.showResults(it);
// Close the triple store and disconnect from the server.
ts.closeTripleStore();
ags.disable();
}
}
`

Up | Next