duncan smith
duncan smith

Reputation: 21

rdflib SPARQL queries (involving subclasses) not behaving as expected

I have just started to self-learn RDF and the Python rdflib library. But I have hit an issue with the following code. I expected the queries to return mark and nat as Persons and only natalie as a Professor. I can't see where I've gone wrong. (BTW, I know Professor should be a title rather than a kind of Person, but I'm just tinkering ATM.) Any help appreciated. Thanks.

rdflib 4, Python 2.7

>>> from rdflib import Graph, BNode, URIRef, Literal
INFO:rdflib:RDFLib Version: 4.2.
>>> from rdflib.namespace import RDF, RDFS, FOAF
>>> G = Graph()
>>> mark = BNode()
>>> nat = BNode()
>>> G.add((mark, RDF.type, FOAF.Person))
>>> G.add((mark, FOAF.firstName, Literal('mark')))
>>> G.add((URIRef('Professor'), RDF.type, RDFS.Class))
>>> G.add((URIRef('Professor'), RDFS.subClassOf, FOAF.Person))
>>> G.add((nat, RDF.type, URIRef('Professor')))
>>> G.add((nat, FOAF.firstName, Literal('natalie')))
>>> qres = G.query(
        """SELECT DISTINCT ?aname
           WHERE {
              ?a rdf:type foaf:Person .
              ?a foaf:firstName ?aname .
           }""", initNs = {"rdf": RDF,"foaf": FOAF})
>>> for row in qres:
    print "%s is a person" % row


mark is a person
>>> qres = G.query(
        """SELECT DISTINCT ?aname
           WHERE {
              ?a rdf:type ?prof .
              ?a foaf:firstName ?aname .
           }""", initNs = {"rdf": RDF,"foaf": FOAF, "prof": URIRef('Professor')})
>>> for row in qres:
    print "%s is a Prof" % row


natalie is a Prof
mark is a Prof
>>> 

Upvotes: 2

Views: 495

Answers (1)

Ted Lawless
Ted Lawless

Reputation: 860

Your query is bringing back all types because the ?prof variable isn't bound to a value.

I think you want to use is the initBindings kwarg to pass in the URI for 'Professor' to your query. So changing your query to below retrieves just natalie.

qres = G.query( """SELECT DISTINCT ?aname WHERE { ?a rdf:type ?prof . ?a foaf:firstName ?aname . }""", initNs ={"rdf": RDF,"foaf": FOAF}, initBindings={"prof": URIRef('Professor')})

Upvotes: 2

Related Questions