0
# Graph Operations
1
2
Primary interface for working with RDF data. The Graph class provides methods for adding, removing, and querying RDF triples, plus parsing and serialization capabilities across multiple formats.
3
4
## Capabilities
5
6
### Graph - Core RDF Graph
7
8
The main container for RDF triples with comprehensive functionality for RDF data manipulation.
9
10
```python { .api }
11
class Graph:
12
def __init__(self, store: Union[Store, str] = 'default', identifier: Optional[Union[Node, str]] = None, namespace_manager: Optional[NamespaceManager] = None, base: Optional[str] = None, bind_namespaces: str = 'rdflib'):
13
"""
14
Create an RDF graph.
15
16
Parameters:
17
- store: Store type ('Memory', 'SPARQLStore', etc.)
18
- identifier: Graph identifier (URIRef or BNode)
19
- namespace_manager: Custom namespace manager
20
"""
21
22
def add(self, triple: Tuple[Node, Node, Node]) -> 'Graph':
23
"""
24
Add a triple to the graph.
25
26
Parameters:
27
- triple: (subject, predicate, object) tuple
28
29
Returns:
30
Graph: Self for method chaining
31
"""
32
33
def remove(self, triple: Tuple[Node, Node, Node]) -> 'Graph':
34
"""
35
Remove triples matching the pattern.
36
37
Parameters:
38
- triple: Pattern tuple (None acts as wildcard)
39
40
Returns:
41
Graph: Self for method chaining
42
"""
43
44
def parse(self, source: Optional[Union[str, IO, InputSource]] = None, publicID: Optional[str] = None, format: Optional[str] = None, location: Optional[str] = None, file: Optional[IO] = None, data: Optional[Union[str, bytes]] = None, **args) -> 'Graph':
45
"""
46
Parse RDF data into the graph.
47
48
Parameters:
49
- source: Source location (URL, file path, or file-like object)
50
- publicID: Logical URI for the document
51
- format: RDF format ('xml', 'turtle', 'n3', 'nt', 'json-ld', etc.)
52
- location: Physical location hint
53
- file: File-like object
54
- data: RDF data as string
55
56
Returns:
57
Graph: Self for method chaining
58
"""
59
60
def serialize(self, destination: Optional[Union[str, IO]] = None, format: str = 'turtle', base: Optional[str] = None, encoding: Optional[str] = None, **args) -> Union[str, bytes, 'Graph']:
61
"""
62
Serialize the graph to RDF format.
63
64
Parameters:
65
- destination: Output destination (file path or file-like object)
66
- format: Output format ('xml', 'turtle', 'n3', 'nt', 'json-ld', etc.)
67
- base: Base URI for relative references
68
- encoding: Character encoding
69
70
Returns:
71
str: Serialized RDF data if no destination specified
72
"""
73
74
def query(self, query_object: Union[str, Query], processor: str = 'sparql', result: str = 'sparql', initNs: Optional[Mapping[str, Any]] = None, initBindings: Optional[Mapping[str, Identifier]] = None, use_store_provided: bool = True, **kwargs) -> Result:
75
"""
76
Execute a SPARQL query against the graph.
77
78
Parameters:
79
- query_object: Query string or prepared query
80
- processor: Query processor to use
81
- result: Result format
82
- initNs: Initial namespace bindings
83
- initBindings: Initial variable bindings
84
- use_store_provided: Use store's query capabilities if available
85
86
Returns:
87
Result: Query results
88
"""
89
90
def update(self, update_object: Union[str, Update], processor: str = 'sparql', initNs: Optional[Mapping[str, Any]] = None, initBindings: Optional[Mapping[str, Identifier]] = None, use_store_provided: bool = True, **kwargs) -> None:
91
"""
92
Execute a SPARQL update against the graph.
93
94
Parameters:
95
- update_object: Update string or prepared update
96
- processor: Update processor to use
97
- initNs: Initial namespace bindings
98
- initBindings: Initial variable bindings
99
- use_store_provided: Use store's update capabilities if available
100
"""
101
102
def triples(self, triple: Tuple[Node, Node, Node]) -> Iterator[Tuple[Node, Node, Node]]:
103
"""
104
Iterate over triples matching the pattern.
105
106
Parameters:
107
- triple: Pattern tuple (None acts as wildcard)
108
109
Returns:
110
Iterator: Matching triples
111
"""
112
113
def __contains__(self, triple: Tuple[Node, Node, Node]) -> bool:
114
"""
115
Check if graph contains a triple.
116
117
Parameters:
118
- triple: Triple to check
119
120
Returns:
121
bool: True if triple exists
122
"""
123
124
def __len__(self) -> int:
125
"""
126
Get number of triples in graph.
127
128
Returns:
129
int: Triple count
130
"""
131
132
def __iter__(self) -> Iterator[Tuple[Node, Node, Node]]:
133
"""
134
Iterate over all triples in graph.
135
136
Returns:
137
Iterator: All triples
138
"""
139
140
def subjects(self, predicate: Node = None, object: Node = None) -> Iterator[Node]:
141
"""
142
Get subjects matching predicate/object pattern.
143
144
Parameters:
145
- predicate: Predicate to match (None for any)
146
- object: Object to match (None for any)
147
148
Returns:
149
Iterator: Matching subjects
150
"""
151
152
def predicates(self, subject: Node = None, object: Node = None) -> Iterator[Node]:
153
"""
154
Get predicates matching subject/object pattern.
155
156
Parameters:
157
- subject: Subject to match (None for any)
158
- object: Object to match (None for any)
159
160
Returns:
161
Iterator: Matching predicates
162
"""
163
164
def objects(self, subject: Node = None, predicate: Node = None) -> Iterator[Node]:
165
"""
166
Get objects matching subject/predicate pattern.
167
168
Parameters:
169
- subject: Subject to match (None for any)
170
- predicate: Predicate to match (None for any)
171
172
Returns:
173
Iterator: Matching objects
174
"""
175
176
def subject_objects(self, predicate: Node = None) -> Iterator[Tuple[Node, Node]]:
177
"""
178
Get subject-object pairs for predicate.
179
180
Parameters:
181
- predicate: Predicate to match
182
183
Returns:
184
Iterator: (subject, object) pairs
185
"""
186
187
def subject_predicates(self, object: Node = None) -> Iterator[Tuple[Node, Node]]:
188
"""
189
Get subject-predicate pairs for object.
190
191
Parameters:
192
- object: Object to match
193
194
Returns:
195
Iterator: (subject, predicate) pairs
196
"""
197
198
def predicate_objects(self, subject: Node = None) -> Iterator[Tuple[Node, Node]]:
199
"""
200
Get predicate-object pairs for subject.
201
202
Parameters:
203
- subject: Subject to match
204
205
Returns:
206
Iterator: (predicate, object) pairs
207
"""
208
209
def bind(self, prefix: str, namespace: Namespace, override: bool = True):
210
"""
211
Bind namespace prefix.
212
213
Parameters:
214
- prefix: Prefix string
215
- namespace: Namespace URI
216
- override: Whether to override existing binding
217
"""
218
219
def namespace(self, prefix: str) -> Namespace:
220
"""
221
Get namespace for prefix.
222
223
Parameters:
224
- prefix: Prefix string
225
226
Returns:
227
Namespace: Namespace object
228
"""
229
230
def namespaces(self) -> Iterator[Tuple[str, Namespace]]:
231
"""
232
Get all namespace bindings.
233
234
Returns:
235
Iterator: (prefix, namespace) pairs
236
"""
237
238
@property
239
def store(self):
240
"""
241
Get the underlying store.
242
243
Returns:
244
Store: Graph's store implementation
245
"""
246
247
@property
248
def namespace_manager(self) -> NamespaceManager:
249
"""
250
Get the namespace manager.
251
252
Returns:
253
NamespaceManager: Namespace manager instance
254
"""
255
256
@property
257
def identifier(self) -> Node:
258
"""
259
Get the graph identifier.
260
261
Returns:
262
Node: Graph identifier
263
"""
264
```
265
266
### ConjunctiveGraph - Multi-Graph Container
267
268
Container for multiple named graphs. Deprecated in favor of Dataset.
269
270
```python { .api }
271
class ConjunctiveGraph(Graph):
272
def __init__(self, store: str = 'default', identifier: Node = None):
273
"""
274
Create a conjunctive graph.
275
276
Parameters:
277
- store: Store type
278
- identifier: Graph identifier
279
"""
280
281
def get_context(self, identifier: Node) -> Graph:
282
"""
283
Get or create a named graph context.
284
285
Parameters:
286
- identifier: Context identifier
287
288
Returns:
289
Graph: Named graph context
290
"""
291
292
def contexts(self, triple: Tuple[Node, Node, Node] = None) -> Iterator[Graph]:
293
"""
294
Get contexts containing the triple pattern.
295
296
Parameters:
297
- triple: Triple pattern to match
298
299
Returns:
300
Iterator: Matching contexts
301
"""
302
303
@property
304
def default_context(self) -> Graph:
305
"""
306
Get the default context.
307
308
Returns:
309
Graph: Default context
310
"""
311
```
312
313
## Usage Examples
314
315
### Basic Graph Operations
316
317
```python
318
from rdflib import Graph, URIRef, Literal, BNode
319
from rdflib.namespace import RDF, FOAF
320
321
# Create a graph
322
g = Graph()
323
324
# Add triples
325
person = URIRef("http://example.org/person/1")
326
g.add((person, RDF.type, FOAF.Person))
327
g.add((person, FOAF.name, Literal("John Doe")))
328
g.add((person, FOAF.age, Literal(30)))
329
330
# Check if triple exists
331
if (person, FOAF.name, None) in g:
332
print("Person has a name")
333
334
# Get all names
335
for name in g.objects(person, FOAF.name):
336
print(f"Name: {name}")
337
338
# Remove a triple
339
g.remove((person, FOAF.age, None))
340
341
# Get graph size
342
print(f"Graph has {len(g)} triples")
343
```
344
345
### Querying Graphs
346
347
```python
348
from rdflib import Graph
349
350
g = Graph()
351
g.parse("data.ttl", format="turtle")
352
353
# SPARQL SELECT query
354
query = """
355
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
356
SELECT ?name ?email WHERE {
357
?person foaf:name ?name .
358
?person foaf:mbox ?email .
359
}
360
"""
361
362
results = g.query(query)
363
for row in results:
364
print(f"Name: {row.name}, Email: {row.email}")
365
366
# SPARQL CONSTRUCT query
367
construct_query = """
368
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
369
CONSTRUCT { ?person foaf:name ?name }
370
WHERE { ?person foaf:name ?name }
371
"""
372
373
new_graph = g.query(construct_query)
374
```
375
376
### Parsing and Serialization
377
378
```python
379
from rdflib import Graph
380
381
g = Graph()
382
383
# Parse from different sources
384
g.parse("http://example.org/data.rdf") # From URL
385
g.parse("data.ttl", format="turtle") # From file
386
g.parse(data=rdf_string, format="xml") # From string
387
388
# Serialize to different formats
389
turtle_data = g.serialize(format="turtle")
390
xml_data = g.serialize(format="xml")
391
jsonld_data = g.serialize(format="json-ld")
392
393
# Serialize to file
394
g.serialize("output.ttl", format="turtle")
395
```
396
397
### Working with Namespaces
398
399
```python
400
from rdflib import Graph, Namespace
401
from rdflib.namespace import RDF, FOAF
402
403
g = Graph()
404
405
# Bind custom namespace
406
EX = Namespace("http://example.org/")
407
g.bind("ex", EX)
408
409
# Use bound namespace in serialization
410
g.add((EX.person1, RDF.type, FOAF.Person))
411
turtle = g.serialize(format="turtle")
412
# Will use 'ex:' prefix in output
413
```
414
415
### Graph Iteration and Patterns
416
417
```python
418
from rdflib import Graph, URIRef
419
from rdflib.namespace import RDF, FOAF
420
421
g = Graph()
422
# ... add some data ...
423
424
# Iterate over all triples
425
for s, p, o in g:
426
print(f"{s} {p} {o}")
427
428
# Find all people
429
for person in g.subjects(RDF.type, FOAF.Person):
430
print(f"Person: {person}")
431
432
# Get all properties of a person
433
person = URIRef("http://example.org/person/1")
434
for pred, obj in g.predicate_objects(person):
435
print(f"{pred}: {obj}")
436
437
# Pattern matching with wildcards
438
for s, p, o in g.triples((None, FOAF.name, None)):
439
print(f"{s} has name {o}")
440
```