An RDF Graph
The constructor accepts one argument, the ‘store’ that will be used to store the graph data (see the ‘store’ package for stores currently shipped with rdflib).
Stores can be context-aware or unaware. Unaware stores take up (some) less space but cannot support features that require context, such as true merging/demerging of sub-graphs and provenance.
The Graph constructor can take an identifier which identifies the Graph by name. If none is given, the graph is assigned a BNode for its identifier. For more on named graphs, see: http://www.w3.org/2004/03/trix/
Ontology for __str__ provenance terms:
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix : <http://rdflib.net/store#> .
@prefix rdfg: <http://www.w3.org/2004/03/trix/rdfg-1/>.
@prefix owl: <http://www.w3.org/2002/07/owl#>.
@prefix log: <http://www.w3.org/2000/10/swap/log#>.
@prefix xsd: <http://www.w3.org/2001/XMLSchema#>.
:Store a owl:Class;
rdfs:subClassOf <http://xmlns.com/wordnet/1.6/Electronic_database>;
rdfs:subClassOf
[a owl:Restriction;
owl:onProperty rdfs:label;
owl:allValuesFrom [a owl:DataRange;
owl:oneOf ("IOMemory"
"Sleepcat"
"MySQL"
"Redland"
"REGEXMatching"
"ZODB"
"AuditableStorage"
"Memory")]
].
:ConjunctiveGraph a owl:Class;
rdfs:subClassOf rdfg:Graph;
rdfs:label "The top-level graph within the store - the union of all the Graphs within."
rdfs:seeAlso <http://rdflib.net/rdf_store/#ConjunctiveGraph>.
:DefaultGraph a owl:Class;
rdfs:subClassOf rdfg:Graph;
rdfs:label "The 'default' subgraph of a conjunctive graph".
:identifier a owl:Datatypeproperty;
rdfs:label "The store-associated identifier of the formula. ".
rdfs:domain log:Formula
rdfs:range xsd:anyURI;
:storage a owl:ObjectProperty;
rdfs:domain [
a owl:Class;
owl:unionOf (log:Formula rdfg:Graph :ConjunctiveGraph)
];
rdfs:range :Store.
:default_context a owl:FunctionalProperty;
rdfs:label "The default context for a conjunctive graph";
rdfs:domain :ConjunctiveGraph;
rdfs:range :DefaultGraph.
{?cg a :ConjunctiveGraph;:storage ?store}
=> {?cg owl:sameAs ?store}.
{?subGraph rdfg:subGraphOf ?cg;a :DefaultGraph}
=> {?cg a :ConjunctiveGraph;:default_context ?subGraphOf} .
Turn uri into an absolute URI if it’s not one already
Add a triple with self as context
Add a sequence of triple with context
Bind prefix to namespace
If override is True will bind namespace to given prefix if namespace was already bound to a different prefix.
Close the graph store
Might be necessary for stores that require closing a connection to a database or releasing some resource.
Query for the RDFS.comment of the subject
Return default if no comment exists
Commits active transactions
Check if the Graph is connected
The Graph is considered undirectional.
Performs a search on the Graph, starting from a random node. Then iteratively goes depth-first through the triplets where the node is subject and object. Return True if all nodes have been visited and False if it cannot continue and there are still unvisited nodes left.
Destroy the store identified by configuration if supported
Generator over all items in the resource specified by list
list is an RDF collection.
Query for the RDFS.label of the subject
Return default if no label exists
return an n3 identifier for the Graph
Generator over all the prefix, namespace tuples
A generator of objects with the given subject and predicate
Open the graph store
Might be necessary for stores that require opening a connection to a database or acquiring some resource.
Parse source adding the resulting triples to the Graph.
The source is specified using one of source, location, file or data.
| Parameters : |
|
|---|---|
| Returns : |
|
Examples:
>>> my_data = '''
... <rdf:RDF
... xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'
... xmlns:rdfs='http://www.w3.org/2000/01/rdf-schema#'
... >
... <rdf:Description>
... <rdfs:label>Example</rdfs:label>
... <rdfs:comment>This is really just an example.</rdfs:comment>
... </rdf:Description>
... </rdf:RDF>
... '''
>>> import tempfile
>>> fd, file_name = tempfile.mkstemp()
>>> f = os.fdopen(fd, 'w')
>>> dummy = f.write(my_data) # Returns num bytes written on py3
>>> f.close()
>>> g = Graph()
>>> result = g.parse(data=my_data, format="application/rdf+xml")
>>> len(g)
2
>>> g = Graph()
>>> result = g.parse(location=file_name, format="application/rdf+xml")
>>> len(g)
2
>>> g = Graph()
>>> result = g.parse(file=open(file_name, "r"), format="application/rdf+xml")
>>> len(g)
2
>>> os.remove(file_name)
A generator of (predicate, object) tuples for the given subject
A generator of predicates with the given subject and object
Find the preferred label for subject.
By default prefers skos:prefLabels over rdfs:labels. In case at least one prefLabel is found returns those, else returns labels. In case a language string (e.g., ‘en’, ‘de’ or even ‘’ for no lang-tagged literals) is given, only such labels will be considered.
Return a list of (labelProp, label) pairs, where labelProp is either skos:prefLabel or rdfs:label.
>>> g = ConjunctiveGraph()
>>> u = URIRef(u'http://example.com/foo')
>>> g.add([u, RDFS.label, Literal('foo')])
>>> g.add([u, RDFS.label, Literal('bar')])
>>> sorted(g.preferredLabel(u))
[(rdflib.term.URIRef(u'http://www.w3.org/2000/01/rdf-schema#label'),
rdflib.term.Literal(u'bar')),
(rdflib.term.URIRef(u'http://www.w3.org/2000/01/rdf-schema#label'),
rdflib.term.Literal(u'foo'))]
>>> g.add([u, SKOS.prefLabel, Literal('bla')])
>>> g.preferredLabel(u)
[(rdflib.term.URIRef(u'http://www.w3.org/2004/02/skos/core#prefLabel'),
rdflib.term.Literal(u'bla'))]
>>> g.add([u, SKOS.prefLabel, Literal('blubb', lang='en')])
>>> sorted(g.preferredLabel(u))
[(rdflib.term.URIRef(u'http://www.w3.org/2004/02/skos/core#prefLabel'),
rdflib.term.Literal(u'blubb', lang='en')),
(rdflib.term.URIRef(u'http://www.w3.org/2004/02/skos/core#prefLabel'),
rdflib.term.Literal(u'bla'))]
>>> g.preferredLabel(u, lang='')
[(rdflib.term.URIRef(u'http://www.w3.org/2004/02/skos/core#prefLabel'),
rdflib.term.Literal(u'bla'))]
>>> g.preferredLabel(u, lang='en')
[(rdflib.term.URIRef(u'http://www.w3.org/2004/02/skos/core#prefLabel'),
rdflib.term.Literal(u'blubb', lang='en'))]
Remove a triple from the graph
If the triple does not provide a context attribute, removes the triple from all contexts.
Create a new Resource instance.
Parameters:
Example:
>>> graph = Graph()
>>> uri = URIRef("http://example.org/resource")
>>> resource = graph.resource(uri)
>>> assert isinstance(resource, Resource)
>>> assert resource.identifier is uri
>>> assert resource.graph is graph
Rollback active transactions
Check if subject is an rdf:Seq
If yes, it returns a Seq class instance, None otherwise.
Serialize the Graph to destination
If destination is None serialize method returns the serialization as a string. Format defaults to xml (AKA rdf/xml).
Format support can be extended with plugins, but ‘xml’, ‘n3’, ‘turtle’, ‘nt’, ‘pretty-xml’, trix’ are built in.
Convenience method to update the value of object
Remove any existing triples for subject and predicate before adding (subject, predicate, object).
A generator of (subject, object) tuples for the given predicate
A generator of (subject, predicate) tuples for the given object
A generator of subjects with the given predicate and object
Generates transitive closure of a user-defined function against the graph
>>> from rdflib.collection import Collection
>>> g=Graph()
>>> a=BNode('foo')
>>> b=BNode('bar')
>>> c=BNode('baz')
>>> g.add((a,RDF.first,RDF.type))
>>> g.add((a,RDF.rest,b))
>>> g.add((b,RDF.first,RDFS.label))
>>> g.add((b,RDF.rest,c))
>>> g.add((c,RDF.first,RDFS.comment))
>>> g.add((c,RDF.rest,RDF.nil))
>>> def topList(node,g):
... for s in g.subjects(RDF.rest,node):
... yield s
>>> def reverseList(node,g):
... for f in g.objects(node,RDF.first):
... print(f)
... for s in g.subjects(RDF.rest,node):
... yield s
>>> [rt for rt in g.transitiveClosure(topList,RDF.nil)]
[rdflib.term.BNode('baz'), rdflib.term.BNode('bar'), rdflib.term.BNode('foo')]
>>> [rt for rt in g.transitiveClosure(reverseList,RDF.nil)]
http://www.w3.org/2000/01/rdf-schema#comment
http://www.w3.org/2000/01/rdf-schema#label
http://www.w3.org/1999/02/22-rdf-syntax-ns#type
[rdflib.term.BNode('baz'), rdflib.term.BNode('bar'), rdflib.term.BNode('foo')]
Transitively generate objects for the property relationship
Generated objects belong to the depth first transitive closure of the property relationship starting at subject.
Transitively generate objects for the property relationship
Generated objects belong to the depth first transitive closure of the property relationship starting at subject.
Generator over the triple store
Returns triples that match the given triple pattern. If triple pattern does not provide a context, all contexts will be searched.
Get a value for a pair of two criteria
Exactly one of subject, predicate, object must be None. Useful if one knows that there may only be one value.
It is one of those situations that occur a lot, hence this ‘macro’ like utility
Parameters: subject, predicate, object – exactly one must be None default – value to be returned if no values found any – if True, return any value in the case there is more than one, else, raise UniquenessError
A ConjunctiveGraph is an (unamed) aggregation of all the named graphs within the Store. It has a default graph, whose name is associated with the ConjunctiveGraph throughout its life. All methods work against this default graph. Its constructor can take an identifier to use as the name of this default graph or it will assign a BNode.
In practice, it is typical to instantiate a ConjunctiveGraph if you want to add triples to the Store but don’t care to mint a URI for the graph. Any triples in the graph can still be addressed.
Instantiating Graphs with default store (IOMemory) and default identifier (a BNode):
>>> g = Graph()
>>> g.store.__class__
<class 'rdflib.plugins.memory.IOMemory'>
>>> g.identifier.__class__
<class 'rdflib.term.BNode'>
Instantiating Graphs with a specific kind of store (IOMemory) and a default identifier (a BNode):
Other store kinds: Sleepycat, MySQL, SQLite
>>> store = plugin.get('IOMemory', Store)()
>>> store.__class__.__name__
'IOMemory'
>>> graph = Graph(store)
>>> graph.store.__class__
<class 'rdflib.plugins.memory.IOMemory'>
Instantiating Graphs with Sleepycat store and an identifier - <http://rdflib.net>:
>>> g = Graph('IOMemory', URIRef("http://rdflib.net"))
>>> g.identifier
rdflib.term.URIRef(u'http://rdflib.net')
>>> str(g)
"<http://rdflib.net> a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'IOMemory']."
Creating a ConjunctiveGraph - The top level container for all named Graphs in a ‘database’:
>>> g = ConjunctiveGraph()
>>> str(g.default_context)
"[a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'IOMemory']]."
Adding / removing reified triples to Graph and iterating over it directly or via triple pattern:
>>> g = Graph('IOMemory')
>>> statementId = BNode()
>>> print(len(g))
0
>>> g.add((statementId, RDF.type, RDF.Statement))
>>> g.add((statementId, RDF.subject, URIRef(u'http://rdflib.net/store/ConjunctiveGraph')))
>>> g.add((statementId, RDF.predicate, RDFS.label))
>>> g.add((statementId, RDF.object, Literal("Conjunctive Graph")))
>>> print(len(g))
4
>>> for s, p, o in g:
... print(type(s))
...
<class 'rdflib.term.BNode'>
<class 'rdflib.term.BNode'>
<class 'rdflib.term.BNode'>
<class 'rdflib.term.BNode'>
>>> for s, p, o in g.triples((None, RDF.object, None)):
... print(o)
...
Conjunctive Graph
>>> g.remove((statementId, RDF.type, RDF.Statement))
>>> print(len(g))
3
None terms in calls to triples() can be thought of as “open variables”.
Graph Aggregation - ConjunctiveGraphs and ReadOnlyGraphAggregate within the same store:
>>> store = plugin.get('IOMemory', Store)()
>>> g1 = Graph(store)
>>> g2 = Graph(store)
>>> g3 = Graph(store)
>>> stmt1 = BNode()
>>> stmt2 = BNode()
>>> stmt3 = BNode()
>>> g1.add((stmt1, RDF.type, RDF.Statement))
>>> g1.add((stmt1, RDF.subject, URIRef(u'http://rdflib.net/store/ConjunctiveGraph')))
>>> g1.add((stmt1, RDF.predicate, RDFS.label))
>>> g1.add((stmt1, RDF.object, Literal("Conjunctive Graph")))
>>> g2.add((stmt2, RDF.type, RDF.Statement))
>>> g2.add((stmt2, RDF.subject, URIRef(u'http://rdflib.net/store/ConjunctiveGraph')))
>>> g2.add((stmt2, RDF.predicate, RDF.type))
>>> g2.add((stmt2, RDF.object, RDFS.Class))
>>> g3.add((stmt3, RDF.type, RDF.Statement))
>>> g3.add((stmt3, RDF.subject, URIRef(u'http://rdflib.net/store/ConjunctiveGraph')))
>>> g3.add((stmt3, RDF.predicate, RDFS.comment))
>>> g3.add((stmt3, RDF.object, Literal("The top-level aggregate graph - The sum of all named graphs within a Store")))
>>> len(list(ConjunctiveGraph(store).subjects(RDF.type, RDF.Statement)))
3
>>> len(list(ReadOnlyGraphAggregate([g1,g2]).subjects(RDF.type, RDF.Statement)))
2
ConjunctiveGraphs have a quads() method which returns quads instead of triples, where the fourth item is the Graph (or subclass thereof) instance in which the triple was asserted:
>>> uniqueGraphNames = set([graph.identifier for s, p, o, graph in ConjunctiveGraph(store).quads((None, RDF.predicate, None))])
>>> len(uniqueGraphNames)
3
>>> unionGraph = ReadOnlyGraphAggregate([g1, g2])
>>> uniqueGraphNames = set([graph.identifier for s, p, o, graph in unionGraph.quads((None, RDF.predicate, None))])
>>> len(uniqueGraphNames)
2
Parsing N3 from StringIO
>>> from StringIO import StringIO
>>> g2 = Graph()
>>> src = '''
... @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
... @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
... [ a rdf:Statement ;
... rdf:subject <http://rdflib.net/store#ConjunctiveGraph>;
... rdf:predicate rdfs:label;
... rdf:object "Conjunctive Graph" ] .
... '''
>>> g2 = g2.parse(StringIO(src), format='n3')
>>> print(len(g2))
4
Using Namespace class:
>>> RDFLib = Namespace('http://rdflib.net')
>>> RDFLib.ConjunctiveGraph
rdflib.term.URIRef(u'http://rdflib.netConjunctiveGraph')
>>> RDFLib['Graph']
rdflib.term.URIRef(u'http://rdflib.netGraph')