将 Hermit 与 ONT-API 和 SPARQL 查询结合使用

Using Hermit with ONT-API and SPARQL Query

我正在使用 OWL-API 加载和 owl ontology 使用 SWRL 规则。

我使用以下代码加载了 ontology:

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 class.

一行代码胜过千言万语:

/** 
* 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());
    }
}