1

I am trying to construct a graph out of the results from SPARQL query. For the purpose of the query construction, I'm using SparqlWrapper and DBpedia as the knowledge base.

from SPARQLWrapper import SPARQLWrapper, JSON
from rdflib import Namespace, Graph, URIRef
from rdflib.namespace import RDF, FOAF
g = Graph()
name = "Asturias"
#labelName = URIRef("<http://dbpedia.org/resource/" + name +">")

sparql = SPARQLWrapper("http://dbpedia.org/sparql")
sparql.setQuery("""
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX dbr:  <http://dbpedia.org/resource/>
    SELECT *
    WHERE { dbr:Asturias ?predicate ?object }
""")
sparql.setReturnFormat(JSON)
results = sparql.query().convert()

for result in results["results"]["bindings"]:
        predicate = result["predicate"]["value"]
        object = result["object"]["value"]
        print(name , predicate , object)
        g.add((name, predicate, object))

print(len(g))
g.serialize(destination='./resources/testg.n3', format='n3')

This outputs

http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.w3.org/2002/07/owl#Thing

and lot more results, but I'm looking for a way to construct a graph from the results, for it to be merged with existing graphs/'s.

This throws me an error as

in add
    "Predicate %s must be an rdflib term" % (p,)
AssertionError: Predicate http://www.w3.org/1999/02/22-rdf-syntax-ns#type must be an rdflib term

The problem is the output JSON's value is something like this Link

Betafish
  • 1,212
  • 3
  • 20
  • 45
  • The error message should be clear enough. You have to create the RDF terms out of the string values: https://rdflib.readthedocs.io/en/stable/rdf_terms.html and https://rdflib.readthedocs.io/en/stable/intro_to_creating_rdf.html – UninformedUser Oct 23 '19 at 09:24
  • 3
    Indeed, the better option would be to use a SPARQL `CONSTRUCT` query which in fact returns a set of triples – UninformedUser Oct 23 '19 at 09:26

0 Answers0