Module 21: RDF and SPARQL with Oxigraph¶
Learning objectives
By the end of this module, you can:
- O1. Open an
OxigraphLensin memory or in a folder, write a DDI file to it, and read or purge one dataset. - O2. Query the store in SPARQL with
lens.store.query, and run addigraph.queryon it withrun, reading the SPARQL thatto_sparqlwrites. - O3. Write SHACL shapes with
ddigraph shapesorshapes_graph(flavor=), and check an export with pyshacl orddigraph validate. - O4. Read an RDF file back into ddigraph's graph with
read_graph. - O5. Predict what Oxigraph does to a language tag, and which tags it refuses.
Prerequisites: Module 8
Time: 45 min self-paced / 60 min instructor-led.
Needs: No server. Oxigraph runs inside Python. Install the oxigraph and shacl extras. The Neo4j tabs, which are optional, need Neo4j 5 as in Module 7.
New in this module: OxigraphLens, lens.store.query, lens.store.update, lens.store.dump, ddigraph.query.run, to_sparql, ddigraph shapes, shapes_graph, ddigraph validate FILE.ttl, read_graph, bcp47_case
1. An RDF store with SPARQL built in¶
In Module 8 you exported a DDI file as Turtle and queried it with rdflib. rdflib reads the whole file into memory each time you start. That is fine for one small file. For many files, or for a graph you keep, you want a triple store: a database for RDF. It keeps the triples, indexes them, and answers SPARQL queries.
Oxigraph is a small, fast triple store. It runs inside your Python process, in memory or in a folder, so it needs no server. Install it with the extras for this module:
pip install "ddigraph[oxigraph,shacl]"
ddigraph talks to Oxigraph through a lens. A lens is ddigraph's word for a backend that can write the graph and read it back. The Oxigraph lens writes the same triples as a Turtle export. It puts them in the store's default graph, the one graph with no name. A store can also hold named graphs, but the lens never reads or changes them.
This module uses the course's sample survey, a Labour Force Survey of the third quarter of 2025. Write its Codebook file to a store in memory:
from ddigraph import ir
from ddigraph.lens.oxigraph import OxigraphLens
lens = OxigraphLens() # no folder: the store lives in memory
stream = ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m21-codebook")
result = lens.write(stream, dataset_id="m21-codebook")
print(result.nodes, "nodes,", result.relationships, "relationships")
print(len(lens.store), "triples in the store")
Expected output:
80 nodes, 48 relationships
1343 triples in the store
ir.parse reads the file into ddigraph's graph stream, the same stream
every backend writes. A Codebook file needs a dataset_id, because its
IDs only mean something inside one file. lens.store is the Oxigraph
Store itself. The 80 nodes become 1343 triples: types, properties, and
the records that let ddigraph rebuild the graph exactly.
2. A store in a folder¶
Give OxigraphLens a folder and the store lives on disk. It is still
there when your program ends. The script below runs Python twice. The
first run writes the survey twice: as Codebook and as DDI-Lifecycle, two
datasets. The second run opens the same folder, finds the triples, purges
one dataset and reads the other back:
python - <<'PY'
from ddigraph import ir
from ddigraph.lens.oxigraph import OxigraphLens
lens = OxigraphLens("m21-store") # made if it does not exist
for path, dataset_id in [
("tests/fixtures/lfs_codebook.xml", "m21-codebook"),
("tests/fixtures/lfs_lifecycle.xml", "m21-survey"),
]:
lens.write(ir.parse(path, dataset_id=dataset_id), dataset_id=dataset_id)
print("first run:", len(lens.store), "triples")
PY
python - <<'PY'
from ddigraph.lens.oxigraph import OxigraphLens
lens = OxigraphLens("m21-store")
print("second run:", len(lens.store), "triples")
print(lens.purge("m21-survey"), "nodes purged")
nodes = [node for chunk in lens.read(dataset_id="m21-codebook") for node in chunk.nodes]
print(len(nodes), "nodes read from m21-codebook")
print(len(lens.store), "triples left")
PY
Expected output:
first run: 3449 triples
second run: 3449 triples
87 nodes purged
80 nodes read from m21-codebook
1343 triples left
purge removes one dataset and keeps every node another dataset also
holds. read gives the dataset back as the same stream ir.parse made.
These are the same calls every ddigraph lens has.
Two things to know about a folder store:
- One user at a time. While a lens has the folder open, it holds a
lock. A second
OxigraphLens("m21-store"), in the same program or another one, raisesOSError. Close the first program before you open the folder again. - Each call copies the graph. A write, read or purge copies the
store's default graph into memory, makes the change there, and writes
back only what changed. So a call slows down as the store grows: a few
seconds at 100,000 triples. To fill a big store, export Turtle with
ddigraph exportand load the file with Oxigraph's ownStore.load. The RDF backend page says more.
3. Ask the store in SPARQL¶
SPARQL is the query language of RDF. A query names a pattern of triples,
with ?variables in the places you want filled. lens.store.query runs
one and gives back one solution per match. Each value in a solution is an
Oxigraph term, and .value is its text.
The first query lists each variable of the Codebook file with its concept. It uses DISCO terms, the DDI Alliance's RDF vocabulary, and SKOS. The Neo4j tab asks the same question of Neo4j in Cypher, after it loads the file as in Module 7. It is optional, and needs Neo4j running:
from neo4j import GraphDatabase
import ddigraph
from ddigraph.config import Settings
ddigraph.bootstrap()
ddigraph.load("tests/fixtures/lfs_codebook.xml", dataset_id="m21-codebook", replace=True)
settings = Settings()
auth = (settings.neo4j_user, settings.neo4j_password.get_secret_value())
with GraphDatabase.driver(settings.neo4j_uri, auth=auth) as driver:
records, _, _ = driver.execute_query(
"""
MATCH (v:Variable)-[:IN_DATASET]->(:Dataset {dataset_id: $dataset})
MATCH (v)-[:USES_CONCEPT]->(c:Concept)
RETURN v.name AS name, c.label AS concept
ORDER BY name
""",
dataset="m21-codebook",
)
for record in records:
print(record["name"], "->", record["concept"])
AGE -> Demographic characteristics
AGEGRP -> Demographic characteristics
EDUC -> Educational attainment
HOURS -> Working time
ILOSTAT -> Labour market status
REGION -> Place of residence
SEX -> Demographic characteristics
Cypher follows the graph's own USES_CONCEPT edge, and reads the
concept's label property.
from ddigraph import ir
from ddigraph.lens.oxigraph import OxigraphLens
lens = OxigraphLens()
lens.write(
ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m21-codebook"),
dataset_id="m21-codebook",
)
rows = lens.store.query("""
PREFIX ddigraph: <https://pbisson44.github.io/ddigraph/ns/1.0/>
PREFIX disco: <http://rdf-vocabulary.ddialliance.org/discovery#>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
SELECT ?name ?concept
WHERE {
?variable a disco:Variable ;
ddigraph:name ?name ;
disco:concept ?c .
?c skos:prefLabel ?concept .
}
ORDER BY ?name
""")
for row in rows:
print(row["name"].value, "->", row["concept"].value)
AGE -> Demographic characteristics
AGEGRP -> Demographic characteristics
EDUC -> Educational attainment
HOURS -> Working time
ILOSTAT -> Labour market status
REGION -> Place of residence
SEX -> Demographic characteristics
SPARQL follows the published disco:concept triple, and reads the
concept's skos:prefLabel. The export writes both the published term
and the ddigraph one, so ddigraph:usesConcept would work too.
The answers are the same: it is one graph, in two databases. In the
SPARQL, a is short for rdf:type. Each PREFIX line gives a short name
to a namespace. ddigraph.rdf.PREFIXES holds every prefix the export
uses, if you would rather build the lines in code.
The second query counts the categories of each code list in the
DDI-Lifecycle file. A count is a quick check of a code list: a list with
only one category would be a mistake. In the graph, a code list reaches
its categories through its codes, when the codes have IDs. SKOS is
simpler: each category says which code list, or concept scheme, it
belongs to, with skos:inScheme. So the SPARQL needs one pattern where
Cypher needs two paths:
from neo4j import GraphDatabase
import ddigraph
from ddigraph.config import Settings
ddigraph.bootstrap()
ddigraph.load("tests/fixtures/lfs_lifecycle.xml", dataset_id="m21-survey", replace=True)
settings = Settings()
auth = (settings.neo4j_user, settings.neo4j_password.get_secret_value())
with GraphDatabase.driver(settings.neo4j_uri, auth=auth) as driver:
records, _, _ = driver.execute_query(
"""
MATCH (cl:CodeList)-[:IN_DATASET]->(:Dataset {dataset_id: $dataset})
MATCH (cl)-[:CONTAINS*0..1]->()-[:HAS_CATEGORY]->(cat:Category)
RETURN cl.label AS code_list, count(cat) AS categories
ORDER BY code_list
""",
dataset="m21-survey",
)
for record in records:
print(record["code_list"], "->", record["categories"])
Age group -> 6
Highest level of education -> 5
Labour force status (ILO) -> 3
Region -> 5
Sex -> 2
Yes or no -> 2
[:CONTAINS*0..1] takes zero or one CONTAINS step: through a code
that has an ID, as in this file, or straight from the code list when
the code has none, as in some DDI 3.1 files.
from ddigraph import ir
from ddigraph.lens.oxigraph import OxigraphLens
lens = OxigraphLens()
lens.write(
ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id="m21-survey"),
dataset_id="m21-survey",
)
rows = lens.store.query("""
PREFIX ddigraph: <https://pbisson44.github.io/ddigraph/ns/1.0/>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
SELECT ?list (COUNT(?member) AS ?categories)
WHERE {
?scheme a ddigraph:CodeList ;
skos:prefLabel ?list .
?member a ddigraph:Category ;
skos:inScheme ?scheme .
}
GROUP BY ?list
ORDER BY ?list
""")
for row in rows:
print(row["list"].value, "->", row["categories"].value)
Age group -> 6
Highest level of education -> 5
Labour force status (ILO) -> 3
Region -> 5
Sex -> 2
Yes or no -> 2
The export writes skos:inScheme from each category to its code
list, even when a code with an ID sits between them. So one pattern
covers both kinds of code. GROUP BY and COUNT work as in SQL.
Every list has at least two categories. "Yes or no" has two, and three questions share it: WORK, LOOK and AVAIL.
A Codebook category keeps its code, such as 1 for Employed, and the
export writes it as skos:notation, the SKOS term for a code. This query
reads the codes and categories of the variable ILOSTAT:
from ddigraph import ir
from ddigraph.lens.oxigraph import OxigraphLens
lens = OxigraphLens()
lens.write(
ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m21-codebook"),
dataset_id="m21-codebook",
)
rows = lens.store.query("""
PREFIX ddigraph: <https://pbisson44.github.io/ddigraph/ns/1.0/>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
SELECT ?code ?category
WHERE {
?variable ddigraph:name "ILOSTAT" ;
ddigraph:usesCategory ?member .
?member skos:notation ?code ;
skos:prefLabel ?category .
}
ORDER BY ?code
""")
for row in rows:
print(row["code"].value, row["category"].value)
Expected output:
1 Employed
2 Unemployed
3 Not in the labour force
The three codes are the labour force status of the ILO, the International Labour Organization: each person aged 15 and over is in exactly one of them.
SPARQL can change the store too. lens.store.update runs an update, such
as DELETE or INSERT. Section 5 uses one to break the graph on purpose.
4. One query, many engines¶
Writing SPARQL by hand means you must know how the export lays the graph
out. ddigraph.query lets you skip that. You write a small, typed query
once, in Python. run turns it into the language of the engine and gives
back plain rows. The same query runs in memory, on Neo4j, on SQL and on
Oxigraph. Module 10 shows all of
them.
Here, the first question of section 3, asked through ddigraph.query:
from ddigraph import ir
from ddigraph.lens.oxigraph import OxigraphLens
from ddigraph.query import Query, asc, edge, node, prop, run, to_sparql
lens = OxigraphLens()
lens.write(
ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m21-codebook"),
dataset_id="m21-codebook",
)
query = Query(
match=[node("v", "Variable"), node("c", "Concept"), edge("v", "USES_CONCEPT", "c")],
returns=[prop("v", "name"), prop("c", "name")],
order_by=[asc(prop("v", "name"))],
)
print(to_sparql(query))
for row in run(query, lens):
print(row)
Expected output:
PREFIX ddigraph: <https://pbisson44.github.io/ddigraph/ns/1.0/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
SELECT (STR(?_p0) AS ?_t0) (LANG(?_p0) AS ?_l0) (STR(?_p1) AS ?_t1) (LANG(?_p1) AS ?_l1) (1 AS ?_row)
WHERE {
?v ddigraph:key ?_k_v .
?v a ddigraph:Variable .
?c ddigraph:key ?_k_c .
?c a ddigraph:Concept .
?_e0 rdf:subject ?v ; rdf:predicate ddigraph:usesConcept ; rdf:object ?c .
FILTER(STRSTARTS(STR(?_e0), "urn:ddigraph:relationship:"))
OPTIONAL { ?v ddigraph:name ?_p0 . FILTER NOT EXISTS { ?v ddigraph:name ?_o0 . FILTER(LANG(?_p0) != "" && (LANG(?_o0) = "" || LCASE(LANG(?_o0)) < LCASE(LANG(?_p0)))) } }
OPTIONAL { ?c ddigraph:name ?_p1 . FILTER NOT EXISTS { ?c ddigraph:name ?_o1 . FILTER(LANG(?_p1) != "" && (LANG(?_o1) = "" || LCASE(LANG(?_o1)) < LCASE(LANG(?_p1)))) } }
}
ORDER BY ASC(!BOUND(?_t0)) ASC(?_t0) ASC(LCASE(COALESCE(?_l0, ""))) ASC(COALESCE(?_l0, ""))
(Text(value='AGE', lang=None), Text(value='Demographic characteristics', lang=None))
(Text(value='AGEGRP', lang=None), Text(value='Demographic characteristics', lang=None))
(Text(value='EDUC', lang=None), Text(value='Educational attainment', lang=None))
(Text(value='HOURS', lang=None), Text(value='Working time', lang=None))
(Text(value='ILOSTAT', lang=None), Text(value='Labour market status', lang=None))
(Text(value='REGION', lang=None), Text(value='Place of residence', lang=None))
(Text(value='SEX', lang=None), Text(value='Demographic characteristics', lang=None))
The rows are the ones section 3 found. Now read the SPARQL that
to_sparql wrote. It matches each node by its
ddigraph class, such as ddigraph:Variable. It finds the edge through
its rdf:Statement, the record the export writes for each relationship,
not through the plain ddigraph:usesConcept triple. A plain triple
appears once, even when two relationships join the same two nodes. A
statement appears once per relationship, so every engine gives the same
number of rows. The properties sit in OPTIONAL, so a node with no name
still gives a row. A text can have one literal per language, so the
FILTER NOT EXISTS keeps one: the literal with no language, or else the
one whose tag sorts first.
The query is checked as you build it. A label, relationship type or
property that does not exist raises ValueError, with the nearest valid
name.
5. Check the graph with SHACL¶
SHACL is a W3C language for rules about the shape of an RDF graph. A rule set is a shapes graph. A SHACL engine, such as pyshacl, checks a data graph against it and reports each node that breaks a rule.
ddigraph writes its own shapes, generated from the same mapping that
drives the export. Each shape checks one node type: one ddigraph:key,
at most one value of the right type for each property (for a text, one
per language), and each required property, unless the node is a stub. From the command line:
ddigraph export tests/fixtures/lfs_codebook.xml --format turtle -o codebook.ttl \
--dataset-id m21-codebook
ddigraph shapes -o shapes.ttl --flavor codebook
ddigraph validate codebook.ttl --flavor codebook
Expected output:
Wrote codebook.ttl
Format: turtle
Nodes: 80 Relationships: 48
Triples: 1343
Wrote shapes.ttl
Flavor: codebook
Triples: 5022
File: .../codebook.ttl
Shapes: codebook (1343 triples)
Shapes result: conforms
ddigraph validate sees the .ttl file and runs SHACL instead of the
XSD check. The 1343 triples are the data's. Pass --flavor: an RDF file
does not say which DDI flavor it came from, and 21 type names, such as
Category, exist in both Codebook and DDI-Lifecycle with other
properties. Without --flavor, such a node passes if it fits either one.
In Python, shapes_graph(flavor=) gives the same shapes as an rdflib
graph, ready for pyshacl. The store holds the same triples as an export,
so you can check it too. Dump its default graph to Turtle, then validate.
This script first breaks the graph with a SPARQL update, so there is
something to find:
import pyshacl
import rdflib
from pyoxigraph import DefaultGraph, RdfFormat
from ddigraph import ir
from ddigraph.lens.oxigraph import OxigraphLens
from ddigraph.rdf.shacl import shapes_graph
lens = OxigraphLens()
lens.write(
ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m21-codebook"),
dataset_id="m21-codebook",
)
# Remove the key of the variable HOURS: every node must have exactly one
lens.store.update("""
PREFIX ddigraph: <https://pbisson44.github.io/ddigraph/ns/1.0/>
DELETE WHERE { <urn:ddigraph:scoped:m21-codebook:V7> ddigraph:key ?key }
""")
lens.store.dump("m21.ttl", RdfFormat.TURTLE, from_graph=DefaultGraph())
data = rdflib.Graph().parse("m21.ttl", format="turtle")
conforms, results, _text = pyshacl.validate(data, shacl_graph=shapes_graph(flavor="codebook"))
print("conforms:", conforms)
for focus, path in results.query("""
PREFIX sh: <http://www.w3.org/ns/shacl#>
SELECT ?focus ?path WHERE { ?r a sh:ValidationResult ; sh:focusNode ?focus ; sh:resultPath ?path }
"""):
print(focus, path)
Expected output:
conforms: False
urn:ddigraph:scoped:m21-codebook:V7 https://pbisson44.github.io/ddigraph/ns/1.0/key
pyshacl.validate gives three things: whether the graph conforms, the
results as an RDF graph, and a text report. The results graph is RDF, so
you read it with SPARQL too. Each result names the focus node that
broke a rule and the path, the predicate the rule was about. Here the
focus node is HOURS, the variable with the ID V7 in the file.
The shapes check each node on its own. They do not check what an edge points at. Module 6 shows the other checks.
6. Read it back¶
RDF can also go back in. read_graph reads Turtle, JSON-LD, N-Triples or
RDF/XML that ddigraph wrote, and gives the same stream as ir.parse. So
a graph can travel as Turtle and come back as nodes and edges.
A file can hold several datasets, as a dump of the folder store from
section 2 would. read_graph then needs to know which one you want:
from pyoxigraph import DefaultGraph, RdfFormat
from ddigraph import ir
from ddigraph.lens.oxigraph import OxigraphLens
from ddigraph.rdf.reader import read_graph
lens = OxigraphLens()
for path, dataset_id in [
("tests/fixtures/lfs_codebook.xml", "m21-codebook"),
("tests/fixtures/lfs_lifecycle.xml", "m21-survey"),
]:
lens.write(ir.parse(path, dataset_id=dataset_id), dataset_id=dataset_id)
lens.store.dump("both.ttl", RdfFormat.TURTLE, from_graph=DefaultGraph())
try:
list(read_graph("both.ttl"))
except ValueError as error:
print("ValueError:", error)
nodes = [node for chunk in read_graph("both.ttl", dataset_id="m21-survey") for node in chunk.nodes]
print(len(nodes), "nodes:", sorted({node.label for node in nodes}))
Expected output:
ValueError: both.ttl holds 2 datasets ['m21-codebook', 'm21-survey']; name the one to read with dataset_id
87 nodes: ['Category', 'Code', 'CodeList', 'Concept', 'Dataset', 'IfThenElse', 'Instrument', 'QuestionConstruct', 'QuestionItem', 'Sequence', 'Universe', 'Variable']
read_graph reads only what ddigraph wrote. It takes each node's identity
from its IRI and each edge from its rdf:Statement. It never guesses. A
file with no dataset, or a key that does not match its IRI, raises
ValueError. You can also load such a file straight into Neo4j with
ddigraph load survey.ttl, as Module 8 showed.
7. Language tags in Oxigraph¶
A text in RDF can carry a language tag, such as "Employed"@en-CA.
Tags ignore case, so EN-ca and en-CA are the same tag. Oxigraph
stores every tag in lower case. When the lens reads a text back, it
writes the tag in the case BCP 47, the standard for tags, recommends:
en-CA, zh-Hant. rdflib keeps a tag as it was written.
The script below gives the category Employed of the DDI-L file a label
tagged EN-ca, in place of en. It writes the file to an rdflib lens and
to the Oxigraph lens, reads both back, and asks SPARQL for the tag:
from pathlib import Path
from ddigraph import ir
from ddigraph.lens.oxigraph import OxigraphLens, bcp47_case
from ddigraph.lens.rdf import RDFLens
xml = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
english = '<r:Content xml:lang="en">Employed</r:Content>'
labelled = '<r:Content xml:lang="EN-ca">Employed</r:Content>'
Path("tagged.xml").write_text(xml.replace(english, labelled))
for lens in (RDFLens(), OxigraphLens()):
lens.write(ir.parse("tagged.xml", dataset_id="m21-tags"), dataset_id="m21-tags")
for chunk in lens.read(dataset_id="m21-tags"):
for node in chunk.nodes:
if node.label == "Category" and node.properties["label"].value == "Employed":
print(type(lens).__name__, "reads", node.properties["label"])
rows = lens.store.query("""
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
SELECT (LANG(?label) AS ?tag)
WHERE { ?category a skos:Concept ; skos:prefLabel ?label . FILTER(STR(?label) = "Employed") }
""")
print("SPARQL LANG():", [row["tag"].value for row in rows])
print("bcp47_case:", bcp47_case("EN-ca"))
Expected output:
RDFLens reads Text(value='Employed', lang='EN-ca')
OxigraphLens reads Text(value='Employed', lang='en-CA')
SPARQL LANG(): ['en-ca']
bcp47_case: en-CA
So a tag already in the recommended case, such as en-CA or fr, reads
back as you wrote it. A tag in another case comes back in the recommended
one. Inside the store, SPARQL sees the lower-case form. ddigraph.query
compares language tags in lower case for this reason.
Oxigraph is also stricter than DDI. DDI's xs:language type allows tags
that are not valid BCP 47, such as en-a. Oxigraph refuses them, so the
write raises ValueError, and the store does not change. Exercise 4
tries one.
Exercises¶
Scenario
Your team keeps the DDI-CDI metadata of the Labour Force Survey. A linked-data group wants it in a triple store they can query with SPARQL, and checked before they trust it.
Exercise 1 (O1, O2). Write tests/fixtures/lfs_cdi.xml, the survey in
DDI-CDI, to a folder store m21-cdi-store as dataset m21-cdi. Then, in a
second Python run, open the folder again and count the nodes of each
ddigraph class with one SPARQL query, most common first. Leave out the
Membership records.
Expected output:
CDICategory 21
CDICode 21
CDIGenericEntity 21
...
Dataset 1
Answer
python - <<'PY'
from ddigraph import ir
from ddigraph.lens.oxigraph import OxigraphLens
lens = OxigraphLens("m21-cdi-store")
lens.write(ir.parse("tests/fixtures/lfs_cdi.xml", dataset_id="m21-cdi"), dataset_id="m21-cdi")
PY
python - <<'PY'
from ddigraph.lens.oxigraph import OxigraphLens
lens = OxigraphLens("m21-cdi-store")
rows = lens.store.query("""
PREFIX ddigraph: <https://pbisson44.github.io/ddigraph/ns/1.0/>
SELECT ?class (COUNT(?node) AS ?n)
WHERE {
?node a ?class .
FILTER(STRSTARTS(STR(?class), STR(ddigraph:)))
FILTER(?class != ddigraph:Membership)
}
GROUP BY ?class
ORDER BY DESC(?n) ?class
""")
for row in rows:
print(row["class"].value.removeprefix("https://pbisson44.github.io/ddigraph/ns/1.0/"), row["n"].value)
PY
CDICategory 21
CDICode 21
CDIGenericEntity 21
CDIInstanceVariable 7
CDIValueDomain 7
CDICodeList 5
CDIConcept 5
CDIAgent 1
CDIConceptSystem 1
CDIUnitType 1
Dataset 1
The second run finds the triples because the store lives in the folder.
Every node carries its ddigraph class, so one GROUP BY counts them.
The filter drops the ddigraph:Membership records, which say which
dataset holds each node but are not nodes themselves. The counts read
like the survey: 21 codes, each with its category and its notation,
the generic entity that holds the code's value; 7 variables, each with
its value domain; 5 code lists.
Exercise 2 (O2). tests/fixtures/lfs_correspondence.xml holds a
DDI-CDI correspondence table. It maps the levels of ISCED 1997, the
education classification, to those of ISCED 2011. Each map in the table,
a CDIConceptMap, has a source category (HAS_SOURCE) and a target
category (HAS_TARGET). Write a ddigraph.query that returns the name of
each map's source and target category, sorted, and run it on an Oxigraph
store.
Expected output:
('0 Pre-primary', '0 Early childhood education')
...
('6 Advanced research (second stage of tertiary)', '8 Doctoral or equivalent')
Answer
from ddigraph import ir
from ddigraph.lens.oxigraph import OxigraphLens
from ddigraph.query import Query, asc, edge, node, prop, run
lens = OxigraphLens()
lens.write(
ir.parse("tests/fixtures/lfs_correspondence.xml", dataset_id="m21-isced"),
dataset_id="m21-isced",
)
query = Query(
match=[
node("map", "CDIConceptMap"),
node("source", "CDICategory"),
node("target", "CDICategory"),
edge("map", "HAS_SOURCE", "source"),
edge("map", "HAS_TARGET", "target"),
],
returns=[prop("source", "name"), prop("target", "name")],
order_by=[asc(prop("source", "name")), asc(prop("target", "name"))],
)
for row in run(query, lens):
print(row)
(Text(value='0 Pre-primary', lang=None), Text(value='0 Early childhood education', lang=None))
(Text(value='1 Primary', lang=None), Text(value='1 Primary', lang=None))
(Text(value='2 Lower secondary', lang=None), Text(value='2 Lower secondary', lang=None))
(Text(value='3 Upper secondary', lang=None), Text(value='3 Upper secondary', lang=None))
(Text(value='4 Post-secondary non-tertiary', lang=None), Text(value='4 Post-secondary non-tertiary', lang=None))
(Text(value='5A Tertiary, theory-based (first stage)', lang=None), Text(value="6 Bachelor's or equivalent", lang=None))
(Text(value='5A Tertiary, theory-based (first stage)', lang=None), Text(value="7 Master's or equivalent", lang=None))
(Text(value='5B Tertiary, practical (first stage)', lang=None), Text(value='5 Short-cycle tertiary', lang=None))
(Text(value='6 Advanced research (second stage of tertiary)', lang=None), Text(value='8 Doctoral or equivalent', lang=None))
Two edge patterns start from the same map: one to its source, one
to its target. run writes the SPARQL for you, with one
rdf:Statement pattern per edge. Level 5A gives two rows: ISCED 2011
split it into Bachelor's and Master's. The file's other
correspondence maps age groups, which are concepts, not categories,
so the labels in node() leave it out. The export also writes each
map with XKOS terms, xkos:sourceConcept and xkos:targetConcept,
for tools that read XKOS.
Exercise 3 (O3). Export tests/fixtures/lfs_lifecycle.xml as
Turtle. Give the question HOURS a second English ddigraph:name,
USUAL_HOURS tagged en, with rdflib. Save the file as broken.ttl,
and check it with ddigraph validate. Print the exit code too.
Expected output:
File: .../broken.ttl
Shapes: lifecycle (2107 triples)
Shapes result: does not conform (1 result(s))
urn:ddi:example.nso:q-hours:1 https://pbisson44.github.io/ddigraph/ns/1.0/name: More than one String shares the same Language
exit code: 1
Answer
ddigraph export tests/fixtures/lfs_lifecycle.xml --format turtle -o survey.ttl > /dev/null
python - <<'PY'
import rdflib
name = rdflib.URIRef("https://pbisson44.github.io/ddigraph/ns/1.0/name")
graph = rdflib.Graph().parse("survey.ttl", format="turtle")
graph.add((rdflib.URIRef("urn:ddi:example.nso:q-hours:1"), name, rdflib.Literal("USUAL_HOURS", lang="en")))
graph.serialize("broken.ttl", format="turtle")
PY
ddigraph validate broken.ttl --flavor lifecycle || echo "exit code: $?"
File: .../broken.ttl
Shapes: lifecycle (2107 triples)
Shapes result: does not conform (1 result(s))
urn:ddi:example.nso:q-hours:1 https://pbisson44.github.io/ddigraph/ns/1.0/name: More than one String shares the same Language
exit code: 1
A shape allows one value per language for a text, and the question
now has two English names. ddigraph validate exits with 1 when the file does
not conform, so a script or a CI job can stop on it.
Exercise 4 (O5). Predict, then check: write the label of the
category Employed in tests/fixtures/lfs_lifecycle.xml with each of the
tags fr, FR-ca, zh-hant-tw and en-a to a new Oxigraph store.
Print the tag each one reads back as, or the error.
Expected output:
fr -> fr
FR-ca -> fr-CA
zh-hant-tw -> zh-Hant-TW
en-a -> ValueError
Answer
from pathlib import Path
from ddigraph import ir
from ddigraph.lens.oxigraph import OxigraphLens
xml = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
english = '<r:Content xml:lang="en">Employed</r:Content>'
for tag in ["fr", "FR-ca", "zh-hant-tw", "en-a"]:
labelled = f'<r:Content xml:lang="{tag}">Employed</r:Content>'
Path("tagged.xml").write_text(xml.replace(english, labelled))
lens = OxigraphLens()
try:
lens.write(ir.parse("tagged.xml", dataset_id="m21-tags"), dataset_id="m21-tags")
except ValueError:
print(tag, "-> ValueError")
continue
for chunk in lens.read(dataset_id="m21-tags"):
for node in chunk.nodes:
if node.label == "Category" and node.properties["label"].value == "Employed":
print(tag, "->", node.properties["label"].lang)
fr -> fr
FR-ca -> fr-CA
zh-hant-tw -> zh-Hant-TW
en-a -> ValueError
Oxigraph keeps each tag in lower case, and the lens gives it back in
the recommended case: a two-letter region in upper case, a four-letter
script in title case. en-a is allowed by DDI but is not valid BCP
47, so Oxigraph refuses it and the write changes nothing.
Exercise 5 (O3, O4). Write the Codebook and DDI-L files of the survey
to one store, as m21-codebook and m21-survey, and dump it to Turtle.
Read each dataset back with read_graph, write it to an rdflib lens, and
check that graph with the shapes of its own flavor. Print the dataset,
its node count and whether it conforms.
Expected output:
m21-codebook 80 True
m21-survey 87 True
Answer
import pyshacl
from pyoxigraph import DefaultGraph, RdfFormat
from ddigraph import ir
from ddigraph.lens.oxigraph import OxigraphLens
from ddigraph.lens.rdf import RDFLens
from ddigraph.rdf.reader import read_graph
from ddigraph.rdf.shacl import shapes_graph
datasets = {
"m21-codebook": ("tests/fixtures/lfs_codebook.xml", "codebook"),
"m21-survey": ("tests/fixtures/lfs_lifecycle.xml", "lifecycle"),
}
lens = OxigraphLens()
for dataset_id, (path, _flavor) in datasets.items():
lens.write(ir.parse(path, dataset_id=dataset_id), dataset_id=dataset_id)
lens.store.dump("both.ttl", RdfFormat.TURTLE, from_graph=DefaultGraph())
for dataset_id, (_path, flavor) in datasets.items():
chunks = list(read_graph("both.ttl", dataset_id=dataset_id))
one = RDFLens()
one.write(chunks, dataset_id=dataset_id)
conforms, _results, _text = pyshacl.validate(one.graph, shacl_graph=shapes_graph(flavor=flavor))
print(dataset_id, sum(len(chunk.nodes) for chunk in chunks), conforms)
m21-codebook 80 True
m21-survey 87 True
A file mixes flavors, but each dataset has one. Reading the datasets apart lets you check each with the full shapes of its flavor, which is stricter than the all-flavor shapes a mixed file would need.
Quiz¶
Question 1 (O1): A notebook has the folder store m21-store open in a lens. You run a script that opens the same folder. What happens?
A. The script sees the store as it was when the notebook opened it.
B. The script raises OSError, because the notebook holds the folder's lock.
C. The script opens a second, empty store next to the first.
D. Both work, and the last one to write wins.
Answer
B. A folder store is open in one place at a time. The lock protects the files from two writers. A looks reasonable, since a database often gives each reader a snapshot, but Oxigraph refuses the second opening outright. Close the notebook's lens, or end its kernel, before the script runs.
Question 2 (O2): Why does the SPARQL from to_sparql match a relationship through its rdf:Statement, not through the plain ddigraph:usesConcept triple?
A. The plain triple is not in the store; only statements are.
B. Oxigraph cannot match a triple whose predicate is in the ddigraph namespace.
C. A statement exists once per relationship, so the query gives one row per relationship, as the other engines do.
D. Statements are faster to match than plain triples.
Answer
C. A plain triple is a fact: it appears once, however many
relationships say it. Two USES_CONCEPT relationships between the
same two nodes would be one triple but two statements, and two rows
in Neo4j. A is tempting, but the export writes both: the plain
triple for other tools, and the statement so ddigraph can count and
order the relationships.
Question 3 (O3): One Turtle file holds a Codebook dataset and a DDI-L dataset. ddigraph validate both.ttl --flavor lifecycle reports more than 100 results, though each dataset conforms on its own. Why?
A. The file is broken: dumping a store loses triples.
B. The Lifecycle shapes check the Codebook nodes too, and Codebook types such as Concept have other properties there.
C. --flavor only works on DDI XML files.
D. Two datasets in one file always fail SHACL.
Answer
B. A shape targets a ddigraph class, such as
ddigraph:Concept, whatever dataset the node is in. With
--flavor lifecycle, the Codebook concepts must meet the DDI-L
rules, and they do not. Check each dataset on its own, as in
Exercise 5, or leave out --flavor, which accepts either flavor's
shape but checks less. D is wrong: the same file conforms without
--flavor.
Question 4 (O4): Reading both.ttl with read_graph raises ValueError and names two datasets. What is the fix?
A. Pass format="turtle".
B. Pass dataset_id= with the dataset you want to read.
C. Load the file into Oxigraph first, then call read_graph.
D. Remove the ddigraph:Membership records from the file.
Answer
B. read_graph gives one dataset's stream, the way ir.parse
gives one file's. When a file holds several, you name one. A
does nothing here: the format comes from the .ttl extension.
D would break the file, since the membership records say which
dataset holds each node.
Question 5 (O5): You write a label tagged EN-gb to an Oxigraph store. What does SPARQL's LANG() give in the store, and what does lens.read give?
A. EN-gb and EN-gb.
B. en-gb and en-gb.
C. en-gb and en-GB.
D. The write fails: EN-gb is not a valid tag.
Answer
C. Oxigraph keeps every tag in lower case, and SPARQL sees what is stored. The lens rewrites the tag in the case BCP 47 recommends when it reads. D is wrong: case does not make a tag invalid. An rdflib lens would give A.
Question 6 (O1): Your Oxigraph store holds two million triples, and each lens.write now takes minutes. What is the better way to add a large file?
A. Use a smaller chunk_size in ir.parse.
B. Export the file as Turtle with ddigraph export, then load it with Oxigraph's Store.load.
C. Open a new OxigraphLens for each file.
D. Purge every dataset first.
Answer
B. Each lens call copies the whole default graph into memory, so its time grows with the store, not with the file. Oxigraph's own loader adds the triples without that copy. A changes how the file is read, not the copy. C fails, since the folder is locked while a lens has it open.
Check yourself¶
- I can open an
OxigraphLensin memory or in a folder, write a DDI file to it, and read or purge one dataset. (O1) - I can query the store in SPARQL with
lens.store.query, and run addigraph.queryon it withrun, reading the SPARQL thatto_sparqlwrites. (O2) - I can write SHACL shapes with
ddigraph shapesorshapes_graph(flavor=), and check an export with pyshacl orddigraph validate. (O3) - I can read an RDF file back into ddigraph's graph with
read_graph. (O4) - I can predict what Oxigraph does to a language tag, and which tags it refuses. (O5)
Next: Module 22: Gremlin