2013-06-29 2 views
0

Я оцениваю возможности запросов Jena, связанные с Model API, и перед вами стоит проблема. Во-первых, я тестирую запросы об ограничениях. Фактически, Jena является одним из доступных API, которые позволяют запрашивать выводимые модели. Кроме того, мне нужно разделить схему на данные, поэтому, используя Protégé, я создал два отдельных файла RDF с двумя разными пространствами имен.Невозможно перестроить действующую онтологию OWL с использованием API Jena OntModel

В первом пространстве имен http://www.test.com/schema# для схемы имеется один класс: Woman; одно свойство объекта: hasSpouse; и один эквивалентный класс по ограничению на hasSpouse : Husband.

<?xml version="1.0"?> 
<!DOCTYPE rdf:RDF [ 
    <!ENTITY owl "http://www.w3.org/2002/07/owl#" > 
    <!ENTITY xsd "http://www.w3.org/2001/XMLSchema#" > 
    <!ENTITY rdfs "http://www.w3.org/2000/01/rdf-schema#" > 
    <!ENTITY rdf "http://www.w3.org/1999/02/22-rdf-syntax-ns#" > 
]> 
<rdf:RDF xmlns="http://www.test.com/schema#" 
    xml:base="http://www.test.com/schema#" 
    xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" 
    xmlns:owl="http://www.w3.org/2002/07/owl#" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema#" 
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> 
    <!--<owl:Ontology rdf:about="http://www.test.com/schema"/>--> 

    <owl:ObjectProperty rdf:about="http://www.test.com/schema#hasSpouse"> 
     <rdfs:range rdf:resource="http://www.test.com/schema#Woman"/> 
    </owl:ObjectProperty> 

    <owl:Class rdf:about="http://www.test.com/schema#Husband"> 
     <owl:equivalentClass> 
      <owl:Restriction> 
       <owl:onProperty rdf:resource="http://www.test.com/schema#hasSpouse"/> 
       <owl:someValuesFrom rdf:resource="http://www.test.com/schema#Woman"/> 
      </owl:Restriction> 
     </owl:equivalentClass> 
    </owl:Class> 

    <owl:Class rdf:about="http://www.test.com/schema#Woman"/> 
</rdf:RDF> 

Во втором пространстве имен, http://www.test.com/data#, есть два человека: john и janette. janette является супругом Woman и john является janette.

<?xml version="1.0"?> 
<!DOCTYPE rdf:RDF [ 
    <!ENTITY owl "http://www.w3.org/2002/07/owl#" > 
    <!ENTITY xsd "http://www.w3.org/2001/XMLSchema#" > 
    <!ENTITY rdfs "http://www.w3.org/2000/01/rdf-schema#" > 
    <!ENTITY rdf "http://www.w3.org/1999/02/22-rdf-syntax-ns#" > 
    <!ENTITY schema "http://www.test.com/schema#"> 
]> 
<rdf:RDF xmlns="http://www.test.com/data#" 
    xml:base="http://www.test.com/data#" 
    xmlns:schema="http://www.test.com/schema#" 
    xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" 
    xmlns:owl="http://www.w3.org/2002/07/owl#" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema#" 
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> 

    <owl:NamedIndividual rdf:about="http://www.test.com/data#janette"> 
     <rdf:type rdf:resource="http://www.test.com/schema#Woman"/> 
    </owl:NamedIndividual> 

    <owl:NamedIndividual rdf:about="http://www.test.com/data#john"> 
     <schema:hasSpouse rdf:resource="http://www.test.com/data#janette"/> 
    </owl:NamedIndividual> 
</rdf:RDF> 

Мой тестовый запрос находит все husband в данных, и я ожидаю получить john. Вот запрос:

PREFIX schema: <http://www.test.com/schema#> 
    select ?subject where {?subject a schema:Husband} 

Все хорошо работает, используя код ниже

