Navigation

  • index
  • modules |
  • next |
  • previous |
  • rdflib 7.0.0 documentation »
  • Navigating Graphs

Navigating Graphs¶

An RDF Graph is a set of RDF triples, and we try to mirror exactly this in RDFLib. The Python Graph() tries to emulate a container type.

Graphs as Iterators¶

RDFLib graphs override __iter__() in order to support iteration over the contained triples:

for s, p, o in someGraph:
    if not (s, p, o) in someGraph:
        raise Exception("Iterator / Container Protocols are Broken!!")

This loop iterates through all the subjects(s), predicates (p) & objects (o) in someGraph.

Contains check¶

Graphs implement __contains__(), so you can check if a triple is in a graph with a triple in graph syntax:

from rdflib import URIRef
from rdflib.namespace import RDF

bob = URIRef("http://example.org/people/bob")
if (bob, RDF.type, FOAF.Person) in graph:
    print("This graph knows that Bob is a person!")

Note that this triple does not have to be completely bound:

if (bob, None, None) in graph:
    print("This graph contains triples about Bob!")

Set Operations on RDFLib Graphs¶

Graphs override several pythons operators: __iadd__(), __isub__(), etc. This supports addition, subtraction and other set-operations on Graphs:

operation

effect

G1 + G2

return new graph with union (triples on both)

G1 += G2

in place union / addition

G1 - G2

return new graph with difference (triples in G1, not in G2)

G1 -= G2

in place difference / subtraction

G1 & G2

intersection (triples in both graphs)

G1 ^ G2

xor (triples in either G1 or G2, but not in both)

Warning

Set-operations on graphs assume Blank Nodes are shared between graphs. This may or may not be what you want. See Merging graphs for details.

Basic Triple Matching¶

Instead of iterating through all triples, RDFLib graphs support basic triple pattern matching with a triples() function. This function is a generator of triples that match a pattern given by arguments, i.e. arguments restrict the triples that are returned. Terms that are None are treated as a wildcard. For example:

g.parse("some_foaf.ttl")
# find all subjects (s) of type (rdf:type) person (foaf:Person)
for s, p, o in g.triples((None, RDF.type, FOAF.Person)):
    print(f"{s} is a person")

# find all subjects of any type
for s, p, o in g.triples((None,  RDF.type, None)):
    print(f"{s} is a {o}")

# create a graph
bobgraph = Graph()
# add all triples with subject 'bob'
bobgraph += g.triples((bob, None, None))

If you are not interested in whole triples, you can get only the bits you want with the methods objects(), subjects(), predicates(), predicate_objects(), etc. Each take parameters for the components of the triple to constraint:

for person in g.subjects(RDF.type, FOAF.Person):
    print("{} is a person".format(person))

Finally, for some properties, only one value per resource makes sense (i.e they are functional properties, or have a max-cardinality of 1). The value() method is useful for this, as it returns just a single node, not a generator:

# get any name of bob
name = g.value(bob, FOAF.name)
# get the one person that knows bob and raise an exception if more are found
person = g.value(predicate=FOAF.knows, object=bob, any=False)

Graph methods for accessing triples¶

Here is a list of all convenience methods for querying Graphs:

Graph.triples(triple)[source]

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.

Parameters:

triple (Tuple[Optional[Node], Union[Path, Node, None], Optional[Node]]) –

Return type:

Generator[Union[Tuple[Node, Node, Node], Tuple[Node, Path, Node]], None, None]

Graph.value(subject=None, predicate=rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#value'), object=None, default=None, any=True)[source]

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

Parameters:
  • subject (Optional[Node]) –

  • predicate (Optional[Node]) –

  • object (Optional[Node]) –

  • default (Optional[Node]) –

  • any (bool) –

Return type:

Optional[Node]

Graph.subjects(predicate=None, object=None, unique=False)[source]

A generator of (optionally unique) subjects with the given predicate and object

Parameters:
  • predicate (Union[None, Path, Node]) –

  • object (Optional[Node]) –

  • unique (bool) –

Return type:

Generator[Node, None, None]

Graph.objects(subject=None, predicate=None, unique=False)[source]

A generator of (optionally unique) objects with the given subject and predicate

Parameters:
  • subject (Optional[Node]) –

  • predicate (Union[None, Path, Node]) –

  • unique (bool) –

Return type:

Generator[Node, None, None]

Graph.predicates(subject=None, object=None, unique=False)[source]

A generator of (optionally unique) predicates with the given subject and object

Parameters:
  • subject (Optional[Node]) –

  • object (Optional[Node]) –

  • unique (bool) –

Return type:

Generator[Node, None, None]

Graph.subject_objects(predicate=None, unique=False)[source]

A generator of (optionally unique) (subject, object) tuples for the given predicate

Parameters:
  • predicate (Union[None, Path, Node]) –

  • unique (bool) –

Return type:

Generator[Tuple[Node, Node], None, None]

Graph.subject_predicates(object=None, unique=False)[source]

A generator of (optionally unique) (subject, predicate) tuples for the given object

Parameters:
  • object (Optional[Node]) –

  • unique (bool) –

Return type:

Generator[Tuple[Node, Node], None, None]

Graph.predicate_objects(subject=None, unique=False)[source]

A generator of (optionally unique) (predicate, object) tuples for the given subject

Parameters:
  • subject (Optional[Node]) –

  • unique (bool) –

Return type:

Generator[Tuple[Node, Node], None, None]

Logo

Table of Contents

  • Navigating Graphs
    • Graphs as Iterators
    • Contains check
    • Set Operations on RDFLib Graphs
    • Basic Triple Matching
    • Graph methods for accessing triples

Previous topic

Creating RDF triples

Next topic

Querying with SPARQL

This Page

  • Show Source

Quick search

Navigation

  • index
  • modules |
  • next |
  • previous |
  • rdflib 7.0.0 documentation »
  • Navigating Graphs
© Copyright 2009 - 2023, RDFLib Team. Created using Sphinx 7.1.1.
Theme based on Read The Docs