2

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
>>> 

1 Answers1

2

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')})

Ted Lawless
  • 830
  • 6
  • 6
  • Yes, exactly right. The other thing I didn't understand was why natalie wasn't recognized as a person via the subclass relationship. But I think the answer to that is that the rdflib SPARQL engine simply doesn't perform that kind of reasoning. Cheers. – duncan smith Mar 14 '16 at 19:05
  • can I use initBindings for name individuals too? – msc87 May 24 '16 at 08:26
  • @msc87 you can also use this for the `?aname` variable in the sample query too. You will want to pass in an RDFLib `Literal` through the init bindings. So: initBindings={"aname": Literal('natalie')}) – Ted Lawless Aug 14 '16 at 14:00