【问题标题】:How to return subgraph from rdf graph如何从 rdf 图返回子图
【发布时间】:2022-08-19 00:24:37
【问题描述】:

为了简单起见,我有一个带有几个类的 RDF 图 G(Person 和 Parrot)。 类Person 通过属性hasAnimal 连接到类Parrot,例如:

@PREFIX : <http://example.org/> 

:Hugo rdf:type :Person . 
:Hugo rdfs:label \"Hugo\" .
:Hugo :hasAnimal :Birdy.
:Birdy rdf:type :Parrot .
:Birdy rdfs:label :\"Birdy\" .

:LonleyBrido rdf:type :Parrot . 

我们需要的是 G 的一个子图,它包含来自 Person 和 Parrot 的所有三元组,它们直接相互连接,从 Person 开始。最初的 Person 对我来说无关紧要,重要的部分是只提取连接的三元组,即要么是 Person 并且确实有一只鹦鹉,要么没有。我已经尝试过的是:

construct {
?person ?p ?o .
?parrot ?p2 ?o2 .
} where {
?person rdf:type :Person .
?person ?p ?o .
?person :hasAnimal ?parrot .
?parrot  rdf:type :Parrot  .
?parrot  ?p2 ?o2 .
}

所以预期的输出是:

:Hugo rdf:type :Person . 
:Hugo rdfs:label \"Hugo\" .
:Hugo :hasAnimal :Birdy.
:Birdy rdf:type :Parrot .
:Birdy rdfs:label :\"Birdy\" .

我正在rdflib 图表上执行此查询。 有没有人可以解决这个问题?

  • 您能否在您的问题中添加您当前查询的问题是什么?有什么问题/不工作?
  • @Stefan-broxIT-Solutions,是的,当前版本对我不起作用。输出为空。
  • 请以 N-Triples 或 Turtle 语法提供示例数据 - 如果查询返回一组空的三元组,则查询根本与数据不匹配。检查前缀,检查类和属性的命名,检查是否存在通过谓词:a_to_b:A 实例与:B 实例三重连接
  • 就像我创建了最少的示例数据:PREFIX : &lt;http://example.org/&gt; :a a :A . :a :a_to_b :b . :b a :B . - 并且查询显然有效(在查询中为: 使用相同的命名空间)
  • 您的示例数据和查询在语法上并不完全正确。无论如何,固定的自包含数据:@prefix : &lt;http://example.org/&gt; . @prefix rdf: &lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&gt;. @prefix rdfs: &lt;http://www.w3.org/2000/01/rdf-schema#&gt;. :Hugo rdf:type :Person . :Hugo rdfs:label \"Hugo\" . :Hugo :hasAnimal :Birdy. :Birdy rdf:type :Parrot . :Birdy rdfs:label \"Birdy\" . :LonleyBrido rdf:type :Parrot .

标签: sparql rdf semantic-web


【解决方案1】:

上面已经描述了解决方案:

import rdflib
from rdflib.namespace import RDF, RDFS

query = """
construct {
?person ?p ?o .
?parrot ?p2 ?o2 .
} where {
?person rdf:type :Person .
?person ?p ?o .
?person :hasAnimal ?parrot .
?parrot  rdf:type :Parrot  .
?parrot  ?p2 ?o2 .
}
"""

g = rdflib.Graph()
g.parse("example.ttl", format="ttl")
g.bind("rdf", RDF)
g.bind("rdfs", RDFS)
EX= rdflib.Namespace("http://example.org/")
g.bind("example", EX)
result = g.query(query)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    • 2022-12-24
    • 1970-01-01
    相关资源
    最近更新 更多