How to iterate over CONSTRUCT output from rdflib?

独自空忆成欢 提交于 2020-01-07 03:05:28

问题


This is a follow-up question from How to prevent triples from getting mixed up while uploading to Dydra programmatically?

I've created a new graph using SPARQL CONSTRUCT query. I now want to iterate over it so that I can add the statements to an RDFlib graph and then insert the data into another triplestore. I have the following questions:

  1. If SPARQL CONSTRUCT returns a graph, do I still need to iterate over the statements and add them to an RDFlib graph? I probably need to do so to be able to insert each triple into a triplestore using a loop.
  2. How does one iterate over a graph resulting from SPARQL CONSTRUCT to retrieve the triples? The 'type' of 'output' shows up as string.

This is my code:

sesameSparqlEndpoint = 'http://my.ip.ad.here:8080/openrdf-sesame/repositories/rep_name'
sparql = SPARQLWrapper(sesameSparqlEndpoint)
queryStringDownload = 'CONSTRUCT {?s ?p ?o} WHERE {?s ?p ?o FILTER REGEX(str(?s), "http")}'
dataGraph = Graph()

sparql.setQuery(queryStringDownload)
sparql.method = 'GET'
sparql.setReturnFormat(JSON)
output = sparql.query().convert()
# print output

#Print all statements in dataGraph      
for stmt in output:
    print stmt

This code just gives me a single column of characters from the triples.


回答1:


  1. I still had to add statements from the Conjunctive Graph created as a result of running the CONSTRUCT query to an RDFlib graph. Why? Because there were issues with parsing the former when doing INSERT. The output of CONSTRUCT query: a) Doesn't have the URIs enclosed within <> b) Doesn't handle non-ASCII characters (hence output.encode('utf-8') is needed).
  2. To retrieve the triples from the graph generated from the CONSTRUCT query, we need to use XML format for output instead of JSON in the code above.

Interesting aside: The type(output) when using XML is Conjunctive Graph. For everything else I tried, it's a string.



来源:https://stackoverflow.com/questions/34425876/how-to-iterate-over-construct-output-from-rdflib

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