Skip to content

Instantly share code, notes, and snippets.

@lawlesst
Last active July 14, 2021 03:38
Show Gist options
  • Save lawlesst/9996cf3050c019a8d5ee to your computer and use it in GitHub Desktop.
Save lawlesst/9996cf3050c019a8d5ee to your computer and use it in GitHub Desktop.
Example code for working with Stardog from Python.
"""
Example code for connecting to Stardog (http://stardog.com/) with
Python's RDFLib (http://github.com/rdflib).
See longer description: http://lawlesst.github.io/notebook/rdflib-stardog.html
"""
from rdflib import Graph, Literal, URIRef
from rdflib.namespace import RDF, SKOS
from rdflib.plugins.stores import sparqlstore
#Define the Stardog store
endpoint = 'http://localhost:5820/demo/query'
store = sparqlstore.SPARQLUpdateStore()
store.open((endpoint, endpoint))
#Identify a named graph where we will be adding our instances.
default_graph = URIRef('http://example.org/default-graph')
ng = Graph(store, identifier=default_graph)
#Load our SKOS data from a file into an in-memory graph.
g = Graph()
g.parse('./sample-concepts.ttl', format='turtle')
#Serialize our named graph to make sure we got what we expect.
print g.serialize(format='turtle')
#Issue a SPARQL INSERT update query to add the assertions
#to Stardog.
ng.update(
u'INSERT DATA { %s }' % g.serialize(format='nt')
)
#Query the data using the RDFLib API.
#All concepts in the Stardog named graph.
for subj in ng.subjects(predicate=RDF.type, object=SKOS.Concept):
print 'Concept: ', subj
#Find concepts that are broader than others
for ob in ng.objects(predicate=SKOS.broader):
print 'Broader: ', ob
#Use RDFLib to issue SPARQL read queries.
#Bind a prefixe for SKOS so we can use it in our SPARQL queries
store.bind('skos', SKOS)
rq = """
SELECT ?s ?label
WHERE {
?s a skos:Concept ;
skos:preferredLabel ?label .
}
"""
for s, l in ng.query(rq):
print s.n3(), l.n3()
#Add a new assertion using the RDFLib API
soccer = URIRef('http://example.org/n1000')
ng.add((soccer, SKOS.altLabel, Literal('Football')))
#Read statements about soccer
for s, p, o in ng.triples((soccer, None, None)):
print s.n3(), p.n3(), o.n3()
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix skos: <http://www.w3.org/2004/02/skos/core#> .
@prefix xml: <http://www.w3.org/XML/1998/namespace> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
<http://example.org/n1234> a skos:Concept ;
skos:broader <http://example.org/n5678> ;
skos:preferredLabel "Baseball" .
<http://example.org/n5678> a skos:Concept ;
skos:preferredLabel "Sports" .
<http://example.org/n1000> a skos:Concept ;
skos:preferredLabel "Soccer" .
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment