""" 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()