![](/img/trans.png)
[英]Trying to run a sparql query on quads+triples files, getting error: com.bigdata.rdf.sparql.ast.QuadsOperationInTriplesModeException
[英]Recursive SPARQL query for a combination of triples
我有以下查询,我使用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 , 2 )。
在某些承诺下(例如使用树状结构), 可以使用FILTER NOT EXISTS
找出某些东西,但是,这不是一般解决方案。
我们的想法是在两个查询中执行此操作。 实质上,这是SELECT
over CONSTRUCT
。 顺便说一下,已经提出了这种SPARQL扩展。
让我们使用Ontospy所基于的rdflib,因为
Ontospy不提供任何本体编辑功能,也不能用于查询三元组。
输入( ontology.ttl
)
@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 .
Python代码
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 }""")
产量
:Country :hasSome+ :State
:State :hasSome+ :City
:Country :hasSome+ :City
如果您不想修改初始RDFLib图,只需创建另一个:
import rdflib
g1 = rdflib.Graph()
g1.parse("ontology.ttl", format="n3")
qres = g1.query(
"""PREFIX : <http://www.example.org/ontology#>
CONSTRUCT {?c :hasSome ?p } WHERE {
?c rdfs:subClassOf [ owl:onProperty :hasPart ;
owl:someValuesFrom ?p ] }""")
g2 = rdflib.Graph();
for triple in qres: # quite a few triples
g2.add(triple)
qres = g2.query(
"""PREFIX : <http://www.example.org/ontology#>
SELECT ?a ?b WHERE { ?a :hasSome+ ?b }""")
for row in qres:
print("%s :hasSome+ %s" % row)
在这两种情况下,您可以使用transitiveClosure()
或transitive_objects()
而不是第二个查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.