I am using the OWL-API to load and owl ontology with SWRL rules.
I loaded an ontology with the following code:
IRI iri = IRI.create(BASE_URL);
OntologyManager manager = OntManagers.createManager();
// Load an ontology
Ontology ontologyWithRules = manager.loadOntologyFromOntologyDocument(iri);
Then I instantiate a Hermit reasoner:
import org.semanticweb.HermiT.ReasonerFactory;
OWLReasonerFactory reasonerFactory = new ReasonerFactory();
OWLReasoner reasoner = reasonerFactory.createReasoner(ontologyWithRules);
Finally, I'd like to query this model:
try (
QueryExecution qexec = QueryExecutionFactory.create(QueryFactory
.create("SELECT ?s ?p ?o WHERE { ?s ?p ?o }"), ontologyWithRules.asGraphModel())
) {
ResultSet res = qexec.execSelect();
while (res.hasNext()) {
System.out.println(res.next());
}
}
However the reasoner wasn't used. Is there a way to use the SPARQL query over the graph with the reasoner turned on?
Running inferences over the model was the missing step. Therefore, I needed to use the InferredOntologyGenerator
class.
One line of code speaks more than a thousand words:
/**
* Important imports:
* import org.semanticweb.HermiT.ReasonerFactory;
* import org.semanticweb.owlapi.util.InferredOntologyGenerator;
**/
IRI iri = IRI.create(BASE_URL);
OntologyManager manager = OntManagers.createManager();
// Load an ontology
Ontology ontologyWithRules = manager.loadOntologyFromOntologyDocument(iri);
// Instantiate a Hermit reasoner:
OWLReasonerFactory reasonerFactory = new ReasonerFactory();
OWLReasoner reasoner = reasonerFactory.createReasoner(ontologyWithRules);
OWLDataFactory df = manager.getOWLDataFactory();
// Create an inference generator over Hermit reasoner
InferredOntologyGenerator inference = new InferredOntologyGenerator(reasoner);
// Infer
inference.fillOntology(df, ontologyWithRules);
// Query
try (
QueryExecution qexec = QueryExecutionFactory.create(QueryFactory
.create("SELECT ?s ?p ?o WHERE { ?s ?p ?o } "), ontologyWithRules.asGraphModel())
) {
ResultSet res = qexec.execSelect();
while (res.hasNext()) {
System.out.println(res.next());
}
}