我正在使用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查询?
发布于 2021-04-27 23:15:51
在模型上运行推理是缺失的一步。因此,我需要使用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());
}
}https://stackoverflow.com/questions/67272845
复制相似问题