如何在RDFLib中的预准备查询中替换namedIndivdual

时间:2016-05-24 11:07:09

标签: python sparql rdflib

我有以下代码可以使用:

for ref_roundaboutID, ref_roundaboutInfo in ref_roundabouts_dict.iteritems():
    print ref_roundaboutID, ref_roundaboutInfo
    ref_RaURI = ref_roundaboutInfo["URI"]
    query = "SELECT distinct ?p ?a ?FID ?b  ?NFID\
            WHERE {?a rno:end_at ?b; rno:FID ?FID;\
            rno:is_part_of ?p; rno:is_part_of ?st.\
            ?p rdf:type ?type.\
            ?type rdfs:subClassOf rno:Street_partiotion.\
            ?st rdf:type rno:Street.\
            ?b rdf:type rno:Node; rno:is_extent_of ?x; rno:FID ?NFID.\
            ?x rno:builds rno:%(v1)s.\
            rno:%(v1)s rdf:type rno:Roundabout.\
            FILTER(NOT EXISTS {?a rno:builds rno:%(v1)s}).\
            FILTER(NOT EXISTS {?st rdf:type rno:detailed_partition}).\
            FILTER(NOT EXISTS {?p rdf:type rno:Lane})}"%dict(v1=ref_RaURI)

    ## rno is the name space rno = Namespae(http://www.semanticweb.org/ontologies/2015/3/RNO_V5042#)

    sparql.prepareQuery(query, initNs={"rno":rno})


    ref_sectionInfo_around_RA=dict()
    results = ref_rdf.query(query, initNs={"rno":rno})
    for result in results:
        sectionUri, linkUri, linkId, nodeUri, nodeId =result 

        print sectionUri, linkUri, linkId, nodeUri, nodeId 

现在我想通过准备一个查询来优化我的代码,并为不同的命名个体多次询问。所以我偶然发现了initBindings,它可以用字典中的变量替换构造查询中的变量。我的代码如下:

query = "SELECT distinct ?p ?a ?FID ?b  ?NFID\
            WHERE {?a rno:end_at ?b; rno:FID ?FID;\
            rno:is_part_of ?p; rno:is_part_of ?st.\
            ?p rdf:type ?type.\
            ?type rdfs:subClassOf rno:Street_partiotion.\
            ?st rdf:type rno:Street.\
            ?b rdf:type rno:Node; rno:is_extent_of ?x; rno:FID ?NFID.\
            ?x rno:builds ?ra.\
            ?ra rdf:type rno:Roundabout.\
            FILTER(NOT EXISTS {?a rno:builds ?ra}).\
            FILTER(NOT EXISTS {?st rdf:type rno:detailed_partition}).\
            FILTER(NOT EXISTS {?p rdf:type rno:Lane})}"
sparql.prepareQuery(query, initNs={"rno":rno})
for ref_roundaboutID, ref_roundaboutInfo in ref_roundabouts_dict.iteritems():
    print ref_roundaboutID, ref_roundaboutInfo
    ref_RaURI = ref_roundaboutInfo["URI"]
    print ref_RaURI
    ## ra_6

    ## rno is the name space rno = Namespae(http://www.semanticweb.org/ontologies/2015/3/RNO_V5042#)

    print rno+ref_RaURI
    ##http://www.semanticweb.org/ontologies/2015/3/RNO_V5042#ra_6
    ## This is the uri of the nameindividual in my ontology. 

    print rdflib.URIRef(rno+ref_RaURI)
    ##http://www.semanticweb.org/ontologies/2015/3/RNO_V5042#ra_6               

    ref_sectionInfo_around_RA=dict()
    results = ref_rdf.query(query, initNs={"rno":rno}, initBindings={'ra':URIRef(rno+ref_RaURI)})
    for result in results:
        sectionUri, linkUri, linkId, nodeUri, nodeId =result 

        print sectionUri, linkUri, linkId, nodeUri, nodeId 

但是,查询结果为空,我不知道代码有什么问题。我还检查过类似的问题,例如thisthis,但到目前为止还没有成功。

0 个答案:

没有答案