System.out.println("QUERY ON LOADED RESTRICTION"); 
    String path = "...."; 

    Model schema = FileManager.get().loadModel("file:"+path+"married_schema_ns.xml"); 
    schema.write(System.out, "RDF/XML-ABBREV"); 
    Model data = FileManager.get().loadModel("file:"+path+"married_data_ns.xml"); 
    data.write(System.out, "RDF/XML-ABBREV"); 

    Reasoner reasoner = ReasonerRegistry.getOWLReasoner(); 
    reasoner = reasoner.bindSchema(schema); 
    InfModel inf_model = ModelFactory.createInfModel(reasoner, data);  

    String query_string = "PREFIX schema: <http://www.test.com/schema#>\r\n"; 
    query_string += "select ?subject where {?subject a schema:Husband}"; 

    Query query = QueryFactory.create(query_string);  
    query.serialize(new IndentedWriter(System.out)); 
    QueryExecution execution = QueryExecutionFactory.create(query,model); 

    ResultSet results = execution.execSelect(); 
    while (results.hasNext()) { 
     QuerySolution solution = results.nextSolution(); 
     RDFNode node = solution.get("subject"); 
     System.out.println("subject="+node); 
    } 

    System.out.println("END ...."); 

Система ответы subject=http://www.test.com/data#john, как и ожидалось. Я попытался построить точно то же самое Model с нуля, но потом запрос больше не работает.

System.out.println("QUERY ON BUILT RESTRICTION"); 
    OntModel ontology = ModelFactory.createOntologyModel(); 
    String ns_ontology="http://www.test.com/schema#"; 
    String pr_ontology = "schema"; 
    ontology.setNsPrefix("", ns_ontology); 

    ObjectProperty has_spouse = ontology.createObjectProperty(ns_ontology+"hasSpouse"); 
    OntClass woman = ontology.createClass(ns_ontology+"Woman"); 
    has_spouse.setRange(woman); 

    OntClass husband = ontology.createClass(ns_ontology+"Husband");  
    SomeValuesFromRestriction restriction = ontology.createSomeValuesFromRestriction(null, has_spouse, woman); 
    husband.addEquivalentClass(restriction); 

    String ns_facts = "http://www.test.com/data#"; 
    String pr_facts = "data"; 

    OntModel facts = ModelFactory.createOntologyModel(); 
    facts.setNsPrefix("", ns_facts); 
    facts.setNsPrefix(pr_ontology, ns_ontology); 
    Resource r = facts.getResource("http://www.w3.org/2002/07/owl#NamedIndividual"); 
    Individual john = facts.createIndividual(ns_facts+"john",r);   
    Individual janette = facts.createIndividual(ns_facts+"janette",r); 
    janette.addProperty(RDF.type, woman); 
    john.addProperty(has_spouse, janette);    

    Reasoner reasoner = ReasonerRegistry.getOWLReasoner(); 
    reasoner.bindSchema(ontology); 
    Model inf_model = ModelFactory.createInfModel(reasoner, facts); 

    String query_string = "PREFIX schema: <"+ns_ontology+">\r\n"; 
    query_string += "select ?subject where {?subject a schema:Husband}"; 

    Query query = QueryFactory.create(query_string);  
    query.serialize(new IndentedWriter(System.out)); 
    QueryExecution execution = QueryExecutionFactory.create(query,model); 

    ResultSet results = execution.execSelect(); 
    while (results.hasNext()) { 
     QuerySolution solution = results.nextSolution(); 
     RDFNode node = solution.get("subject"); 
     System.out.println("subject="+node); 
    } 
    System.out.println("END ..."); 

Я не понимаю, почему. Сериализация RDF/XML-ABBREV двух версий идеально подходит.

Кроме того, при загрузке построенной схемы/сериализации данных в первой версии запрос снова работает.

Если кто-то может помочь мне понять этот момент!

+1

Это настоящий код, в котором вы работаете? Выполнение запроса Выполнение QueryExecution = QueryExecutionFactory.create (запрос, модель); 'reference' model', но я не вижу никакой переменной 'model'. (Это как в первом, так и в втором блоках кода.) –

+0

Фактически я оригинально создаю функцию для выполнения запроса, и я скопирую тело для чтения. Я забыл обновить имя переменной извините! – jeanmi

+0

Попробуйте написатьВсе модель во втором решении. Согласны ли аксиомы с аксиомами в онтологии протеже? Если вы хотите программно найти различия, вы можете создать два объекта HashSet и, используя эти объекты, сравнить утверждения в моделях. –

ответ

0

Я забыл переназначить аргумент переменной после вызова его метода bindSchemareasoner = reasoner.bindSchema(schema).