Module 8: Linked data: RDF out and back in¶
Learning objectives
By the end of this module, you can:
- O1. Export a DDI file as Turtle or JSON-LD, with
ddigraph exportand withddigraph.export(), and read the counts it reports. - O2. Explain why each node carries two
rdf:types, and tell a published term (DISCO, SKOS, Dublin Core) from addigraph:term. - O3. Query an export with SPARQL in
rdflib, using published terms, and read an edge's order from itsrdf:Statement. - O4. Read an export back into the graph stream with
read_graph, and load it into Neo4j withddigraph load out.ttl.
Prerequisites: Module 7
Time: 45 min self-paced / 60 min instructor-led.
Needs: No server. The rdf extra (pip install "ddigraph[rdf]"); the Oxigraph tab of section 7 also needs the oxigraph extra. The Neo4j tab of section 7, and section 9, are optional and use the Neo4j server from Module 7.
New in this module: ddigraph export --format turtle|jsonld, ddigraph.export(), ExportResult, rdflib, SPARQL, class_iris, rdf:Statement, ddigraph:Membership, read_graph, ddigraph load out.ttl
1. Why RDF?¶
In Module 7 you put a DDI file into Neo4j. That graph is useful to you. But
Neo4j's labels and relationship names are your own words. Another system
cannot tell what USES_CODELIST means.
RDF (Resource Description Framework) is a W3C standard for sharing graphs. An RDF graph is a set of triples. A triple is one fact in three parts: a subject, a predicate and an object, such as "question SEX has the text What is your sex?". Each part is an IRI, a global name that looks like a web address, or a plain value.
The trick is to use words that others already use. The DDI Alliance publishes RDF words for DDI: DISCO for studies, variables and questions, and XKOS for classifications. Code lists fit SKOS, the W3C standard for code lists and thesauri. When ddigraph writes RDF, it uses these published terms wherever one exists. A tool that has never heard of ddigraph can then read your questions and code lists.
You need the rdf extra for this module:
pip install "ddigraph[rdf]"
2. Export from the command line¶
ddigraph export reads a DDI file and writes it to disk. It needs no
database. --format turtle writes Turtle, a compact text form of RDF
that people can read. --format jsonld writes JSON-LD, the same triples
as JSON, which web tools like.
This module uses tests/fixtures/lfs_lifecycle.xml, the course's sample
survey in DDI-Lifecycle 3.3. It is a fictional Labour Force Survey: a
questionnaire with 8 questions, 6 code lists and 7 variables.
ddigraph export tests/fixtures/lfs_lifecycle.xml --format turtle -o survey.ttl
ddigraph export tests/fixtures/lfs_lifecycle.xml --format jsonld -o survey.jsonld
Expected output:
Wrote survey.ttl
Format: turtle
Nodes: 87 Relationships: 108
Triples: 2106
Wrote survey.jsonld
Format: jsonld
Nodes: 87 Relationships: 108
Triples: 2106
Both files hold the same triples. The graph has 87 nodes and 108
relationships, the same graph that ddigraph load puts into Neo4j. There
are many more triples than nodes, because each property is a triple too,
and the export adds a few resources of its own (section 6). ntriples and
rdfxml are the other RDF formats. The CLI reference
lists every option.
3. Export from Python¶
ddigraph.export() does the same from Python. It returns an
ExportResult, which holds the counts:
import ddigraph
result = ddigraph.export("tests/fixtures/lfs_lifecycle.xml", "survey.ttl", format="turtle")
print(result.format, result.path)
print(result.nodes, "nodes,", result.relationships, "relationships,", result.triples, "triples")
Expected output:
turtle survey.ttl
87 nodes, 108 relationships, 2106 triples
result.triples is None for the formats that are not RDF, such as
json and csv.
4. Read one node in Turtle¶
Here is the question WORK, as the export wrote it:
ddigraph export tests/fixtures/lfs_lifecycle.xml --format turtle -o survey.ttl > /dev/null
grep -A 14 '^<urn:ddi:example.nso:q-work:1>' survey.ttl
Expected output:
<urn:ddi:example.nso:q-work:1> a disco:Question,
ddigraph:QuestionItem ;
dcterms:identifier "urn:ddi:example.nso:q-work:1" ;
dcterms:isPartOf <urn:ddigraph:scoped:lfs_lifecycle:%3Adataset> ;
dcterms:publisher "example.nso" ;
disco:concept <urn:ddi:example.nso:concept-labour:1> ;
disco:questionText "Last week, did you do any work for pay or profit, even for one hour?"@en ;
disco:responseDomain <urn:ddi:example.nso:cl-yesno:1> ;
owl:versionInfo "1" ;
ddigraph:ddiId "q-work" ;
ddigraph:key "5aa45158348ca4b8ceba45a593fe3657" ;
ddigraph:name "WORK"@en ;
ddigraph:responseType "code" ;
ddigraph:usesCodelist <urn:ddi:example.nso:cl-yesno:1> ;
ddigraph:usesConcept <urn:ddi:example.nso:concept-labour:1> .
Read it as a list of facts about one subject. Each line after the first is
a predicate and an object. a is short for rdf:type. Four things to see:
- The subject is the node's identity. It is the DDI URN,
urn:ddi:example.nso:q-work:1, as in Module 4. A URN is already unique in the world, so ddigraph makes up no new web address. A Codebook record has no URN, so its subject is its scoped identity, such asurn:ddigraph:scoped:lfs_codebook:V1for the variable SEX. ddigraph:keyis the node's key, the same 32 characters as in every other backend.- Published terms come first.
disco:questionText,disco:conceptanddcterms:publisher(Dublin Core) are terms that other tools know. The@enafter the text is its language, as the DDI file gives it. - Each edge is there twice. The edge to the code list is
disco:responseDomain, the published term, andddigraph:usesCodelist, the ddigraph term. The edge to the concept isdisco:conceptandddigraph:usesConcept. There is noUSES_CODELISTanywhere.
The code list is cl-yesno, the Yes or no list. The questions LOOK and
AVAIL point to the same list: DDI-L writes a code list once, and any
question can use it.
5. Two types for every node¶
The question has two types: disco:Question and ddigraph:QuestionItem.
This counts the nodes that have a DDI URN, by their types:
from collections import Counter
import rdflib
import ddigraph
ddigraph.export("tests/fixtures/lfs_lifecycle.xml", "survey.ttl", format="turtle")
graph = rdflib.Graph().parse("survey.ttl")
names = graph.namespace_manager
kinds = Counter()
for subject in set(graph.subjects(rdflib.RDF.type, None)):
if str(subject).startswith("urn:ddi:"):
types = sorted(kind.n3(names) for kind in graph.objects(subject, rdflib.RDF.type))
kinds[tuple(types)] += 1
for types, count in sorted(kinds.items()):
print(count, list(types))
Expected output:
23 ['ddigraph:Category', 'skos:Concept']
23 ['ddigraph:Code']
6 ['ddigraph:CodeList', 'skos:ConceptScheme']
5 ['ddigraph:Concept', 'skos:Concept']
1 ['ddigraph:IfThenElse']
1 ['ddigraph:Instrument', 'disco:Instrument']
8 ['ddigraph:QuestionConstruct']
8 ['ddigraph:QuestionItem', 'disco:Question']
2 ['ddigraph:Sequence']
2 ['ddigraph:Universe', 'disco:Universe']
7 ['ddigraph:Variable', 'disco:Variable']
Why two? The match from DDI types to published classes is many to one.
class_iris gives the classes ddigraph writes for a label:
from ddigraph.rdf.vocabulary import class_iris
for label in ("Question", "QuestionItem", "CodeList", "CodeScheme", "Sequence"):
print(label, class_iris(label))
Expected output:
Question ('http://rdf-vocabulary.ddialliance.org/discovery#Question', 'https://pbisson44.github.io/ddigraph/ns/1.0/Question')
QuestionItem ('http://rdf-vocabulary.ddialliance.org/discovery#Question', 'https://pbisson44.github.io/ddigraph/ns/1.0/QuestionItem')
CodeList ('http://www.w3.org/2004/02/skos/core#ConceptScheme', 'https://pbisson44.github.io/ddigraph/ns/1.0/CodeList')
CodeScheme ('http://www.w3.org/2004/02/skos/core#ConceptScheme', 'https://pbisson44.github.io/ddigraph/ns/1.0/CodeScheme')
Sequence ('https://pbisson44.github.io/ddigraph/ns/1.0/Sequence',)
Both Question and QuestionItem become disco:Question. Both
CodeList and CodeScheme become skos:ConceptScheme. Given only the
published class, nobody can tell which DDI type the node was. So each node
carries both:
- the published class, for any other tool, which reads it and ignores the other;
- the
ddigraph:class, which keeps the exact DDI type, so that ddigraph can rebuild the graph you started with (section 8).
A Code, a Sequence or an IfThenElse has no published class, so it
has only its ddigraph: class. A DDI-CDI node has three types: its
published class, its class in the DDI-CDI ontology, such as
cdi:Category, and its ddigraph: class.
6. The ddigraph vocabulary¶
DISCO defines 16 classes. ddigraph has about 250 node types. Every type, predicate and property with no published term gets one in a single namespace:
https://pbisson44.github.io/ddigraph/ns/1.0/
That address is real: open it and you get the
vocabulary reference. The 1.0 is the version of the
vocabulary, not of the package. It changes only when a term changes
meaning, so a query you write today keeps working.
A relationship becomes a predicate in lowerCamelCase: HAS_CONSTRUCT is
ddigraph:hasConstruct. A property does too: response_type is
ddigraph:responseType.
Two facts about the graph do not fit in a plain triple, so the export writes them as resources of their own:
- An edge's order and how it was found. The constructs of a sequence
come in order, and a reference was resolved one way or another. So each
relationship is also an
rdf:Statement. It names its subject, predicate and object, and carriesddigraph:ordinalandddigraph:resolution. - Which file a node came from. Each node has a
ddigraph:Membership. It says which dataset holds the node, and the file, flavor and line it was read from.
This lists the statements that start at the questionnaire's main sequence or at its routing step, "Worked last week?", with their order:
import rdflib
import ddigraph
ddigraph.export("tests/fixtures/lfs_lifecycle.xml", "survey.ttl", format="turtle")
graph = rdflib.Graph().parse("survey.ttl")
rows = graph.query("""
PREFIX ddigraph: <https://pbisson44.github.io/ddigraph/ns/1.0/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
SELECT ?subject ?predicate ?object ?ordinal WHERE {
?edge a rdf:Statement ;
rdf:subject ?subject ;
rdf:predicate ?predicate ;
rdf:object ?object .
FILTER(?subject IN (<urn:ddi:example.nso:lfs-main:1>, <urn:ddi:example.nso:if-worked:1>))
OPTIONAL { ?edge ddigraph:ordinal ?ordinal }
}
ORDER BY ?predicate ?ordinal
""")
names = graph.namespace_manager
for subject, predicate, obj, ordinal in rows:
print(subject, predicate.n3(names), obj, ordinal)
Expected output:
urn:ddi:example.nso:if-worked:1 ddigraph:elseConstruct urn:ddi:example.nso:job-search:1 None
urn:ddi:example.nso:lfs-main:1 ddigraph:hasConstruct urn:ddi:example.nso:qc-sex:1 0
urn:ddi:example.nso:lfs-main:1 ddigraph:hasConstruct urn:ddi:example.nso:qc-age:1 1
urn:ddi:example.nso:lfs-main:1 ddigraph:hasConstruct urn:ddi:example.nso:qc-region:1 2
urn:ddi:example.nso:lfs-main:1 ddigraph:hasConstruct urn:ddi:example.nso:qc-education:1 3
urn:ddi:example.nso:lfs-main:1 ddigraph:hasConstruct urn:ddi:example.nso:qc-work:1 4
urn:ddi:example.nso:lfs-main:1 ddigraph:hasConstruct urn:ddi:example.nso:if-worked:1 5
urn:ddi:example.nso:if-worked:1 ddigraph:thenConstruct urn:ddi:example.nso:qc-hours:1 None
The main sequence asks SEX, AGE, REGION, EDUC and WORK, then reaches the
routing step: its hasConstruct edges carry the ordinals 0 to 5. The
routing step has no order. It is a choice: if WORK is Yes, the
thenConstruct edge leads to HOURS; if not, the elseConstruct edge leads
to the job search questions. The plain triples are there for your queries.
The statements and memberships are there for the ddigraph reader. The
RDF backend page describes each resource.
7. Ask questions with SPARQL¶
SPARQL is the query language of RDF. A query is a pattern of triples
with variables, which start with ?. rdflib, which the rdf extra
installs, runs SPARQL on a graph in memory.
This query uses published terms only. It asks for each question's text,
its code list, and the number of answers in that list. COUNT and
GROUP BY work as in SQL: they give one row per question and list, with
the answers counted.
import rdflib
import ddigraph
ddigraph.export("tests/fixtures/lfs_lifecycle.xml", "survey.ttl", format="turtle")
graph = rdflib.Graph().parse("survey.ttl")
rows = graph.query("""
PREFIX disco: <http://rdf-vocabulary.ddialliance.org/discovery#>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
SELECT ?text ?list (COUNT(?category) AS ?answers) WHERE {
?question a disco:Question ;
disco:questionText ?text ;
disco:responseDomain ?scheme .
?scheme skos:prefLabel ?list .
?category skos:inScheme ?scheme .
}
GROUP BY ?text ?list
ORDER BY ?text
""")
for text, code_list, answers in rows:
print(f"{text} | {code_list} | {answers} answers")
Expected output:
If you found a job, could you start within the next two weeks? | Yes or no | 2 answers
In the last four weeks, did you look for work? | Yes or no | 2 answers
In which region do you live? | Region | 5 answers
Last week, did you do any work for pay or profit, even for one hour? | Yes or no | 2 answers
What is the highest level of education you have completed? | Highest level of education | 5 answers
What is your sex? | Sex | 2 answers
Six of the eight questions have a code list. AGE and HOURS take a number, so they have none. Three questions share the Yes or no list. A tool that knows DISCO and SKOS could run this query on your export, with no idea that ddigraph made it. That is the point of published terms.
The same lookup works in a database. Pick a backend below. In the Oxigraph
tab, the Turtle file goes into an Oxigraph store, an RDF database, and the
same SPARQL runs there. In the Neo4j tab, ddigraph.load puts the same file
into Neo4j, and Cypher asks the question. The Neo4j tab needs the server; it
uses the dataset m08-lookup and purges it at the end.
Neo4j has its own words, not DISCO or SKOS. The question is a QuestionItem, and its answers are reached with the code list path of Module 9. Both tabs print the same lines:
import os
from neo4j import GraphDatabase
import ddigraph
from ddigraph.lens.neo4j import Neo4jLens
ddigraph.export(
"tests/fixtures/lfs_lifecycle.xml", "survey.ttl", format="turtle", dataset_id="m08-lookup"
)
ddigraph.load("survey.ttl", replace=True)
QUERY = """
MATCH (q:QuestionItem)-[:IN_DATASET]->(:Dataset {dataset_id: 'm08-lookup'})
MATCH (q)-[:USES_CODELIST]->(cl:CodeList)-[:CONTAINS*0..1]->()-[:HAS_CATEGORY]->(cat:Category)
RETURN q.question_text AS text, cl.label AS list, count(cat) AS answers
ORDER BY text
"""
auth = (os.environ["DDIGRAPH_NEO4J_USER"], os.environ["DDIGRAPH_NEO4J_PASSWORD"])
with GraphDatabase.driver(os.environ["DDIGRAPH_NEO4J_URI"], auth=auth) as driver:
records, _, _ = driver.execute_query(QUERY)
for record in records:
print(f"{record['text']} | {record['list']} | {record['answers']} answers")
Neo4jLens(driver).purge("m08-lookup")
If you found a job, could you start within the next two weeks? | Yes or no | 2 answers
In the last four weeks, did you look for work? | Yes or no | 2 answers
In which region do you live? | Region | 5 answers
Last week, did you do any work for pay or profit, even for one hour? | Yes or no | 2 answers
What is the highest level of education you have completed? | Highest level of education | 5 answers
What is your sex? | Sex | 2 answers
pyoxigraph comes with the oxigraph extra. The store reads the export as any triple store would:
from pyoxigraph import RdfFormat, Store
import ddigraph
ddigraph.export(
"tests/fixtures/lfs_lifecycle.xml", "survey.ttl", format="turtle", dataset_id="m08-lookup"
)
store = Store()
store.load(path="survey.ttl", format=RdfFormat.TURTLE)
rows = store.query("""
PREFIX disco: <http://rdf-vocabulary.ddialliance.org/discovery#>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
SELECT ?text ?list (COUNT(?category) AS ?answers) WHERE {
?question a disco:Question ;
disco:questionText ?text ;
disco:responseDomain ?scheme .
?scheme skos:prefLabel ?list .
?category skos:inScheme ?scheme .
}
GROUP BY ?text ?list
ORDER BY ?text
""")
for row in rows:
print(f"{row['text'].value} | {row['list'].value} | {row['answers'].value} answers")
If you found a job, could you start within the next two weeks? | Yes or no | 2 answers
In the last four weeks, did you look for work? | Yes or no | 2 answers
In which region do you live? | Region | 5 answers
Last week, did you do any work for pay or profit, even for one hour? | Yes or no | 2 answers
What is the highest level of education you have completed? | Highest level of education | 5 answers
What is your sex? | Sex | 2 answers
Note the direction of skos:inScheme. The graph says
CodeList -CONTAINS-> Code -HAS_CATEGORY-> Category, because that is how
the XML nests. SKOS puts the link on the member: the category is
skos:inScheme its code list. So the export writes the link both ways
round: down from the code list, with ddigraph:contains then
ddigraph:hasCategory, and up from the category, with skos:inScheme.
Module 9 looks at code lists in more
depth.
8. Read RDF back¶
RDF is also an input. read_graph, in ddigraph.rdf.reader, reads a
Turtle, JSON-LD, N-Triples or RDF/XML file that ddigraph wrote. It gives
back the same stream of chunks as the DDI parsers of Module 4:
import rdflib
from rdflib.compare import isomorphic
import ddigraph
from ddigraph.rdf.reader import read_graph
from ddigraph.rdf.writer import build_graph
ddigraph.export("tests/fixtures/lfs_lifecycle.xml", "survey.ttl", format="turtle")
nodes = [node for chunk in read_graph("survey.ttl") for node in chunk.nodes]
print(len(nodes), "nodes read back")
print(sorted({node.label for node in nodes}))
again = build_graph(read_graph("survey.ttl"))
print("same triples:", isomorphic(again, rdflib.Graph().parse("survey.ttl")))
Expected output:
87 nodes read back
['Category', 'Code', 'CodeList', 'Concept', 'Dataset', 'IfThenElse', 'Instrument', 'QuestionConstruct', 'QuestionItem', 'Sequence', 'Universe', 'Variable']
same triples: True
The labels are the DDI types, such as QuestionItem, not Question. That
is the two-type trick at work: read_graph reads the ddigraph: class.
build_graph writes the stream back as RDF, and isomorphic checks that
the two graphs hold the same triples. The round trip loses nothing.
read_graph follows a few rules:
- It reads one dataset. A file that holds several needs
dataset_id=. - It reads only RDF that ddigraph wrote. RDF from another tool, or an
export from ddigraph 0.5, raises
ValueError. - It reads each edge from its
rdf:Statement, not from the plain triples. A triple you add yourself stays out of the stream.
9. Optional: load the export into Neo4j¶
ddigraph load takes an RDF file as well as a DDI file. It knows RDF by
the file's extension. The nodes go into the dataset the file holds, so give
the dataset its ID when you export. This step needs the Neo4j server and
the DDIGRAPH_NEO4J_* variables you set in Module 2. It uses the dataset ID
m08-survey, and --replace makes it safe to run twice. A short Python
step then counts what Neo4j holds. UNWIND turns each node's list of
labels into one row per label:
ddigraph export tests/fixtures/lfs_lifecycle.xml --format turtle --dataset-id m08-survey -o out.ttl > /dev/null
ddigraph load out.ttl --replace
python - <<'EOF'
import os
from neo4j import GraphDatabase
from ddigraph.lens.neo4j import Neo4jLens
QUERY = """
MATCH (n:DDINode)-[:IN_DATASET]->(:Dataset {dataset_id: 'm08-survey'})
UNWIND labels(n) AS label
RETURN label, count(*) AS nodes
ORDER BY label
"""
auth = (os.environ["DDIGRAPH_NEO4J_USER"], os.environ["DDIGRAPH_NEO4J_PASSWORD"])
with GraphDatabase.driver(os.environ["DDIGRAPH_NEO4J_URI"], auth=auth) as driver:
records, _, _ = driver.execute_query(QUERY)
for record in records:
print(record["label"], record["nodes"])
Neo4jLens(driver).purge("m08-survey") # clean up; leave this line out to keep the dataset
EOF
Expected output:
Pre-ingestion: connecting to Neo4j at ... format: rdf
Ingestion complete: dataset_id=m08-survey, nodes_written=87, relationships_written=108, stubs=0, references=0, resolved=0, unresolved=0, conflicts=0
Category 23
Code 23
CodeList 6
Concept 5
DDINode 86
IfThenElse 1
Instrument 1
QuestionConstruct 8
QuestionItem 8
Sequence 2
Universe 2
Variable 7
The first line ends with format: rdf. The load wrote the same 87 nodes
and 108 relationships as a load of the XML file. references=0 because the
references were resolved when the XML was read. An RDF file holds edges,
not references. The counts match the types of section 5, and each of the
86 nodes also has the DDINode label, as for a dataset loaded from XML.
The Python step ends with a purge, so the step leaves nothing behind.
Leave it out to look at the dataset in Neo4j Browser, with this query:
MATCH (n:DDINode)-[:IN_DATASET]->(:Dataset {dataset_id: 'm08-survey'})
RETURN labels(n) AS labels, n.ddi_id AS id
ORDER BY id
Exercises¶
Scenario
A partner agency runs a linked-data catalogue. It accepts JSON-LD, and it only understands published terms. You send it the Labour Force Survey in DDI-CDI, and you want to be sure nothing is lost on the way out or back.
Exercise 1 (O1). Export tests/fixtures/lfs_cdi.xml as JSON-LD from
Python. Print the nodes, relationships and triples the result reports.
Then load the file with the json module and print how many objects the
top-level list holds.
Expected output:
91 nodes, 92 relationships, 1995 triples
273 JSON-LD objects
Answer
import json
import ddigraph
result = ddigraph.export("tests/fixtures/lfs_cdi.xml", "cdi.jsonld", format="jsonld")
print(result.nodes, "nodes,", result.relationships, "relationships,", result.triples, "triples")
with open("cdi.jsonld", encoding="utf-8") as handle:
objects = json.load(handle)
print(len(objects), "JSON-LD objects")
91 nodes, 92 relationships, 1995 triples
273 JSON-LD objects
Each subject is one object: the 91 nodes, the 90 memberships (the Dataset node has none), and the 92 statements, one per relationship.
Exercise 2 (O2). Export tests/fixtures/lfs_codebook.xml, the same
survey in DDI-Codebook, as Turtle. Count how many different rdf:types it
uses, and how many of them are in the ddigraph: namespace. Import the
namespace as DDIGRAPH from ddigraph.rdf.vocabulary.
Expected output:
26 types, 16 of them ddigraph types
Answer
import rdflib
import ddigraph
from ddigraph.rdf.vocabulary import DDIGRAPH
ddigraph.export("tests/fixtures/lfs_codebook.xml", "codebook.ttl", format="turtle")
graph = rdflib.Graph().parse("codebook.ttl")
types = {str(kind) for kind in graph.objects(None, rdflib.RDF.type)}
project = {kind for kind in types if kind.startswith(DDIGRAPH)}
print(len(types), "types,", len(project), "of them ddigraph types")
26 types, 16 of them ddigraph types
Most types are ddigraph: ones, since DISCO has only 16 classes. Two
of them, ddigraph:Membership and ddigraph:Dataset, belong to the
export itself. The 10 published types cover what other people search
for: the study, its variables, questions, universes and data file, and
the categories and concepts as skos:Concept. One of them is
rdf:Statement, for the edges.
Exercise 3 (O3). Write a SPARQL query on the Codebook export that lists
each disco:Variable with its label and the label of its concept. Use
published terms only (rdfs:label, disco:concept, skos:prefLabel).
Sort by the variable's label.
Expected output:
Age group -> Demographic characteristics
Age in completed years -> Demographic characteristics
Highest level of education -> Educational attainment
Labour force status (ILO) -> Labour market status
Region of residence -> Place of residence
Sex of the person -> Demographic characteristics
Usual weekly hours in the main job -> Working time
Answer
import rdflib
import ddigraph
ddigraph.export("tests/fixtures/lfs_codebook.xml", "codebook.ttl", format="turtle")
graph = rdflib.Graph().parse("codebook.ttl")
rows = graph.query("""
PREFIX disco: <http://rdf-vocabulary.ddialliance.org/discovery#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
SELECT ?variable ?concept WHERE {
?v a disco:Variable ;
rdfs:label ?variable ;
disco:concept ?c .
?c skos:prefLabel ?concept .
}
ORDER BY ?variable
""")
for variable, concept in rows:
print(variable, "->", concept)
Age group -> Demographic characteristics
Age in completed years -> Demographic characteristics
Highest level of education -> Educational attainment
Labour force status (ILO) -> Labour market status
Region of residence -> Place of residence
Sex of the person -> Demographic characteristics
Usual weekly hours in the main job -> Working time
A Codebook concept is a skos:Concept, so its label is
skos:prefLabel. A variable has no SKOS class, so its label is
rdfs:label. The edge USES_CONCEPT is written as disco:concept.
"Demographic characteristics" comes three times, and it is three
concepts, not one: DDI-Codebook writes the concept inside each
variable. In DDI-L, the three variables point to one concept.
Exercise 4 (O4). Read cdi.jsonld from Exercise 1 back with
read_graph, and check that it holds the same graph as the XML file. Use
canonical from ddigraph.conform: it gives the same value for two
streams that describe the same graph. Then print the sorted labels read
back.
Expected output:
same graph: True
['CDIAgent', 'CDICategory', 'CDICode', 'CDICodeList', 'CDIConcept', 'CDIConceptSystem', 'CDIGenericEntity', 'CDIInstanceVariable', 'CDIUnitType', 'CDIValueDomain', 'Dataset']
Answer
import ddigraph
from ddigraph import iter_graph
from ddigraph.conform import canonical
from ddigraph.rdf.reader import read_graph
ddigraph.export("tests/fixtures/lfs_cdi.xml", "cdi.jsonld", format="jsonld")
back = canonical(read_graph("cdi.jsonld"))
original = canonical(iter_graph("tests/fixtures/lfs_cdi.xml"))
print("same graph:", back == original)
labels = sorted({node.label for chunk in read_graph("cdi.jsonld") for node in chunk.nodes})
print(labels)
same graph: True
['CDIAgent', 'CDICategory', 'CDICode', 'CDICodeList', 'CDIConcept', 'CDIConceptSystem', 'CDIGenericEntity', 'CDIInstanceVariable', 'CDIUnitType', 'CDIValueDomain', 'Dataset']
The JSON-LD file holds the same nodes, with the same keys, properties
and provenance, and the same relationships, in order. read_graph knows
the format from the .jsonld extension.
Quiz¶
Question 1 (O1): An export of the sample survey reports 87 nodes and over 2,000 triples. Why are there so many more triples than nodes?
A. The export repeats each node once per relationship it takes part in.
B. Each property, each type and each edge is a triple, and the export adds a membership per node and a statement per edge.
C. Turtle writes each triple twice, once per prefix.
D. The count includes the triples of the DISCO and SKOS vocabularies.
Answer
B. A node with ten properties and two types is already twelve triples. Each membership and each statement adds a few more. A is tempting, but a node is written once: its edges are triples about it, not copies of it. The vocabularies themselves are not copied in.
Question 2 (O2): A colleague wants smaller files and proposes to write only the published rdf:type. What breaks?
A. Nothing: other tools read only the published type anyway.
B. SPARQL queries that use disco:Question stop working.
C. ddigraph can no longer tell a QuestionItem from a Question, or a CodeList from a CodeScheme, so it cannot rebuild the original graph.
D. The file no longer parses as Turtle.
Answer
C. The match to published classes is many to one, so the
published type alone loses the DDI type. A is true for other tools,
which is why it is tempting, but the round trip of section 8 needs
the ddigraph: class. Queries on disco:Question would still work.
Question 3 (O3): You want the categories of a code list in their order. Which part of the export holds that order?
A. The order of the skos:inScheme triples in the Turtle file.
B. The ddigraph:ordinal on the rdf:Statement of each contains edge, from the code list to its codes.
C. The skos:prefLabel of each category, sorted.
D. The ddigraph:line of each category's membership.
Answer
B. A set of triples has no order, so the order of lines in a file means nothing (A). The statement of each edge carries its ordinal. D is tempting, since a later line often means a later category, but a category can be defined anywhere in the file, far from its code list. C would put "Female" before "Male", whatever the list says.
Question 4 (O3): Which SPARQL pattern finds the categories of the code list ?scheme in a SKOS tool?
A. ?scheme skos:member ?category
B. ?scheme skos:inScheme ?category
C. ?category skos:inScheme ?scheme
D. ?scheme ddigraph:hasCategory ?category, since SKOS has no such link
Answer
C. SKOS puts the link on the member. B is the graph's direction,
which is tempting, but it would say the scheme is inside the
category. skos:member belongs to skos:Collection, not to a
concept scheme. D works in ddigraph's own terms, but a SKOS tool
does not know them.
Question 5 (O4): You run read_graph on a Turtle file of SKOS concepts that another tool published. What happens?
A. It reads the concepts as Concept nodes.
B. It raises ValueError, because the file holds no dataset and IRIs that are not ddigraph identities.
C. It returns an empty stream.
D. It reads the triples it knows and skips the rest.
Answer
B. read_graph reads only what ddigraph wrote, and never guesses
an identity. D sounds friendly, but a half-read graph would be
worse than an error. To use someone else's RDF, query it with
rdflib beside your export.
Question 6 (O4): You run ddigraph load out.ttl. Which dataset do the nodes join?
A. A dataset named out, after the file name.
B. The dataset the RDF file holds, which --dataset-id named at export time.
C. No dataset: RDF has no datasets.
D. The dataset rdf.
Answer
B. The export writes the Dataset node and a membership per node, so the file knows its dataset. A is how a DDI XML file gets its default ID, which is why it is tempting. That is why section 9 names the dataset when it exports.
Check yourself¶
- I can export a DDI file as Turtle or JSON-LD, with
ddigraph exportand withddigraph.export(), and read the counts it reports. (O1) - I can explain why each node carries two
rdf:types, and tell a published term from addigraph:term. (O2) - I can query an export with SPARQL in
rdflib, using published terms, and read an edge's order from itsrdf:Statement. (O3) - I can read an export back with
read_graph, and load it into Neo4j withddigraph load out.ttl. (O4)
Next: Module 9: Code lists and classifications: SKOS and XKOS