rdflib SPARQL queries (involving subclasses) not behaving as expected

怎甘沉沦 提交于 2020-01-02 19:29:14

问题


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:


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



来源:https://stackoverflow.com/questions/35786261/rdflib-sparql-queries-involving-subclasses-not-behaving-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!