Getting started with rdflib

Introduction to parsing RDF into rdflib graphs

Reading an NT file

RDF data has various syntaxes (xml, n3, ntriples, trix, etc) that you might want to read. The simplest format is ntriples. Create the file demo.nt in the current directory with these two lines:

<> \
<> \
<> .
<> \
<> \
"Hello world" .

In an interactive python interpreter, try this:

>>> from rdflib.graph import Graph
>>> g = Graph()
>>> g.parse("demo.nt", format="nt")
<Graph identifier=HCbubHJy0 (<class 'rdflib.graph.Graph'>)>
>>> len(g)
>>> import pprint
>>> for stmt in g:
...     pprint.pprint(stmt)
 rdflib.term.Literal(u'Hello world'))

The final lines show how rdflib represents the two statements in the file. The statements themselves are just length-3 tuples; and the subjects, predicates, and objects are all rdflib types.

Reading remote graphs

Reading graphs from the net is just as easy:

>>> g.parse("")
>>> len(g)

The format defaults to xml, which is the common format for .rdf files you’ll find on the net.

See also

Plugin parsers for rdflib

Introduction to using SPARQL to query an rdflib graph

Create an Rdflib Graph

You might parse some files into a new graph (Introduction to parsing RDF into rdflib graphs) or open an on-disk rdflib store.

from rdflib.graph import Graph
g = Graph()

LiveJournal produces FOAF data for their users, but they seem to use foaf:member_name for a person’s full name. For this demo, I made foaf:name act as a synonym for foaf:member_name (a poor man’s one-way owl:equivalentProperty):

from rdflib.namespace import Namespace
FOAF = Namespace("")
[g.add((s, FOAF['name'], n)) for s,_,n in g.triples((None, FOAF['member_name'], None))]

Run a Query

The rdflib package concentrates on providing the core RDF types and interfaces for working with RDF. As indicated in the introduction, the package defines a plugin interface (for parsers, stores, and serializers) that other packages can use to implement parsers, stores, and serializers that will plug into the rdflib package.

In order to perform SPARQL queries, you need to install the companion rdfextras package which includes a SPARQL plugin implementation:

$ easy_install rdfextras

In order to use the SPARQL plugin in your code, the plugin must first be registered. This binds the the imported SPARQL query processor implementation to the rdflib.graph.Graph.query() method, which can then be passed a SPARQL query (a string). When called, the query() method returns a SPARQLQuery object whose result attribute is a list of results.

Continuing the example...

import rdflib
from rdflib import plugin

    'sparql', rdflib.query.Processor,
    'rdfextras.sparql.processor', 'Processor')
    'sparql', rdflib.query.Result,
    'rdfextras.sparql.query', 'SPARQLQueryResult')

qres = g.query(
    """SELECT DISTINCT ?aname ?bname
       WHERE {
          ?a foaf:knows ?b .
          ?a foaf:name ?aname .
          ?b foaf:name ?bname .

for row in qres.result:
    print "%s knows %s" % row

The results are tuples of values in the same order as your SELECT arguments.

Timothy Berners-Lee knows Edd Dumbill
Timothy Berners-Lee knows Jennifer Golbeck
Timothy Berners-Lee knows Nicholas Gibbins
Timothy Berners-Lee knows Nigel Shadbolt
Dan Brickley knows binzac
Timothy Berners-Lee knows Eric Miller
Drew Perttula knows David McClosky
Timothy Berners-Lee knows Dan Connolly


The parse() initNs argument is a dictionary of namespaces to be expanded in the query string. In a large program, it is common to use the same dict for every single query. You might even hack your graph instance so that the initNs arg is already filled in.

In order to use an empty prefix (e.g. ?a :knows ?b), use a BASE directive in the SPARQL query to set a default namespace:



As with SQL queries, it is common to run the same SPARQL query many times with only a few terms changing each time. rdflib calls this initBindings:

FOAF = Namespace("")
ns = dict(foaf=FOAF)
drew = URIRef('')
for row in g.query("""SELECT ?name
                      WHERE { ?p foaf:name ?name }""",
                   initNs=ns, initBindings={'p' : drew}):
    print row


(rdflib.Literal('Drew Perttula', language=None, datatype=None),)

Store operations

Example code to create a Sleepycat (bsddb or bsddb3) triple store, add some triples, and serialize the resulting graph. Finally, close the graph and remove the database files that were created.

import rdflib
from rdflib.graph import ConjunctiveGraph as Graph
from rdflib import plugin
from import Store, NO_STORE, VALID_STORE
from rdflib.namespace import Namespace
from rdflib.term import Literal
from rdflib.term import URIRef
from tempfile import mkdtemp

default_graph_uri = ""
configString = "/var/tmp/rdfstore"

# Get the Sleepycat plugin.
store = plugin.get('Sleepycat', Store)('rdfstore')

# Open previously created store, or create it if it doesn't exist yet
graph = Graph(store="Sleepycat",
              identifier = URIRef(default_graph_uri))
path = mkdtemp()
rt =, create=False)
if rt == NO_STORE:
    # There is no underlying Sleepycat infrastructure, create it, create=True)
    assert rt == VALID_STORE, "The underlying store is corrupt"

print "Triples in graph before add: ", len(graph)

# Now we'll add some triples to the graph & commit the changes
rdflib = Namespace('')
graph.bind("test", "")

graph.add((rdflib['pic:1'], rdflib['name'], Literal('Jane & Bob')))
graph.add((rdflib['pic:2'], rdflib['name'], Literal('Squirrel in Tree')))

print "Triples in graph after add: ", len(graph)

# display the graph in RDF/XML
print graph.serialize()


# Clean up the mkdtemp spoor to remove the Sleepycat database files...
import os
for f in os.listdir(path):

The output will appear as follows:

Triples in graph before add:  0
Triples in graph after add:  2
<?xml version="1.0" encoding="UTF-8"?>
  <rdf:Description rdf:about="">
    <name>Jane &amp; Bob</name>
  <rdf:Description rdf:about="">
    <name>Squirrel in Tree</name>