如何根据主题查找RDF对象或反之?
我正在使用RDFLIB来构建三个数据集(A、B、C)之间的图,数据格式是ntriples。
我的目标是让这些图包含数据集之间的链接,比如A指向B,B指向C,C又指向A。我想检查这些链接的一致性,确保从A出去的链接能正确指回A中的相同条目。
问题是:当我遍历A到B的链接时,我想查找在B到C中对应的条目(可能不止一个),同样的情况也适用于C到A。我想知道有没有办法在知道主题的情况下查找对象,而不需要遍历所有条目?
1 个回答
5
有没有办法通过知道主题来查找对象,而不需要遍历所有条目呢?
答案是有的。你可以使用两种不同的方法:(a)带限制地遍历;或者(b)发出一个SPARQL查询。
(a) 限制图形并遍历
这个方法使用了RDFLib中的triples
函数,作用于图对象。你可以查看这个链接了解更多信息。
#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])