graph
RDFLib defines the following kinds of Graphs:
Graph
An RDF graph is a set of RDF triples. Graphs support the python in
operator, as well as iteration and some operations like union,
difference and intersection.
See Graph
Conjunctive Graph
Deprecation notice
ConjunctiveGraph is deprecated, use Dataset instead.
A Conjunctive Graph is the most relevant collection of graphs that are
considered to be the boundary for closed world assumptions. This
boundary is equivalent to that of the store instance (which is itself
uniquely identified and distinct from other instances of
Store that signify other Conjunctive Graphs). It is
equivalent to all the named graphs within it and associated with a
_default_ graph which is automatically assigned a
BNode for an identifier - if one isn’t given.
See ConjunctiveGraph
Quoted graph
The notion of an RDF graph [14] is extended to include the concept of a formula node. A formula node may occur wherever any other kind of node can appear. Associated with a formula node is an RDF graph that is completely disjoint from all other graphs; i.e. has no nodes in common with any other graph. (It may contain the same labels as other RDF graphs; because this is, by definition, a separate graph, considerations of tidiness do not apply between the graph at a formula node and any other graph.)
This is intended to map the idea of “{ N3-expression }” that is used by N3 into an RDF graph upon which RDF semantics is defined.
See QuotedGraph
Dataset
The RDF 1.1 Dataset, a small extension to the Conjunctive Graph. The primary term is “graphs in the datasets” and not “contexts with quads” so there is a separate method to set/retrieve a graph in a dataset and to operate with dataset graphs. As a consequence of this approach, dataset graphs cannot be identified with blank nodes, a name is always required (RDFLib will automatically add a name if one is not provided at creation time). This implementation includes a convenience method to directly add a single quad to a dataset graph.
See Dataset
Working with graphs
Instantiating Graphs with default store (Memory) and default identifier (a BNode):
>>> g = Graph()
>>> g.store.__class__
<class 'rdflib.plugins.stores.memory.Memory'>
>>> g.identifier.__class__
<class 'rdflib.term.BNode'>
Instantiating Graphs with a Memory store and an identifier - https://rdflib.github.io:
>>> g = Graph('Memory', URIRef("https://rdflib.github.io"))
>>> g.identifier
rdflib.term.URIRef('https://rdflib.github.io')
>>> str(g) # doctest: +NORMALIZE_WHITESPACE
"<https://rdflib.github.io> a rdfg:Graph;rdflib:storage
[a rdflib:Store;rdfs:label 'Memory']."
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 'Memory']]."
Adding / removing reified triples to Graph and iterating over it directly or via triple pattern:
>>> g = Graph()
>>> statementId = BNode()
>>> print(len(g))
0
>>> g.add((statementId, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((statementId, RDF.subject,
... URIRef("https://rdflib.github.io/store/ConjunctiveGraph"))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((statementId, RDF.predicate, namespace.RDFS.label)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((statementId, RDF.object, Literal("Conjunctive Graph"))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.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)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> print(len(g))
3
None terms in calls to triples() can be
thought of as “open variables”.
Graph support set-theoretic operators, you can add/subtract graphs, as well as intersection (with multiplication operator g1*g2) and xor (g1 ^ g2).
Note that BNode IDs are kept when doing set-theoretic operations, this may or may not be what you want. Two named graphs within the same application probably want share BNode IDs, two graphs with data from different sources probably not. If your BNode IDs are all generated by RDFLib they are UUIDs and unique.
>>> g1 = Graph()
>>> g2 = Graph()
>>> u = URIRef("http://example.com/foo")
>>> g1.add([u, namespace.RDFS.label, Literal("foo")]) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g1.add([u, namespace.RDFS.label, Literal("bar")]) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add([u, namespace.RDFS.label, Literal("foo")]) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add([u, namespace.RDFS.label, Literal("bing")]) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> len(g1 + g2) # adds bing as label
3
>>> len(g1 - g2) # removes foo
1
>>> len(g1 * g2) # only foo
1
>>> g1 += g2 # now g1 contains everything
Graph Aggregation - ConjunctiveGraphs and ReadOnlyGraphAggregate within the same store:
>>> store = plugin.get("Memory", Store)()
>>> g1 = Graph(store)
>>> g2 = Graph(store)
>>> g3 = Graph(store)
>>> stmt1 = BNode()
>>> stmt2 = BNode()
>>> stmt3 = BNode()
>>> g1.add((stmt1, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g1.add((stmt1, RDF.subject,
... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g1.add((stmt1, RDF.predicate, namespace.RDFS.label)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g1.add((stmt1, RDF.object, Literal('Conjunctive Graph'))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add((stmt2, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add((stmt2, RDF.subject,
... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add((stmt2, RDF.predicate, RDF.type)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add((stmt2, RDF.object, namespace.RDFS.Class)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g3.add((stmt3, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g3.add((stmt3, RDF.subject,
... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g3.add((stmt3, RDF.predicate, namespace.RDFS.comment)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g3.add((stmt3, RDF.object, Literal(
... 'The top-level aggregate graph - The sum ' +
... 'of all named graphs within a Store'))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> 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 a string:
>>> 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 <https://rdflib.github.io/store#ConjunctiveGraph>;
... rdf:predicate rdfs:label;
... rdf:object "Conjunctive Graph" ] .
... '''
>>> g2 = g2.parse(data=src, format="n3")
>>> print(len(g2))
4
Using Namespace class:
>>> RDFLib = Namespace("https://rdflib.github.io/")
>>> RDFLib.ConjunctiveGraph
rdflib.term.URIRef('https://rdflib.github.io/ConjunctiveGraph')
>>> RDFLib["Graph"]
rdflib.term.URIRef('https://rdflib.github.io/Graph')
Classes:
-
BatchAddGraph–Wrapper around graph that turns batches of calls to Graph’s add
-
ConjunctiveGraph–A ConjunctiveGraph is an (unnamed) aggregation of all the named
-
Dataset–An RDFLib Dataset is an object that stores multiple Named Graphs - instances of
-
Graph–An RDF Graph: a Python object containing nodes and relations between them as
-
ModificationException– -
QuotedGraph–Quoted Graphs are intended to implement Notation 3 formulae. They are
-
ReadOnlyGraphAggregate–Utility class for treating a set of graphs as a single graph
-
Seq–Wrapper around an RDF Seq resource
-
UnSupportedAggregateOperation–
__all__
module-attribute
__all__ = ['Graph', 'ConjunctiveGraph', 'QuotedGraph', 'Seq', 'ModificationException', 'Dataset', 'UnSupportedAggregateOperation', 'ReadOnlyGraphAggregate', 'BatchAddGraph', '_ConjunctiveGraphT', '_ContextIdentifierType', '_DatasetT', '_GraphT', '_ObjectType', '_OptionalIdentifiedQuadType', '_OptionalQuadType', '_PredicateType', '_QuadPathPatternType', '_QuadPatternType', '_QuadSelectorType', '_QuadType', '_SubjectType', '_TripleOrOptionalQuadType', '_TripleOrTriplePathType', '_TripleOrQuadPathPatternType', '_TripleOrQuadPatternType', '_TripleOrQuadSelectorType', '_TriplePathPatternType', '_TriplePathType', '_TriplePatternType', '_TripleSelectorType', '_TripleType']
BatchAddGraph
BatchAddGraph(graph: Graph, batch_size: int = 1000, batch_addn: bool = False)
Wrapper around graph that turns batches of calls to Graph’s add (and optionally, addN) into calls to batched calls to addN`.
Parameters:
-
(graphGraph) –The graph to wrap
-
(batch_sizeint, default:1000) –The maximum number of triples to buffer before passing to Graph’s addN
-
(batch_addnbool, default:False) –If True, then even calls to
addNwill be batched according to batch_size
Attributes:
-
graph–The wrapped graph
-
count–The number of triples buffered since initialization or the last call to reset
-
batch–The current buffer of triples
Methods:
-
__enter__– -
__exit__– -
add–Add a triple to the buffer.
-
addN– -
reset–Manually clear the buffered triples and reset the count to zero
Attributes:
-
graph–
Source code in rdflib/graph.py
__enter__
__enter__() -> BatchAddGraph
__exit__
add
add(triple_or_quad: Union[_TripleType, _QuadType]) -> BatchAddGraph
Add a triple to the buffer.
Parameters:
-
(triple_or_quadUnion[_TripleType, _QuadType]) –The triple or quad to add
Returns:
-
BatchAddGraph–The BatchAddGraph instance
Source code in rdflib/graph.py
addN
addN(quads: Iterable[_QuadType]) -> BatchAddGraph
reset
reset() -> BatchAddGraph
ConjunctiveGraph
ConjunctiveGraph(store: Union[Store, str] = 'default', identifier: Optional[Union[IdentifiedNode, str]] = None, default_graph_base: Optional[str] = None)
Bases: Graph
A ConjunctiveGraph is an (unnamed) aggregation of all the named graphs in a store.
Deprecation notice
ConjunctiveGraph is deprecated, use rdflib.graph.Dataset instead.
It has a default graph, whose name is associated with the
graph throughout its life. Constructor can take an identifier
to use as the name of this default graph or it will assign a
BNode.
All methods that add triples work against this default graph.
All queries are carried out against the union of all graphs.
Methods:
-
__contains__–Support for ‘triple/quad in graph’ syntax
-
__len__–Number of triples in the entire conjunctive graph
-
__reduce__– -
__str__– -
add–Add a triple or quad to the store.
-
addN–Add a sequence of triples with context
-
context_id–URI#context
-
contexts–Iterate over all contexts in the graph
-
get_context–Return a context graph for the given identifier
-
get_graph–Returns the graph identified by given identifier
-
parse–Parse source adding the resulting triples to its own context (sub graph
-
quads–Iterate over all the quads in the entire conjunctive graph
-
remove–Removes a triple or quads
-
remove_context–Removes the given context from the graph
-
triples–Iterate over all the triples in the entire conjunctive graph
-
triples_choices–Iterate over all the triples in the entire conjunctive graph
Attributes:
Source code in rdflib/graph.py
__contains__
Support for ‘triple/quad in graph’ syntax
__len__
__reduce__
__str__
add
Add a triple or quad to the store.
if a triple is given it is added to the default context
Source code in rdflib/graph.py
addN
Add a sequence of triples with context
Source code in rdflib/graph.py
context_id
context_id(uri: str, context_id: Optional[str] = None) -> URIRef
contexts
Iterate over all contexts in the graph
If triple is specified, iterate over all contexts the triple is in.
Source code in rdflib/graph.py
get_context
get_context(identifier: Optional[Union[_ContextIdentifierType, str]], quoted: bool = False, base: Optional[str] = None) -> Graph
Return a context graph for the given identifier
identifier must be a URIRef or BNode.
Source code in rdflib/graph.py
get_graph
get_graph(identifier: _ContextIdentifierType) -> Union[Graph, None]
parse
parse(source: Optional[Union[IO[bytes], TextIO, InputSource, str, bytes, PurePath]] = None, publicID: Optional[str] = None, format: Optional[str] = None, location: Optional[str] = None, file: Optional[Union[BinaryIO, TextIO]] = None, data: Optional[Union[str, bytes]] = None, **args: Any) -> Graph
Parse source adding the resulting triples to its own context (sub graph of this graph).
See rdflib.graph.Graph.parse for documentation on arguments.
Parameters:
-
(sourceOptional[Union[IO[bytes], TextIO, InputSource, str, bytes, PurePath]], default:None) –The source to parse
-
(publicIDOptional[str], default:None) –The public ID of the source
-
(formatOptional[str], default:None) –The format of the source
-
(locationOptional[str], default:None) –The location of the source
-
(fileOptional[Union[BinaryIO, TextIO]], default:None) –The file object to parse
-
(dataOptional[Union[str, bytes]], default:None) –The data to parse
-
(**argsAny, default:{}) –Additional arguments
Returns:
-
Graph–The graph into which the source was parsed. In the case of n3 it returns
-
Graph–the root context.
Note
If the source is in a format that does not support named graphs its triples will be added to the default graph (i.e. ConjunctiveGraph.default_context).
Caution
This method can access directly or indirectly requested network or
file resources, for example, when parsing JSON-LD documents with
@context directives that point to a network location.
When processing untrusted or potentially malicious documents, measures should be taken to restrict network and file access.
For information on available security measures, see the RDFLib Security Considerations documentation.
Changed in 7.0
The publicID argument is no longer used as the identifier (i.e. name)
of the default graph as was the case before version 7.0. In the case of
sources that do not support named graphs, the publicID parameter will
also not be used as the name for the graph that the data is loaded into,
and instead the triples from sources that do not support named graphs will
be loaded into the default graph (i.e. ConjunctiveGraph.default_context).
Source code in rdflib/graph.py
2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 | |
quads
quads(triple_or_quad: Optional[_TripleOrQuadPatternType] = None) -> Generator[_OptionalQuadType, None, None]
Iterate over all the quads in the entire conjunctive graph
Source code in rdflib/graph.py
remove
Removes a triple or quads
if a triple is given it is removed from all contexts a quad is removed from the given context only
Source code in rdflib/graph.py
remove_context
triples
triples(triple_or_quad: _TripleOrQuadPatternType, context: Optional[_ContextType] = ...) -> Generator[_TripleType, None, None]
triples(triple_or_quad: _TripleOrQuadSelectorType, context: Optional[_ContextType] = None) -> Generator[_TripleOrTriplePathType, None, None]
Iterate over all the triples in the entire conjunctive graph
For legacy reasons, this can take the context to query either as a fourth element of the quad, or as the explicit context keyword parameter. The kw param takes precedence.
Source code in rdflib/graph.py
triples_choices
triples_choices(triple: _TripleChoiceType, context: Optional[_ContextType] = None) -> Generator[_TripleType, None, None]
Iterate over all the triples in the entire conjunctive graph
Source code in rdflib/graph.py
Dataset
Dataset(store: Union[Store, str] = 'default', default_union: bool = False, default_graph_base: Optional[str] = None)
Bases: ConjunctiveGraph
An RDFLib Dataset is an object that stores multiple Named Graphs - instances of RDFLib Graph identified by IRI - within it and allows whole-of-dataset or single Graph use.
RDFLib’s Dataset class is based on the RDF 1.2. ‘Dataset’ definition:
An RDF dataset is a collection of RDF graphs, and comprises:
- Exactly one default graph, being an RDF graph. The default graph does not have a name and MAY be empty.
- Zero or more named graphs. Each named graph is a pair consisting of an IRI or a blank node (the graph name), and an RDF graph. Graph names are unique within an RDF dataset.
Accordingly, a Dataset allows for Graph objects to be added to it with
URIRef or BNode identifiers and always
creats a default graph with the URIRef identifier
urn:x-rdflib:default.
Dataset extends Graph’s Subject, Predicate, Object (s, p, o) ‘triple’ structure to include a graph identifier - archaically called Context - producing ‘quads’ of s, p, o, g.
Triples, or quads, can be added to a Dataset. Triples, or quads with the graph
identifer :code:urn:x-rdflib:default go into the default graph.
Deprecation notice
Dataset builds on the ConjunctiveGraph class but that class’s direct
use is now deprecated (since RDFLib 7.x) and it should not be used.
ConjunctiveGraph will be removed from future RDFLib versions.
Examples of usage and see also the examples/datast.py file:
>>> # Create a new Dataset
>>> ds = Dataset()
>>> # simple triples goes to default graph
>>> ds.add((
... URIRef("http://example.org/a"),
... URIRef("http://www.example.org/b"),
... Literal("foo")
... )) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Dataset'>)>
>>> # Create a graph in the dataset, if the graph name has already been
>>> # used, the corresponding graph will be returned
>>> # (ie, the Dataset keeps track of the constituent graphs)
>>> g = ds.graph(URIRef("http://www.example.com/gr"))
>>> # add triples to the new graph as usual
>>> g.add((
... URIRef("http://example.org/x"),
... URIRef("http://example.org/y"),
... Literal("bar")
... )) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> # alternatively: add a quad to the dataset -> goes to the graph
>>> ds.add((
... URIRef("http://example.org/x"),
... URIRef("http://example.org/z"),
... Literal("foo-bar"),
... g
... )) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Dataset'>)>
>>> # querying triples return them all regardless of the graph
>>> for t in ds.triples((None,None,None)): # doctest: +SKIP
... print(t) # doctest: +NORMALIZE_WHITESPACE
(rdflib.term.URIRef("http://example.org/a"),
rdflib.term.URIRef("http://www.example.org/b"),
rdflib.term.Literal("foo"))
(rdflib.term.URIRef("http://example.org/x"),
rdflib.term.URIRef("http://example.org/z"),
rdflib.term.Literal("foo-bar"))
(rdflib.term.URIRef("http://example.org/x"),
rdflib.term.URIRef("http://example.org/y"),
rdflib.term.Literal("bar"))
>>> # querying quads() return quads; the fourth argument can be unrestricted
>>> # (None) or restricted to a graph
>>> for q in ds.quads((None, None, None, None)): # doctest: +SKIP
... print(q) # doctest: +NORMALIZE_WHITESPACE
(rdflib.term.URIRef("http://example.org/a"),
rdflib.term.URIRef("http://www.example.org/b"),
rdflib.term.Literal("foo"),
None)
(rdflib.term.URIRef("http://example.org/x"),
rdflib.term.URIRef("http://example.org/y"),
rdflib.term.Literal("bar"),
rdflib.term.URIRef("http://www.example.com/gr"))
(rdflib.term.URIRef("http://example.org/x"),
rdflib.term.URIRef("http://example.org/z"),
rdflib.term.Literal("foo-bar"),
rdflib.term.URIRef("http://www.example.com/gr"))
>>> # unrestricted looping is equivalent to iterating over the entire Dataset
>>> for q in ds: # doctest: +SKIP
... print(q) # doctest: +NORMALIZE_WHITESPACE
(rdflib.term.URIRef("http://example.org/a"),
rdflib.term.URIRef("http://www.example.org/b"),
rdflib.term.Literal("foo"),
None)
(rdflib.term.URIRef("http://example.org/x"),
rdflib.term.URIRef("http://example.org/y"),
rdflib.term.Literal("bar"),
rdflib.term.URIRef("http://www.example.com/gr"))
(rdflib.term.URIRef("http://example.org/x"),
rdflib.term.URIRef("http://example.org/z"),
rdflib.term.Literal("foo-bar"),
rdflib.term.URIRef("http://www.example.com/gr"))
>>> # resticting iteration to a graph:
>>> for q in ds.quads((None, None, None, g)): # doctest: +SKIP
... print(q) # doctest: +NORMALIZE_WHITESPACE
(rdflib.term.URIRef("http://example.org/x"),
rdflib.term.URIRef("http://example.org/y"),
rdflib.term.Literal("bar"),
rdflib.term.URIRef("http://www.example.com/gr"))
(rdflib.term.URIRef("http://example.org/x"),
rdflib.term.URIRef("http://example.org/z"),
rdflib.term.Literal("foo-bar"),
rdflib.term.URIRef("http://www.example.com/gr"))
>>> # Note that in the call above -
>>> # ds.quads((None,None,None,"http://www.example.com/gr"))
>>> # would have been accepted, too
>>> # graph names in the dataset can be queried:
>>> for c in ds.graphs(): # doctest: +SKIP
... print(c.identifier) # doctest:
urn:x-rdflib:default
http://www.example.com/gr
>>> # A graph can be created without specifying a name; a skolemized genid
>>> # is created on the fly
>>> h = ds.graph()
>>> for c in ds.graphs(): # doctest: +SKIP
... print(c) # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
DEFAULT
https://rdflib.github.io/.well-known/genid/rdflib/N...
http://www.example.com/gr
>>> # Note that the Dataset.graphs() call returns names of empty graphs,
>>> # too. This can be restricted:
>>> for c in ds.graphs(empty=False): # doctest: +SKIP
... print(c) # doctest: +NORMALIZE_WHITESPACE
DEFAULT
http://www.example.com/gr
>>> # a graph can also be removed from a dataset via ds.remove_graph(g)
New in version 4.0
Methods:
-
__getstate__– -
__iadd__–Add all quads in Dataset other to Dataset.
-
__iter__–Iterates over all quads in the store
-
__reduce__– -
__setstate__– -
__str__– -
add_graph–alias of graph for consistency
-
contexts– -
graph– -
graphs– -
parse–Parse an RDF source adding the resulting triples to the Graph.
-
quads– -
remove_graph– -
serialize–
Attributes:
Source code in rdflib/graph.py
__getstate__
__getstate__() -> Tuple[Store, _ContextIdentifierType, _ContextType, bool]
__iadd__
Add all quads in Dataset other to Dataset. BNode IDs are not changed.
__iter__
__reduce__
__setstate__
__setstate__(state: Tuple[Store, _ContextIdentifierType, _ContextType, bool]) -> None
Source code in rdflib/graph.py
__str__
add_graph
add_graph(g: Optional[Union[_ContextIdentifierType, _ContextType, str]]) -> Graph
contexts
Source code in rdflib/graph.py
graph
graph(identifier: Optional[Union[_ContextIdentifierType, _ContextType, str]] = None, base: Optional[str] = None) -> Graph
Source code in rdflib/graph.py
graphs
Source code in rdflib/graph.py
parse
parse(source: Optional[Union[IO[bytes], TextIO, InputSource, str, bytes, PurePath]] = None, publicID: Optional[str] = None, format: Optional[str] = None, location: Optional[str] = None, file: Optional[Union[BinaryIO, TextIO]] = None, data: Optional[Union[str, bytes]] = None, **args: Any) -> Dataset
Parse an RDF source adding the resulting triples to the Graph.
Parameters:
-
(sourceOptional[Union[IO[bytes], TextIO, InputSource, str, bytes, PurePath]], default:None) –The source to parse. See rdflib.graph.Graph.parse for details.
-
(publicIDOptional[str], default:None) –The public ID of the source.
-
(formatOptional[str], default:None) –The format of the source.
-
(locationOptional[str], default:None) –The location of the source.
-
(fileOptional[Union[BinaryIO, TextIO]], default:None) –The file object to parse.
-
(dataOptional[Union[str, bytes]], default:None) –The data to parse.
-
(**argsAny, default:{}) –Additional arguments.
Returns:
-
Dataset–The graph that the source was parsed into.
Note
The source is specified using one of source, location, file or data.
If the source is in a format that does not support named graphs its triples
will be added to the default graph
(i.e. :attr:.Dataset.default_graph).
If the source is in a format that does not support named graphs its triples
will be added to the default graph (i.e. Dataset.default_graph).
Caution
This method can access directly or indirectly requested network or
file resources, for example, when parsing JSON-LD documents with
@context directives that point to a network location.
When processing untrusted or potentially malicious documents, measures should be taken to restrict network and file access.
For information on available security measures, see the RDFLib Security Considerations documentation.
Changed in 7.0
The publicID argument is no longer used as the identifier (i.e. name)
of the default graph as was the case before version 7.0. In the case of
sources that do not support named graphs, the publicID parameter will
also not be used as the name for the graph that the data is loaded into,
and instead the triples from sources that do not support named graphs will
be loaded into the default graph (i.e. Dataset.default_graph).
Source code in rdflib/graph.py
quads
quads(quad: Optional[_TripleOrQuadPatternType] = None) -> Generator[_OptionalIdentifiedQuadType, None, None]
Source code in rdflib/graph.py
remove_graph
Source code in rdflib/graph.py
serialize
serialize(destination: None = ..., format: str = ..., base: Optional[str] = ..., *, encoding: str, **args: Any) -> bytes
serialize(destination: None = ..., format: str = ..., base: Optional[str] = ..., encoding: None = ..., **args: Any) -> str
serialize(destination: Union[str, PurePath, IO[bytes]], format: str = ..., base: Optional[str] = ..., encoding: Optional[str] = ..., **args: Any) -> Graph
serialize(destination: Optional[Union[str, PurePath, IO[bytes]]] = ..., format: str = ..., base: Optional[str] = ..., encoding: Optional[str] = ..., **args: Any) -> Union[bytes, str, Graph]
serialize(destination: Optional[Union[str, PurePath, IO[bytes]]] = None, format: str = 'trig', base: Optional[str] = None, encoding: Optional[str] = None, **args: Any) -> Union[bytes, str, Graph]
Source code in rdflib/graph.py
Graph
Graph(store: Union[Store, str] = 'default', identifier: Optional[Union[_ContextIdentifierType, str]] = None, namespace_manager: Optional[NamespaceManager] = None, base: Optional[str] = None, bind_namespaces: _NamespaceSetString = 'rdflib')
Bases: Node
An RDF Graph: a Python object containing nodes and relations between them as RDF ‘triples’.
This is the central RDFLib object class and Graph objects are almost always present in all uses of RDFLib.
Example
The basic use is to create a Graph and iterate through or query its content:
>>> from rdflib import Graph, URIRef
>>> g = Graph()
>>> g.add((
... URIRef("http://example.com/s1"), # subject
... URIRef("http://example.com/p1"), # predicate
... URIRef("http://example.com/o1"), # object
... )) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((
... URIRef("http://example.com/s2"), # subject
... URIRef("http://example.com/p2"), # predicate
... URIRef("http://example.com/o2"), # object
... )) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> for triple in sorted(g): # simple looping
... print(triple)
(rdflib.term.URIRef('http://example.com/s1'), rdflib.term.URIRef('http://example.com/p1'), rdflib.term.URIRef('http://example.com/o1'))
(rdflib.term.URIRef('http://example.com/s2'), rdflib.term.URIRef('http://example.com/p2'), rdflib.term.URIRef('http://example.com/o2'))
>>> # get the object of the triple with subject s1 and predicate p1
>>> o = g.value(
... subject=URIRef("http://example.com/s1"),
... predicate=URIRef("http://example.com/p1")
... )
Parameters:
-
(storeUnion[Store, str], default:'default') –The constructor accepts one argument, the “store” that will be used to store the graph data with the default being the
Memory(in memory) Store. Other Stores that persist content to disk using various file databases or Stores that use remote servers (SPARQL systems) are supported. All builtin storetypes can be accessed via their registered names. Other Stores not shipped with RDFLib can be added as plugins, such as HDT. Registration of external plugins is described inrdflib.plugin.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.
Even if used with a context-aware store, Graph will only expose the quads which belong to the default graph. To access the rest of the data the
Datasetclass can be used instead.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 the RDFLib
Datasetclass and the TriG Specification, https://www.w3.org/TR/trig/. -
(identifierOptional[Union[_ContextIdentifierType, str]], default:None) –identifier of the graph itself
-
(namespace_managerOptional[NamespaceManager], default:None) –Used namespace manager. Create with bind_namespaces if
None. -
(baseOptional[str], default:None) –Base used for URIs
-
(bind_namespaces_NamespaceSetString, default:'rdflib') –Used bind_namespaces for namespace_manager Is only used, when no namespace_manager is provided.
Methods:
-
__add__–Set-theoretic union
-
__cmp__– -
__contains__–Support for ‘triple in graph’ syntax.
-
__eq__– -
__ge__– -
__getitem__–A graph can be “sliced” as a shortcut for the triples method
-
__gt__– -
__hash__– -
__iadd__–Add all triples in Graph other to Graph.
-
__isub__–Subtract all triples in Graph other from Graph.
-
__iter__–Iterates over all triples in the store.
-
__le__– -
__len__–Returns the number of triples in the graph.
-
__lt__– -
__mul__–Set-theoretic intersection.
-
__reduce__– -
__repr__– -
__str__– -
__sub__–Set-theoretic difference.
-
__xor__–Set-theoretic XOR.
-
absolutize–Turn uri into an absolute URI if it’s not one already
-
add–Add a triple with self as context.
-
addN–Add a sequence of triple with context
-
all_nodes– -
bind–Bind prefix to namespace
-
cbd–Retrieves the Concise Bounded Description of a Resource from a Graph.
-
close–Close the graph store
-
collection–Create a new
Collectioninstance. -
commit–Commits active transactions
-
compute_qname– -
connected–Check if the Graph is connected.
-
de_skolemize– -
destroy–Destroy the store identified by
configurationif supported -
isomorphic–Check if this graph is isomorphic to another graph.
-
items–Generator over all items in the resource specified by list
-
n3–Return an n3 identifier for the Graph
-
namespaces–Generator over all the prefix, namespace tuples
-
objects–A generator of (optionally unique) objects with the given
-
open–Open the graph store
-
parse–Parse an RDF source adding the resulting triples to the Graph.
-
predicate_objects–A generator of (optionally unique) (predicate, object) tuples
-
predicates–Generate predicates with the given subject and object.
-
print– -
qname– -
query–Query this graph.
-
remove–Remove a triple from the graph
-
resource–Create a new
Resourceinstance. -
rollback–Rollback active transactions
-
serialize–Serialize the graph.
-
set–Convenience method to update the value of object
-
skolemize– -
subject_objects–A generator of (optionally unique) (subject, object) tuples
-
subject_predicates–A generator of (optionally unique) (subject, predicate) tuples
-
subjects–A generator of (optionally unique) subjects with the given
-
toPython– -
transitiveClosure–Generates transitive closure of a user-defined function against the graph
-
transitive_objects–Transitively generate objects for the
predicaterelationship -
transitive_subjects–Transitively generate subjects for the
predicaterelationship -
triples–Generator over the triple store.
-
triples_choices– -
update–Update this graph with the given update query.
-
value–Get a value for a pair of two criteria
Attributes:
-
__and__– -
__or__– -
base(Optional[str]) – -
context_aware(bool) – -
default_union(bool) – -
formula_aware(bool) – -
identifier(_ContextIdentifierType) – -
namespace_manager(NamespaceManager) –this graph’s namespace-manager
-
store(Store) –
Source code in rdflib/graph.py
namespace_manager
property
writable
namespace_manager: NamespaceManager
this graph’s namespace-manager
__add__
Set-theoretic union BNode IDs are not changed.
Source code in rdflib/graph.py
__cmp__
Source code in rdflib/graph.py
__contains__
__contains__(triple: _TripleSelectorType) -> bool
Support for ‘triple in graph’ syntax.
Parameters:
-
(triple_TripleSelectorType) –The triple pattern to check for.
Returns:
-
bool–True if the triple pattern exists in the graph, False otherwise.
Source code in rdflib/graph.py
__eq__
__ge__
__ge__(other: Graph) -> bool
__getitem__
A graph can be “sliced” as a shortcut for the triples method The python slice syntax is (ab)used for specifying triples. A generator over matches is returned, the returned tuples include only the parts not given
>>> import rdflib
>>> g = rdflib.Graph()
>>> g.add((rdflib.URIRef("urn:bob"), namespace.RDFS.label, rdflib.Literal("Bob"))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> list(g[rdflib.URIRef("urn:bob")]) # all triples about bob
[(rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label'), rdflib.term.Literal('Bob'))]
>>> list(g[:namespace.RDFS.label]) # all label triples
[(rdflib.term.URIRef('urn:bob'), rdflib.term.Literal('Bob'))]
>>> list(g[::rdflib.Literal("Bob")]) # all triples with bob as object
[(rdflib.term.URIRef('urn:bob'), rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label'))]
Combined with SPARQL paths, more complex queries can be written concisely:
- Name of all Bobs friends:
g[bob : FOAF.knows/FOAF.name ] - Some label for Bob:
g[bob : DC.title|FOAF.name|RDFS.label] - All friends and friends of friends of Bob:
g[bob : FOAF.knows * "+"] - etc.
New in version 4.0
Source code in rdflib/graph.py
__gt__
__hash__
__iadd__
Add all triples in Graph other to Graph. BNode IDs are not changed.
__isub__
Subtract all triples in Graph other from Graph. BNode IDs are not changed.
__iter__
Iterates over all triples in the store.
Returns:
-
None–A generator yielding all triples in the store.
__le__
__le__(other: Graph) -> bool
__len__
Returns the number of triples in the graph.
If context is specified then the number of triples in the context is returned instead.
Returns:
-
int–The number of triples in the graph.
Source code in rdflib/graph.py
__lt__
__mul__
Set-theoretic intersection. BNode IDs are not changed.
__reduce__
__repr__
__str__
Source code in rdflib/graph.py
__sub__
Set-theoretic difference. BNode IDs are not changed.
__xor__
absolutize
absolutize(uri: str, defrag: int = 1) -> URIRef
add
add(triple: _TripleType) -> _GraphT
Add a triple with self as context.
Parameters:
-
(triple_TripleType) –The triple to add to the graph.
Returns:
-
_GraphT–The graph instance.
Source code in rdflib/graph.py
addN
Add a sequence of triple with context
Source code in rdflib/graph.py
all_nodes
all_nodes() -> Set[Node]
bind
Bind prefix to namespace
If override is True will bind namespace to given prefix even if namespace was already bound to a different prefix.
if replace, replace any existing prefix with the new namespace
Parameters:
-
(prefixOptional[str]) –The prefix to bind
-
(namespaceAny) –The namespace to bind the prefix to
-
(overridebool, default:True) –If True, override any existing prefix binding
-
(replacebool, default:False) –If True, replace any existing namespace binding
Source code in rdflib/graph.py
cbd
cbd(resource: _SubjectType, *, target_graph: Optional[Graph] = None) -> Graph
Retrieves the Concise Bounded Description of a Resource from a Graph.
Parameters:
-
(resource_SubjectType) –A URIRef object, the Resource to query for.
-
(target_graphOptional[Graph], default:None) –Optionally, a graph to add the CBD to; otherwise, a new graph is created for the CBD.
Returns:
-
Graph–A Graph, subgraph of self if no graph was provided otherwise the provided graph.
Note
Concise Bounded Description (CBD) is defined as:
Given a particular node (the starting node) in a particular RDF graph (the source graph), a subgraph of that particular graph, taken to comprise a concise bounded description of the resource denoted by the starting node, can be identified as follows:
-
Include in the subgraph all statements in the source graph where the subject of the statement is the starting node;
-
Recursively, for all statements identified in the subgraph thus far having a blank node object, include in the subgraph all statements in the source graph where the subject of the statement is the blank node in question and which are not already included in the subgraph.
-
Recursively, for all statements included in the subgraph thus far, for all reifications of each statement in the source graph, include the concise bounded description beginning from the rdf:Statement node of each reification.
This results in a subgraph where the object nodes are either URI references, literals, or blank nodes not serving as the subject of any statement in the graph.
Source code in rdflib/graph.py
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 | |
close
Close the graph store
Might be necessary for stores that require closing a connection to a database or releasing some resource.
Source code in rdflib/graph.py
collection
collection(identifier: _SubjectType) -> Collection
Create a new Collection instance.
Parameters:
-
(identifier_SubjectType) –A URIRef or BNode instance.
Returns:
-
Collection–A new Collection instance.
Example
Source code in rdflib/graph.py
commit
compute_qname
compute_qname(uri: str, generate: bool = True) -> Tuple[str, URIRef, str]
connected
Check if the Graph is connected.
The Graph is considered undirectional.
Returns:
-
bool–True if all nodes have been visited and there are no unvisited nodes left,
-
bool–False otherwise.
Note
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.
Source code in rdflib/graph.py
de_skolemize
Source code in rdflib/graph.py
destroy
isomorphic
Check if this graph is isomorphic to another graph.
Performs a basic check if these graphs are the same. If no BNodes are involved, this is accurate.
Parameters:
-
(otherGraph) –The graph to compare with.
Returns:
-
bool–True if the graphs are isomorphic, False otherwise.
Note
This is only an approximation. See rdflib.compare for a correct implementation of isomorphism checks.
Source code in rdflib/graph.py
items
Generator over all items in the resource specified by list
Parameters:
-
(listNode) –An RDF collection.
Source code in rdflib/graph.py
n3
n3(namespace_manager: Optional[NamespaceManager] = None) -> str
namespaces
namespaces() -> Generator[Tuple[str, URIRef], None, None]
Generator over all the prefix, namespace tuples
Returns:
-
None–Generator yielding prefix, namespace tuples
Source code in rdflib/graph.py
objects
objects(subject: Optional[Union[_SubjectType, List[_SubjectType]]] = None, predicate: Union[None, Path, _PredicateType] = None, unique: bool = False) -> Generator[_ObjectType, None, None]
A generator of (optionally unique) objects with the given subject(s) and predicate
Parameters:
-
(subjectOptional[Union[_SubjectType, List[_SubjectType]]], default:None) –A specific subject or a list of subjects to match or None to match any subject.
-
(predicateUnion[None, Path, _PredicateType], default:None) –A specific predicate to match or None to match any predicate.
-
(uniquebool, default:False) –If True, only yield unique objects.
Yields:
-
_ObjectType–Objects matching the given subject and predicate.
Source code in rdflib/graph.py
open
Open the graph store
Might be necessary for stores that require opening a connection to a database or acquiring some resource.
Source code in rdflib/graph.py
parse
parse(source: Optional[Union[IO[bytes], TextIO, InputSource, str, bytes, PurePath]] = None, publicID: Optional[str] = None, format: Optional[str] = None, location: Optional[str] = None, file: Optional[Union[BinaryIO, TextIO]] = None, data: Optional[Union[str, bytes]] = None, **args: Any) -> Graph
Parse an RDF source adding the resulting triples to the Graph.
The source is specified using one of source, location, file or data.
Parameters:
-
(sourceOptional[Union[IO[bytes], TextIO, InputSource, str, bytes, PurePath]], default:None) –An
xml.sax.xmlreader.InputSource, file-like object,pathlib.Pathlike object, or string. In the case of a string the string is the location of the source. -
(publicIDOptional[str], default:None) –The logical URI to use as the document base. If None specified the document location is used (at least in the case where there is a document location). This is used as the base URI when resolving relative URIs in the source document, as defined in
IETF RFC 3986 <https://datatracker.ietf.org/doc/html/rfc3986#section-5.1.4>_, given the source document does not define a base URI. -
(formatOptional[str], default:None) –Used if format can not be determined from source, e.g. file extension or Media Type. Format support is managed with plugins. Available formats are e.g. “turle”, “xml”, “n3”, “nt” and “trix” or see parser module.
-
(locationOptional[str], default:None) –A string indicating the relative or absolute URL of the source.
Graph’s absolutize method is used if a relative location is specified. -
(fileOptional[Union[BinaryIO, TextIO]], default:None) –A file-like object.
-
(dataOptional[Union[str, bytes]], default:None) –A string containing the data to be parsed.
-
(argsAny, default:{}) –Additional arguments to pass to the parser.
Returns:
-
Graph–self, i.e. the Graph instance.
Example
>>> 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 os, tempfile
>>> fd, file_name = tempfile.mkstemp()
>>> f = os.fdopen(fd, "w")
>>> dummy = f.write(my_data) # Returns num bytes written
>>> 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()
>>> with open(file_name, "r") as f:
... result = g.parse(f, format="application/rdf+xml")
>>> len(g)
2
>>> os.remove(file_name)
>>> # default turtle parsing
>>> result = g.parse(data="<http://example.com/a> <http://example.com/a> <http://example.com/a> .")
>>> len(g)
3
Caution
This method can access directly or indirectly requested network or
file resources, for example, when parsing JSON-LD documents with
@context directives that point to a network location.
When processing untrusted or potentially malicious documents, measures should be taken to restrict network and file access.
For information on available security measures, see the RDFLib Security Considerations documentation.
Source code in rdflib/graph.py
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 | |
predicate_objects
predicate_objects(subject: Optional[_SubjectType] = None, unique: bool = False) -> Generator[Tuple[_PredicateType, _ObjectType], None, None]
A generator of (optionally unique) (predicate, object) tuples for the given subject
Source code in rdflib/graph.py
predicates
predicates(subject: Optional[_SubjectType] = None, object: Optional[_ObjectType] = None, unique: bool = False) -> Generator[_PredicateType, None, None]
Generate predicates with the given subject and object.
Parameters:
-
(subjectOptional[_SubjectType], default:None) –A specific subject to match or None to match any subject.
-
(objectOptional[_ObjectType], default:None) –A specific object to match or None to match any object.
-
(uniquebool, default:False) –If True, only yield unique predicates.
Yields:
-
_PredicateType–Predicates matching the given subject and object.
Source code in rdflib/graph.py
print
qname
query
query(query_object: Union[str, Query], processor: Union[str, Processor] = 'sparql', result: Union[str, Type[Result]] = 'sparql', initNs: Optional[Mapping[str, Any]] = None, initBindings: Optional[Mapping[str, Identifier]] = None, use_store_provided: bool = True, **kwargs: Any) -> Result
Query this graph.
Parameters:
-
(query_objectUnion[str, Query]) –The query string or object to execute.
-
(processorUnion[str, Processor], default:'sparql') –The query processor to use. Default is “sparql”.
-
(resultUnion[str, Type[Result]], default:'sparql') –The result format to use. Default is “sparql”.
-
(initNsOptional[Mapping[str, Any]], default:None) –Initial namespaces to use for resolving prefixes in the query. If none are given, the namespaces from the graph’s namespace manager are used.
-
(initBindingsOptional[Mapping[str, Identifier]], default:None) –Initial variable bindings to use. A type of ‘prepared queries’ can be realized by providing these bindings.
-
(use_store_providedbool, default:True) –Whether to use the store’s query method if available.
-
(kwargsAny, default:{}) –Additional arguments to pass to the query processor.
Returns:
-
Result–A [
rdflib.query.Result][rdflib.query.Result] instance.
Caution
This method can access indirectly requested network endpoints, for
example, query processing will attempt to access network endpoints
specified in SERVICE directives.
When processing untrusted or potentially malicious queries, measures should be taken to restrict network and file access.
For information on available security measures, see the RDFLib Security Considerations documentation.
Source code in rdflib/graph.py
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 | |
remove
Remove a triple from the graph
If the triple does not provide a context attribute, removes the triple from all contexts.
Source code in rdflib/graph.py
resource
resource(identifier: Union[Node, str]) -> Resource
Create a new Resource instance.
Parameters:
-
(identifierUnion[Node, str]) –A URIRef or BNode instance.
Returns:
-
Resource–A new Resource instance.
Example
Source code in rdflib/graph.py
rollback
serialize
serialize(destination: None, format: str, base: Optional[str], encoding: str, **args: Any) -> bytes
serialize(destination: None = ..., format: str = ..., base: Optional[str] = ..., *, encoding: str, **args: Any) -> bytes
serialize(destination: None = ..., format: str = ..., base: Optional[str] = ..., encoding: None = ..., **args: Any) -> str
serialize(destination: Union[str, PurePath, IO[bytes]], format: str = ..., base: Optional[str] = ..., encoding: Optional[str] = ..., **args: Any) -> Graph
serialize(destination: Optional[Union[str, PurePath, IO[bytes]]] = ..., format: str = ..., base: Optional[str] = ..., encoding: Optional[str] = ..., **args: Any) -> Union[bytes, str, Graph]
serialize(destination: Optional[Union[str, PurePath, IO[bytes]]] = None, format: str = 'turtle', base: Optional[str] = None, encoding: Optional[str] = None, **args: Any) -> Union[bytes, str, _GraphT]
Serialize the graph.
Parameters:
-
(destinationOptional[Union[str, PurePath, IO[bytes]]], default:None) –The destination to serialize the graph to. This can be a path as a string or pathlib.PurePath object, or it can be an IO[bytes] like object. If this parameter is not supplied the serialized graph will be returned.
-
(formatstr, default:'turtle') –The format that the output should be written in. This value references a Serializer plugin. Format support is managed with plugins. Defaults to “turtle” and some other formats are builtin, like “xml” and “trix”. See also serialize module.
-
(baseOptional[str], default:None) –The base IRI for formats that support it. For the turtle format this will be used as the @base directive.
-
(encodingOptional[str], default:None) –Encoding of output.
-
(argsAny, default:{}) –Additional arguments to pass to the Serializer that will be used.
Returns:
-
Union[bytes, str, _GraphT]–The serialized graph if
destinationis None. The serialized graph is returned -
Union[bytes, str, _GraphT]–as str if no encoding is specified, and as bytes if an encoding is specified.
-
Union[bytes, str, _GraphT]–self (i.e. the Graph instance) if
destinationis not None.
Source code in rdflib/graph.py
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 | |
set
Convenience method to update the value of object
Remove any existing triples for subject and predicate before adding (subject, predicate, object).
Source code in rdflib/graph.py
skolemize
skolemize(new_graph: Optional[Graph] = None, bnode: Optional[BNode] = None, authority: Optional[str] = None, basepath: Optional[str] = None) -> Graph
Source code in rdflib/graph.py
subject_objects
subject_objects(predicate: Union[None, Path, _PredicateType] = None, unique: bool = False) -> Generator[Tuple[_SubjectType, _ObjectType], None, None]
A generator of (optionally unique) (subject, object) tuples for the given predicate
Source code in rdflib/graph.py
subject_predicates
subject_predicates(object: Optional[_ObjectType] = None, unique: bool = False) -> Generator[Tuple[_SubjectType, _PredicateType], None, None]
A generator of (optionally unique) (subject, predicate) tuples for the given object
Source code in rdflib/graph.py
subjects
subjects(predicate: Union[None, Path, _PredicateType] = None, object: Optional[Union[_ObjectType, List[_ObjectType]]] = None, unique: bool = False) -> Generator[_SubjectType, None, None]
A generator of (optionally unique) subjects with the given predicate and object(s)
Parameters:
-
(predicateUnion[None, Path, _PredicateType], default:None) –A specific predicate to match or None to match any predicate.
-
(objectOptional[Union[_ObjectType, List[_ObjectType]]], default:None) –A specific object or list of objects to match or None to match any object.
-
(uniquebool, default:False) –If True, only yield unique subjects.
Source code in rdflib/graph.py
toPython
transitiveClosure
transitiveClosure(func: Callable[[_TCArgT, Graph], Iterable[_TCArgT]], arg: _TCArgT, seen: Optional[Dict[_TCArgT, int]] = None)
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,namespace.RDFS.label))
g.add((b,RDF.rest,c))
g.add((c,RDF.first,namespace.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')]
Parameters:
-
(funcCallable[[_TCArgT, Graph], Iterable[_TCArgT]]) –A function that generates a sequence of nodes
-
(arg_TCArgT) –The starting node
-
(seenOptional[Dict[_TCArgT, int]], default:None) –A dict of visited nodes
Source code in rdflib/graph.py
transitive_objects
transitive_objects(subject: Optional[_SubjectType], predicate: Optional[_PredicateType], remember: Optional[Dict[Optional[_SubjectType], int]] = None) -> Generator[Optional[_SubjectType], None, None]
Transitively generate objects for the predicate relationship
Generated objects belong to the depth first transitive closure of the
predicate relationship starting at subject.
Parameters:
-
(subjectOptional[_SubjectType]) –The subject to start the transitive closure from
-
(predicateOptional[_PredicateType]) –The predicate to follow
-
(rememberOptional[Dict[Optional[_SubjectType], int]], default:None) –A dict of visited nodes
Source code in rdflib/graph.py
transitive_subjects
transitive_subjects(predicate: Optional[_PredicateType], object: Optional[_ObjectType], remember: Optional[Dict[Optional[_ObjectType], int]] = None) -> Generator[Optional[_ObjectType], None, None]
Transitively generate subjects for the predicate relationship
Generated subjects belong to the depth first transitive closure of the
predicate relationship starting at object.
Parameters:
-
(predicateOptional[_PredicateType]) –The predicate to follow
-
(objectOptional[_ObjectType]) –The object to start the transitive closure from
-
(rememberOptional[Dict[Optional[_ObjectType], int]], default:None) –A dict of visited nodes
Source code in rdflib/graph.py
triples
triples(triple: _TriplePatternType) -> Generator[_TripleType, None, None]
triples(triple: _TriplePathPatternType) -> Generator[_TriplePathType, None, None]
triples(triple: _TripleSelectorType) -> Generator[_TripleOrTriplePathType, None, None]
triples(triple: _TripleSelectorType) -> Generator[_TripleOrTriplePathType, None, None]
Generator over the triple store.
Returns triples that match the given triple pattern. If the triple pattern does not provide a context, all contexts will be searched.
Parameters:
-
(triple_TripleSelectorType) –A triple pattern where each component can be a specific value or None as a wildcard. The predicate can also be a path expression.
Yields:
-
_TripleOrTriplePathType–Triples matching the given pattern.
Source code in rdflib/graph.py
triples_choices
triples_choices(triple: _TripleChoiceType, context: Optional[_ContextType] = None) -> Generator[_TripleType, None, None]
Source code in rdflib/graph.py
update
update(update_object: Union[Update, str], processor: Union[str, UpdateProcessor] = 'sparql', initNs: Optional[Mapping[str, Any]] = None, initBindings: Optional[Mapping[str, Identifier]] = None, use_store_provided: bool = True, **kwargs: Any) -> None
Update this graph with the given update query.
Parameters:
-
(update_objectUnion[Update, str]) –The update query string or object to execute.
-
(processorUnion[str, UpdateProcessor], default:'sparql') –The update processor to use. Default is “sparql”.
-
(initNsOptional[Mapping[str, Any]], default:None) –Initial namespaces to use for resolving prefixes in the query. If none are given, the namespaces from the graph’s namespace manager are used.
-
(initBindingsOptional[Mapping[str, Identifier]], default:None) –Initial variable bindings to use.
-
(use_store_providedbool, default:True) –Whether to use the store’s update method if available.
-
(kwargsAny, default:{}) –Additional arguments to pass to the update processor.
Caution
This method can access indirectly requested network endpoints, for
example, query processing will attempt to access network endpoints
specified in SERVICE directives.
When processing untrusted or potentially malicious queries, measures should be taken to restrict network and file access.
For information on available security measures, see the RDFLib Security Considerations documentation.
Source code in rdflib/graph.py
value
value(subject: None = ..., predicate: None = ..., object: Optional[_ObjectType] = ..., default: Optional[Node] = ..., any: bool = ...) -> None
value(subject: Optional[_SubjectType] = ..., predicate: None = ..., object: None = ..., default: Optional[Node] = ..., any: bool = ...) -> None
value(subject: Optional[_SubjectType] = None, predicate: Optional[_PredicateType] = value, object: Optional[_ObjectType] = None, default: Optional[Node] = None, any: bool = True) -> Optional[Node]
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:
-
(subjectOptional[_SubjectType], default:None) –Subject of the triple pattern, exactly one of subject, predicate, object must be None
-
(predicateOptional[_PredicateType], default:value) –Predicate of the triple pattern, exactly one of subject, predicate, object must be None
-
(objectOptional[_ObjectType], default:None) –Object of the triple pattern, exactly one of subject, predicate, object must be None
-
(defaultOptional[Node], default:None) –Value to be returned if no values found
-
(anybool, default:True) –If True, return any value in the case there is more than one, else, raise UniquenessError
Source code in rdflib/graph.py
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 | |
ModificationException
QuotedGraph
QuotedGraph(store: Union[Store, str], identifier: Optional[Union[_ContextIdentifierType, str]])
Bases: Graph
Quoted Graphs are intended to implement Notation 3 formulae. They are associated with a required identifier that the N3 parser must provide in order to maintain consistent formulae identification for scenarios such as implication and other such processing.
Methods:
-
__reduce__– -
__str__– -
add–Add a triple with self as context
-
addN–Add a sequence of triple with context
-
n3–Return an n3 identifier for the Graph
Source code in rdflib/graph.py
__reduce__
__str__
add
Add a triple with self as context
Source code in rdflib/graph.py
addN
Add a sequence of triple with context
Source code in rdflib/graph.py
n3
n3(namespace_manager: Optional[NamespaceManager] = None) -> str
ReadOnlyGraphAggregate
Bases: ConjunctiveGraph
Utility class for treating a set of graphs as a single graph
Only read operations are supported (hence the name). Essentially a ConjunctiveGraph over an explicit subset of the entire store.
Methods:
-
__cmp__– -
__contains__– -
__hash__– -
__iadd__– -
__isub__– -
__len__– -
__reduce__– -
__repr__– -
absolutize– -
add– -
addN– -
bind– -
close– -
commit– -
compute_qname– -
destroy– -
n3– -
namespaces– -
open– -
parse– -
qname– -
quads–Iterate over all the quads in the entire aggregate graph
-
remove– -
rollback– -
triples– -
triples_choices–
Attributes:
-
graphs–
Source code in rdflib/graph.py
__cmp__
Source code in rdflib/graph.py
__contains__
Source code in rdflib/graph.py
__hash__
__iadd__
__isub__
__len__
__reduce__
__repr__
absolutize
add
addN
bind
close
commit
compute_qname
compute_qname(uri: str, generate: bool = True) -> Tuple[str, URIRef, str]
destroy
n3
n3(namespace_manager: Optional[NamespaceManager] = None) -> NoReturn
open
Source code in rdflib/graph.py
parse
parse(source: Optional[Union[IO[bytes], TextIO, InputSource, str, bytes, PurePath]], publicID: Optional[str] = None, format: Optional[str] = None, **args: Any) -> NoReturn
Source code in rdflib/graph.py
qname
quads
quads(triple_or_quad: _TripleOrQuadSelectorType) -> Generator[Tuple[_SubjectType, Union[Path, _PredicateType], _ObjectType, _ContextType], None, None]
Iterate over all the quads in the entire aggregate graph
Source code in rdflib/graph.py
remove
rollback
triples
Source code in rdflib/graph.py
triples_choices
triples_choices(triple: _TripleChoiceType, context: Optional[_ContextType] = None) -> Generator[_TripleType, None, None]
Source code in rdflib/graph.py
Seq
Wrapper around an RDF Seq resource
It implements a container type in Python with the order of the items returned corresponding to the Seq content. It is based on the natural ordering of the predicate names _1, _2, _3, etc, which is the ‘implementation’ of a sequence in RDF terms.
Parameters:
-
(graphGraph) –the graph containing the Seq
-
(subject_SubjectType) –the subject of a Seq. Note that the init does not check whether this is a Seq, this is done in whoever creates this instance!
Methods:
-
__getitem__–Item given by index from the Seq
-
__iter__–Generator over the items in the Seq
-
__len__–Length of the Seq
-
toPython–