针对三元组合的递归SPARQL查询

时间:2018-03-15 19:11:15

标签: python sparql owl

我有以下查询,我使用ontospy在Python中递归运行:

SELECT ?c WHERE {
    ?c rdfs:subClassOf ?restriction .
    ?restriction owl:onProperty :has_part ; owl:someValuesFrom ?p .
    VALUES ?p { <some_uri> }
}

基本上,我从中返回的值并重新运行查询,以遵循本体中“有部分”关系的层次结构。我希望通过向查询本身添加递归来避免进行多个SPARQL查询。我知道如何使用rdfs:subClassOf*为单个三元组执行此操作,但无法找出组合两个三元组的语法:

?c rdfs:subClassOf ?restriction .
?restriction owl:onProperty :has_part ; owl:someValuesFrom ?p .

这可能吗?

1 个答案:

答案 0 :(得分:3)

我不能给出正式的证据,但这看起来不可能。这不是针对属性路径设计的,以及为什么存在某些扩展(12)。

根据某些承诺(例如使用树状结构),使用 <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <version>${version.maven-bundle-plugin}</version> <extensions>true</extensions> <configuration> <instructions> <Bundle-SymbolicName>${project.groupId}.${project.artifactId}</Bundle-SymbolicName> <Bundle-Name>${project.name}</Bundle-Name> <Import-Package>org.jasypt.encryption.pbe, com.google.gson, javax.ws.rs, javax.xml.bind.annotation, com.fasterxml.jackson.jaxrs.json, com.fasterxml.jackson.jaxrs.xml, org.apache.camel, org.apache.camel.builder, org.apache.camel.model,* </Import-Package> </instructions> </configuration> </plugin> 计算出某些内容possible,但这不是一般解决方案。

这个想法是在两个查询中执行此操作。实质上,这是FILTER NOT EXISTS超过SELECT。顺便说一下,这样的SPARQL扩展已经是proposed

让我们使用Ontospy所基于的,因为

  

Ontospy不提供任何本体编辑功能,也不能用于查询三元组。

输入(CONSTRUCT

ontology.ttl

Python代码

@prefix : <http://www.example.org/ontology#> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@base <http://www.example.org/ontology> .

<http://www.example.org/ontology> rdf:type owl:Ontology .

:hasPart rdf:type owl:ObjectProperty .

:Country rdf:type owl:Class ;
         rdfs:subClassOf [ rdf:type owl:Restriction ;
                           owl:onProperty :hasPart ;
                           owl:someValuesFrom :State
                         ] .

:State rdf:type owl:Class ;
       rdfs:subClassOf [ rdf:type owl:Restriction ;
                         owl:onProperty :hasPart ;
                         owl:someValuesFrom :City
                       ] .

:City rdf:type owl:Class .

<强>输出

import rdflib

g = rdflib.Graph()
g.parse("ontology.ttl", format="n3")

qres = g.update(
    """PREFIX : <http://www.example.org/ontology#> 
       INSERT { ?c :hasSome ?p } 
       WHERE  { ?c rdfs:subClassOf [ owl:onProperty :hasPart ; 
                                     owl:someValuesFrom ?p ] }""")

qres = g.query(
    """PREFIX : <http://www.example.org/ontology#> 
       SELECT ?a ?b WHERE {?a :hasSome+ ?b }""")

for row in qres:
    print("%s :hasSome+ %s" % row)

qres = g.update(
    """PREFIX : <http://www.example.org/ontology#> 
       DELETE { ?s :hasSome ?o } WHERE { ?s :hasSome ?o }""")

如果您不想修改初始RDFLib图,只需创建另一个:

:Country :hasSome+ :State
:State   :hasSome+ :City
:Country :hasSome+ :City

在这两种情况下,您可以使用transitiveClosure()transitive_objects()代替第二个查询。