1

我正在使用 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 查询?

4

1 回答 1

0

对模型进行推理是缺少的步骤。因此,我需要使用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());
    }
}

于 2021-04-27T15:15:51.423 回答