我正在使用 RDFLIB 在带有 ntriples 的 3 个数据集(A、B、C)之间构建图形。
目标:图表包含这些数据集 A->B、B->C 和 C->A 之间的链接,我想通过确保从 A 传出的链接引用回 A 中的相同条目来检查这些链接的一致性。
问题:一旦我遍历 A->B 中的链接,我想在 B->C 中查找相应的条目(可能不止一个),对于 C->A 也是如此,有没有办法通过了解主题而不遍历所有条目来查找对象?
有没有办法通过知道主题而不遍历所有条目来查找对象?
答案是肯定的。您可以使用不同的机制:(a)有限制地迭代;或 (b) 发出 SPARQL 查询。
(a) 约束图并迭代
triples
此解决方案在 Graph 对象上使用 RDFLib函数。请参阅此参考。
#Parse the file
g = rdflib.Graph()
g.parse("yourdata.nquads")
subject = article = rdflib.term.URIRef("http://www.someuri.org/for/your/subject")
# (subject,None,None) represents a constrain to iterate over the graph. By setting
# any of the three elements in the triple you constrain by any combination of subject,
# predicate or object. In this case we only constrain by subject.
for triple in g.triples((subject,None,None)):
print triple
(b) 发出 SPARQL 查询
使用SPARQL 标准的更标准的解决方案。
rdflib.plugin.register('sparql', rdflib.query.Processor,
'rdfextras.sparql.processor', 'Processor')
rdflib.plugin.register('sparql', rdflib.query.Result,
'rdfextras.sparql.query', 'SPARQLQueryResult')
#Parse the file
g = rdflib.Graph()
g.parse("yourdata.nquads")
query = """
SELECT ?pred ?obj WHERE {
<http://www.someuri.org/for/your/subject> ?pred ?obj
}
"""
for row in g.query(query):
print "Predicate:%s Object:%s"%(row[0],row[1])