### Navigation

- index
- modules |
- next |
- previous |
- rdflib 4.1.2 documentation »

# Navigating Graphs

An RDF Graph is a set of RDF triples, and we try to mirror exactly this in RDFLib, and the graph tries to emulate a container type:

## Graphs as Iterators

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

    for subject,predicate,obj in someGraph:
       if not (subject,predicate,obj) in someGraph:
          raise Exception("Iterator / Container Protocols are Broken!!")

## Contains check

Graphs implement `__contains__()`, so you can check if a triple is in a graph with `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
`G1 += G1` | in place union / addition
`G1 - G2` | return new graph with difference
`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 bnodes are shared between graphs. This may or may not do 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 the pattern given by the arguments. The arguments of these are RDF terms that restrict the triples that are returned. Terms that are `None` are treated as a wildcard. For example:

    g.load("some_foaf.rdf")
    for s,p,o in g.triples( (None, RDF.type, FOAF.Person) ):
       print "%s is a person"%s

    for s,p,o in g.triples( (None,  RDF.type, None) ):
       print "%s is a %s"%(s,o)

    bobgraph = Graph()

    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()`, `predicates_objects()`, etc. Each take parameters for the components of the triple to constraint:

    for person in g.subjects(RDF.type, FOAF.Person):
       print "%s is a person"%person

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

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

## `Graph` methods for accessing triples

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

`Graph.``label`(subject, default='')

  Query for the RDFS.label of the subject

  Return default if no label exists or any label if multiple exist.

`Graph.``preferredLabel`(subject, lang=None, default=None, labelProperties=(rdflib.term.URIRef(u'http://www.w3.org/2004/02/skos/core#prefLabel'), rdflib.term.URIRef(u'http://www.w3.org/2000/01/rdf-schema#label')))

  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.

      >>> from rdflib import ConjunctiveGraph, URIRef, RDFS, Literal
      >>> from rdflib.namespace import SKOS
      >>> from pprint import pprint
      >>> g = ConjunctiveGraph()
      >>> u = URIRef(u'http://example.com/foo')
      >>> g.add([u, RDFS.label, Literal('foo')])
      >>> g.add([u, RDFS.label, Literal('bar')])
      >>> pprint(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')])
      >>> pprint(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'bla')),
        (rdflib.term.URIRef(u'http://www.w3.org/2004/02/skos/core#prefLabel'),
        rdflib.term.Literal(u'blubb', lang='en'))]
      >>> g.preferredLabel(u, lang='')
      [(rdflib.term.URIRef(u'http://www.w3.org/2004/02/skos/core#prefLabel'),
        rdflib.term.Literal(u'bla'))]
      >>> pprint(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'))]

`Graph.``triples`((s, p, o))

  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.

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

  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

`Graph.``subjects`(predicate=None, object=None)

  A generator of subjects with the given predicate and object

`Graph.``objects`(subject=None, predicate=None)

  A generator of objects with the given subject and predicate

`Graph.``predicates`(subject=None, object=None)

  A generator of predicates with the given subject and object

`Graph.``subject_objects`(predicate=None)

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

`Graph.``subject_predicates`(object=None)

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

`Graph.``predicate_objects`(subject=None)

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

### Navigation

- index
- modules |
- next |
- previous |
- rdflib 4.1.2 documentation »