我正在使用OWL-API来加载带有SWRL规则的OWL本体。
我用以下代码加载了一个本体:
IRI iri = IRI.create(BASE_URL);
OntologyManager manager = OntManagers.createManager();
// Load an ontology
Ontology ontologyWithRules = manager.loadOntologyFromOntologyDocument(iri);
然后我实例化一个隐士推理器:
import org.semanticweb.HermiT.ReasonerFactory;
OWLReasonerFactory reasonerFactory = new ReasonerFactory();
OWLReasoner reasoner = reasonerFactory.createReasoner(ontologyWithRules);
最后,我想查询一下这个模型:
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());
}
}
然而,推理机并没有被使用。有没有一种方法可以在启用推理器的情况下对图使用SPARQL查询?
在模型上运行推断是缺失的一步。因此,我需要使用InferredOntologyGenerator
类。
一行代码胜过千言万语:
/**
* 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());
}
}