import rdflib from rdflib import Graph, URIRef, Literal, Namespace SH = Namespace("http://bug/") graph = Graph() graph.bind('sh',SH) graph.add((SH.a,SH.p,SH.b)) graph.add((SH.b,SH.p,SH.c)) graph.add((SH.x,SH.p,SH.y)) # finding a chain of length three q1 = """SELECT ?here ?there ?elsewhere WHERE { ?here sh:p ?there . ?there sh:p ?elsewhere . }""" r1 = graph.query(q1) for row in r1 : r1r = row; print row # also should find *and report* the chain, but doesn't report correctly q2 = """SELECT ?here ?there ?elsewhere WHERE { ?here sh:p ?there . { SELECT ?there ?elsewhere WHERE { ?there sh:p ?elsewhere . } } }""" r2 = graph.query(q2) for row in r2: r2r = row; print row # also should find *and report* the chain, and does q3 = """SELECT ?here ?there ?elsewhere WHERE { { SELECT ?there ?elsewhere WHERE { ?there sh:p ?elsewhere . } } ?here sh:p ?there . }""" r3 = graph.query(q3) for row in r3: r3r = row; print row assert r1r[0] == r2r[0] assert r1r[1] == r2r[1] assert r1r[2] == r2r[2] assert r3r[0] == r2r[0] assert r3r[1] == r2r[1] assert r3r[2] == r2r[2]