Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Example code for working with Stardog from Python.
Example code for connecting to Stardog ( with
Python's RDFLib (
See longer description:
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(), endpoint))
#Identify a named graph where we will be adding our instances.
default_graph = URIRef('')
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.
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
?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('')
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: <> .
@prefix rdfs: <> .
@prefix skos: <> .
@prefix xml: <> .
@prefix xsd: <> .
<> a skos:Concept ;
skos:broader <> ;
skos:preferredLabel "Baseball" .
<> a skos:Concept ;
skos:preferredLabel "Sports" .
<> a skos:Concept ;
skos:preferredLabel "Soccer" .
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment