RDFLib / rdflib

RDFLib is a Python library for working with RDF, a simple yet powerful language for representing information.
https://rdflib.readthedocs.org
BSD 3-Clause "New" or "Revised" License
2.16k stars 555 forks source link

Add easy way to serialize a graph to sparql INSERT DATA query for use by sparqlwrapper #1704

Open pulquero opened 2 years ago

pulquero commented 2 years ago

AFAICT, there is no simple way to use sparqlwrapper to insert an rdflib Graph object via query.

ghost commented 2 years ago

The examples below use the data from the test suite and roundtrip just fine afaict, I'll refine them and add them to the cookbook:

add graph contents to sparql endpoint's default graph:

g1 = Graph()
g1.parse(data=timblcardn3, format="n3")
updatequery = "\n".join([f"PREFIX {prefix}: {ns.n3()}" for prefix, ns in g1.namespaces()])
updatequery += f"\nINSERT DATA {{"
updatequery += " .\n".join([f"\t\t{s.n3()} {p.n3()} {o.n3()}" for (s, p, o) in g1.triples((None, None, None))])
updatequery += f" . \n\n}}\n"
# sanity check
g2 = Graph()
g2.update(updatequery)
assert len(g2) == len(g1)

Add graph and contents to sparql endpoint's dataset

g = Graph(identifier=URIRef("urn:example:timblcard"))
g.parse(data=timblcardn3, format="n3", publicID="https://www.w3.org/People/Berners-Lee/card#i")
updatequery = "\n".join([f"PREFIX {prefix}: {ns.n3()}" for prefix, ns in g.namespaces()])
updatequery += f"\nINSERT DATA {{\n\tGRAPH {g.identifier.n3()} {{\n"
updatequery += " .\n".join([f"\t\t{s.n3()} {p.n3()} {o.n3()}" for (s, p, o) in g.triples((None, None, None))])
updatequery += f" . \n\t }}\n}}\n"
# sanity check
ds = Dataset()
ds.update(updatequery)
assert g.identifier in list(ds.contexts())
assert len(ds.graph(g.identifier)) == len(g)

In both examples, for SPARQLWrapper UPDATE, it'd be sparql.setQuery(updatequery).

But in any case, such functionality seems more pertinent to SPARQLWrapper rather than RDFLib.