0
# Dataset and Named Graphs
1
2
RDF 1.1 Dataset implementation for working with collections of named graphs. Provides methods for managing multiple graphs within a single container, supporting the W3C RDF 1.1 Dataset specification.
3
4
## Capabilities
5
6
### Dataset - RDF 1.1 Dataset Container
7
8
Primary container for multiple named graphs with a default graph.
9
10
```python { .api }
11
class Dataset:
12
def __init__(self, store: str = 'default', default_union: bool = False, default_graph_base: str = None):
13
"""
14
Create an RDF 1.1 Dataset.
15
16
Parameters:
17
- store: Store type ('Memory', 'SPARQLStore', etc.)
18
- default_union: Whether default graph is union of named graphs
19
- default_graph_base: Base URI for default graph
20
"""
21
22
def graph(self, identifier: Node = None) -> Graph:
23
"""
24
Get or create a named graph.
25
26
Parameters:
27
- identifier: Graph identifier (URIRef or BNode); auto-generated if None
28
29
Returns:
30
Graph: Named graph instance
31
"""
32
33
def add_graph(self, g: Graph) -> 'Dataset':
34
"""
35
Add an existing graph to the dataset.
36
37
Parameters:
38
- g: Graph to add
39
40
Returns:
41
Dataset: Self for method chaining
42
"""
43
44
def remove_graph(self, g: Graph) -> 'Dataset':
45
"""
46
Remove a graph from the dataset.
47
48
Parameters:
49
- g: Graph to remove
50
51
Returns:
52
Dataset: Self for method chaining
53
"""
54
55
@property
56
def default_graph(self) -> Graph:
57
"""
58
Get the default graph.
59
60
Returns:
61
Graph: Default graph instance
62
"""
63
64
def named_graphs(self) -> Iterator[Graph]:
65
"""
66
Iterate over named graphs in the dataset.
67
68
Returns:
69
Iterator: Named graph instances
70
"""
71
72
def contexts(self, triple: Tuple[Node, Node, Node] = None) -> Iterator[Graph]:
73
"""
74
Get contexts (graphs) containing the triple pattern.
75
76
Parameters:
77
- triple: Triple pattern to match
78
79
Returns:
80
Iterator: Matching graph contexts
81
"""
82
83
def quads(self, quad: Tuple[Node, Node, Node, Node] = None) -> Iterator[Tuple[Node, Node, Node, Graph]]:
84
"""
85
Iterate over quads (triples with graph context).
86
87
Parameters:
88
- quad: Quad pattern to match (subject, predicate, object, graph)
89
90
Returns:
91
Iterator: Matching quads
92
"""
93
94
def add(self, quad: Tuple[Node, Node, Node, Node]):
95
"""
96
Add a quad to the dataset.
97
98
Parameters:
99
- quad: (subject, predicate, object, graph) tuple
100
"""
101
102
def remove(self, quad: Tuple[Node, Node, Node, Node]):
103
"""
104
Remove quads matching the pattern.
105
106
Parameters:
107
- quad: Quad pattern (None acts as wildcard)
108
"""
109
110
def parse(self, source, publicID: str = None, format: str = None, location: str = None, file=None, data: str = None, **args):
111
"""
112
Parse RDF data into the dataset.
113
114
Parameters:
115
- source: Source location (URL, file path, or file-like object)
116
- publicID: Logical URI for the document
117
- format: RDF format ('trig', 'nquads', etc.)
118
- location: Physical location hint
119
- file: File-like object
120
- data: RDF data as string
121
122
Returns:
123
Dataset: Self for method chaining
124
"""
125
126
def serialize(self, destination=None, format: str = 'trig', **args) -> str:
127
"""
128
Serialize the dataset to RDF format.
129
130
Parameters:
131
- destination: Output destination (file path or file-like object)
132
- format: Output format ('trig', 'nquads', etc.)
133
134
Returns:
135
str: Serialized RDF data if no destination specified
136
"""
137
138
def query(self, query_object, processor: str = 'sparql', result: str = 'sparql', initNs: Dict[str, Namespace] = None, initBindings: Dict = None, use_store_provided: bool = True, **kwargs):
139
"""
140
Execute a SPARQL query against the dataset.
141
142
Parameters:
143
- query_object: Query string or prepared query
144
- processor: Query processor to use
145
- result: Result format
146
- initNs: Initial namespace bindings
147
- initBindings: Initial variable bindings
148
- use_store_provided: Use store's query capabilities if available
149
150
Returns:
151
Result: Query results
152
"""
153
154
def update(self, update_object, processor: str = 'sparql', initNs: Dict[str, Namespace] = None, initBindings: Dict = None, use_store_provided: bool = True, **kwargs):
155
"""
156
Execute a SPARQL update against the dataset.
157
158
Parameters:
159
- update_object: Update string or prepared update
160
- processor: Update processor to use
161
- initNs: Initial namespace bindings
162
- initBindings: Initial variable bindings
163
- use_store_provided: Use store's update capabilities if available
164
"""
165
166
def __len__(self) -> int:
167
"""
168
Get total number of quads in dataset.
169
170
Returns:
171
int: Quad count across all graphs
172
"""
173
174
def __contains__(self, quad: Tuple[Node, Node, Node, Node]) -> bool:
175
"""
176
Check if dataset contains a quad.
177
178
Parameters:
179
- quad: Quad to check
180
181
Returns:
182
bool: True if quad exists
183
"""
184
```
185
186
## Usage Examples
187
188
### Creating and Managing Datasets
189
190
```python
191
from rdflib import Dataset, Graph, URIRef, Literal
192
from rdflib.namespace import RDF, FOAF, DCTERMS
193
194
# Create a dataset
195
ds = Dataset()
196
197
# Work with the default graph
198
default = ds.default_graph
199
default.add((URIRef("http://example.org/person/1"), RDF.type, FOAF.Person))
200
201
# Create named graphs
202
graph1 = ds.graph(URIRef("http://example.org/graph/personal"))
203
graph2 = ds.graph(URIRef("http://example.org/graph/work"))
204
205
# Add data to named graphs
206
graph1.add((URIRef("http://example.org/person/1"), FOAF.name, Literal("John Doe")))
207
graph1.add((URIRef("http://example.org/person/1"), FOAF.age, Literal(30)))
208
209
graph2.add((URIRef("http://example.org/person/1"), FOAF.title, Literal("Software Engineer")))
210
graph2.add((URIRef("http://example.org/person/1"), FOAF.organization, Literal("TechCorp")))
211
```
212
213
### Querying Datasets with SPARQL
214
215
```python
216
from rdflib import Dataset
217
218
ds = Dataset()
219
# ... populate with data ...
220
221
# Query across all graphs
222
query = """
223
SELECT ?name ?title ?graph WHERE {
224
GRAPH ?graph {
225
?person foaf:name ?name .
226
OPTIONAL { ?person foaf:title ?title }
227
}
228
}
229
"""
230
231
results = ds.query(query)
232
for row in results:
233
print(f"Name: {row.name}, Title: {row.title}, Graph: {row.graph}")
234
235
# Query specific graph
236
specific_query = """
237
SELECT ?name WHERE {
238
GRAPH <http://example.org/graph/personal> {
239
?person foaf:name ?name
240
}
241
}
242
"""
243
244
results = ds.query(specific_query)
245
```
246
247
### Working with Quads
248
249
```python
250
from rdflib import Dataset, URIRef, Literal
251
from rdflib.namespace import FOAF
252
253
ds = Dataset()
254
255
# Add quads directly
256
person = URIRef("http://example.org/person/1")
257
graph_uri = URIRef("http://example.org/graph/data")
258
259
ds.add((person, FOAF.name, Literal("Alice"), graph_uri))
260
ds.add((person, FOAF.age, Literal(25), graph_uri))
261
262
# Iterate over quads
263
for s, p, o, g in ds.quads():
264
print(f"Subject: {s}, Predicate: {p}, Object: {o}, Graph: {g}")
265
266
# Pattern matching with quads
267
for s, p, o, g in ds.quads((person, None, None, None)):
268
print(f"Person property: {p} = {o} in graph {g}")
269
```
270
271
### Parsing and Serializing Datasets
272
273
```python
274
from rdflib import Dataset
275
276
ds = Dataset()
277
278
# Parse dataset formats
279
ds.parse("data.trig", format="trig") # TriG format
280
ds.parse("data.nq", format="nquads") # N-Quads format
281
282
# Serialize to dataset formats
283
trig_data = ds.serialize(format="trig")
284
nquads_data = ds.serialize(format="nquads")
285
286
# Save to file
287
ds.serialize("output.trig", format="trig")
288
```
289
290
### Managing Named Graphs
291
292
```python
293
from rdflib import Dataset, Graph, URIRef
294
from rdflib.namespace import FOAF
295
296
ds = Dataset()
297
298
# Create and populate a graph
299
graph_uri = URIRef("http://example.org/graph/people")
300
people_graph = ds.graph(graph_uri)
301
people_graph.add((URIRef("http://example.org/person/1"), FOAF.name, Literal("John")))
302
303
# Add an existing graph
304
external_graph = Graph()
305
external_graph.add((URIRef("http://example.org/person/2"), FOAF.name, Literal("Jane")))
306
external_graph.identifier = URIRef("http://example.org/graph/external")
307
ds.add_graph(external_graph)
308
309
# Iterate over named graphs
310
for graph in ds.named_graphs():
311
print(f"Graph: {graph.identifier}")
312
for triple in graph:
313
print(f" {triple}")
314
315
# Remove a graph
316
ds.remove_graph(people_graph)
317
```
318
319
### Dataset with Union Default Graph
320
321
```python
322
from rdflib import Dataset, URIRef, Literal
323
from rdflib.namespace import FOAF
324
325
# Create dataset with union default graph
326
ds = Dataset(default_union=True)
327
328
# Add data to named graphs
329
graph1 = ds.graph(URIRef("http://example.org/graph/1"))
330
graph1.add((URIRef("http://example.org/person/1"), FOAF.name, Literal("Alice")))
331
332
graph2 = ds.graph(URIRef("http://example.org/graph/2"))
333
graph2.add((URIRef("http://example.org/person/2"), FOAF.name, Literal("Bob")))
334
335
# Query default graph sees union of named graphs
336
query = """
337
SELECT ?name WHERE {
338
?person foaf:name ?name
339
}
340
"""
341
342
results = ds.default_graph.query(query)
343
for row in results:
344
print(f"Name from union: {row.name}")
345
```
346
347
### SPARQL Updates with Datasets
348
349
```python
350
from rdflib import Dataset
351
352
ds = Dataset()
353
354
# SPARQL update with named graphs
355
update = """
356
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
357
358
INSERT DATA {
359
GRAPH <http://example.org/graph/people> {
360
<http://example.org/person/1> foaf:name "John Doe" ;
361
foaf:age 30 .
362
}
363
}
364
"""
365
366
ds.update(update)
367
368
# Move data between graphs
369
move_update = """
370
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
371
372
DELETE {
373
GRAPH <http://example.org/graph/people> {
374
?person foaf:age ?age
375
}
376
}
377
INSERT {
378
GRAPH <http://example.org/graph/demographics> {
379
?person foaf:age ?age
380
}
381
}
382
WHERE {
383
GRAPH <http://example.org/graph/people> {
384
?person foaf:age ?age
385
}
386
}
387
"""
388
389
ds.update(move_update)
390
```