Skip to content

Module 4: Nodes, edges and identity

Learning objectives

By the end of this module, you can:

  • O1. Stream a DDI file as chunks of nodes and relationships with ddigraph.iter_graph or ddigraph.ir.parse.
  • O2. Name the six fields of a node, and say what each one holds.
  • O3. Tell the three kinds of identity apart, and turn an identity into its text form and its key with ddigraph.urn.
  • O4. Follow edges by their start and end keys, and read their ordinal and resolution.
  • O5. Find stubs, the nodes that stand in for a reference the file cannot resolve, and say why ddigraph keeps them.

Prerequisites: Module 3

Time: 45 min self-paced / 60 min instructor-led.

Needs: No server.

New in this module: ddigraph.iter_graph, ddigraph.ir.parse, GraphChunk, Node, Relationship, Text, ddigraph.urn, Urn, Scoped, Derived, stubs


1. One stream for three flavors

In Module 3, one command previewed three very different files. That works because of one function underneath: ddigraph.ir.parse. It takes a path, works out the flavor, and gives the same thing for all three: a stream of nodes and relationships. The stream is called the IR, the intermediate representation.

Every part of ddigraph reads that stream: the previewer, the exporters, the validators, the database writers and your own code. None of them needs to know which flavor the file was.

graph LR
    C[Codebook XML] --> P[ir.parse]
    L[Lifecycle XML] --> P
    D[CDI XML] --> P
    P --> V[preview]
    P --> E[export]
    P --> N[Neo4j and other databases]
    P --> Y[your code]

This module is about that last arrow.


2. Stream a file

ddigraph.iter_graph is ir.parse with one default: the dataset ID is the file name. Print each node's type label and identity, for the sample survey's questionnaire:

from ddigraph import iter_graph

for chunk in iter_graph("tests/fixtures/lfs_lifecycle.xml"):
    for node in chunk.nodes:
        print(node.label, node.identity)

Expected output (87 lines; the middle ones are cut here):

Dataset Scoped(dataset='lfs_lifecycle', local_id=':dataset')
Instrument Urn(agency='example.nso', id='lfs-instrument', version='1')
Sequence Urn(agency='example.nso', id='lfs-main', version='1')
IfThenElse Urn(agency='example.nso', id='if-worked', version='1')
Sequence Urn(agency='example.nso', id='job-search', version='1')
QuestionConstruct Urn(agency='example.nso', id='qc-sex', version='1')
...
Variable Urn(agency='example.nso', id='var-ilostat', version='1')
Variable Urn(agency='example.nso', id='var-hours', version='1')

The first node is the Dataset node. Every stream starts with one. The other nodes follow in the order the file holds them: the questionnaire first, then the questions, the code lists with their codes and categories, the concepts, the universes and, last, the seven variables.

The stream comes in chunks. A chunk is a GraphChunk: a list of nodes and a list of relationships. Make the chunks small to see them:

from ddigraph import iter_graph

for chunk in iter_graph("tests/fixtures/lfs_lifecycle.xml", chunk_size=30):
    print(len(chunk.nodes), "nodes,", len(chunk.relationships), "relationships")

Expected output:

30 nodes, 0 relationships
30 nodes, 0 relationships
27 nodes, 30 relationships
0 nodes, 30 relationships
0 nodes, 30 relationships
0 nodes, 18 relationships

Each chunk holds at most chunk_size nodes and at most chunk_size relationships. The 87 nodes come first, then the 108 relationships. Chunks keep memory flat: ddigraph reads the whole file first, sorting on disk once it passes a memory limit, then gives the graph one chunk at a time. It never holds the whole graph, whether the file is 50 KB, like this one, or 65 MB. A database writer sends each chunk in one transaction.

ir.parse needs a dataset_id for a Codebook file, because a Codebook ID only means something inside its dataset. Without one it stops with ValueError: ... a Codebook file needs a dataset_id, to scope its IDs. iter_graph fills it in from the file name.


3. What a node holds

Every node has the same six fields:

Field What it holds
key 32 hex characters, unique in the graph. Edges use it to name their ends.
label The node's type, such as QuestionItem. It becomes the Neo4j label.
identity Which object it is. The key is computed from it.
properties Everything else: names, labels, text, agency, version.
provenance Where it came from: the file, the flavor and the line.
unresolved Empty on a real node. It holds a reason on a stub (section 6).

Print them for the question WORK, "Last week, did you do any work for pay or profit, even for one hour?":

from ddigraph import iter_graph

for chunk in iter_graph("tests/fixtures/lfs_lifecycle.xml"):
    for node in chunk.nodes:
        if node.label == "QuestionItem" and node.properties["name"] == "WORK":
            print("key       ", node.key)
            print("label     ", node.label)
            print("identity  ", node.identity)
            print("properties", sorted(node.properties))
            print("provenance", node.provenance)
            print("unresolved", node.unresolved)
            print("text      ", node.properties["question_text"])

Expected output:


A text property, such as label or question_text, is a Text: the string in value, and its language in lang, which the file's xml:lang gives. This file writes xml:lang="en", so lang is 'en'. A file that names no language gives None. Use .value to get the string alone. The response_type is code: the answer is a code from a code list, here "Yes or no".


4. Identity

An identity is an object, not a string, because it comes in three kinds, and each has more than one part:

Kind Used for Text form
Urn A DDI-L object, or a CDI object with a DDI URN urn:ddi:example.nso:q-work:1
Scoped A Codebook element with an ID, another CDI identifier, and every Dataset node urn:ddigraph:scoped:lfs_codebook:V1
Derived An element with no ID of its own urn:ddigraph:derived:...
  • A DDI URN is global: the same agency, ID and version name the same object in every file.
  • A scoped ID is unique only inside one dataset, so the dataset is part of it.
  • A derived identity names an element that has no ID. It is built from the key of the node that holds it, its role there (such as concept), a hash of its content, and a count of identical siblings. So adding an element to a file changes no other node's key.

ddigraph.urn turns an identity into its text form with text, back again with parse, and into a key with key:

from ddigraph import urn

question = urn.Urn("example.nso", "q-work", "1")
print(urn.text(question))
print(urn.key(question))
print(urn.parse("urn:ddi:example.nso:q-work:1") == question)

variable = urn.Scoped("LFS 2025:Q3", "V1")
print(urn.text(variable))

Expected output:

urn:ddi:example.nso:q-work:1
5aa45158348ca4b8ceba45a593fe3657
True
urn:ddigraph:scoped:LFS%202025%3AQ3:V1

The key is the same as the question's key in section 3, with no file read at all: it is a hash (BLAKE3) of the text form. Each part of the text form is percent-encoded: a space becomes %20 and a colon %3A. So two different identities never share a text form.

A derived identity shows its parts. In the survey's Codebook file, the concept "Demographic characteristics" has no ID, so it is named by the variable that holds it:

from ddigraph import iter_graph, urn

for chunk in iter_graph("tests/fixtures/lfs_codebook.xml"):
    for node in chunk.nodes:
        if node.label == "Concept" and node.properties["name"] == "Demographic characteristics":
            print(node.identity)
print(urn.key(urn.Scoped("lfs_codebook", "V1")))

Expected output:

ca3caae6b7f152c4f2ce6ad8640cc234

There are three. DDI-Codebook has no way to reuse a concept, so the file writes "Demographic characteristics" again in each of the variables SEX, AGE and AGEGRP. The three share a content_hash, because their text is the same, but each has its own parent_key, so they are three nodes. The first parent_key is the key of variable V1, SEX, as the last line shows. The DDI-L file writes the concept once, with a URN, and gives one node. Node identity has the full rules.

Use the key

It is tempting to build your own key from part of an identity, such as ddi_id alone. That fails without a sound: every node that shares that part falls onto one key, and their properties merge. You get fewer nodes than you started with, and no error. node.key comes from the whole identity, so use it.


5. Relationships

A relationship has a type and two ends. Each end is a node's key, so the code keeps each node's name as the nodes go past. A node with no name, such as the Dataset node, keeps its label. The file has 108 edges, so the code prints only those of the questionnaire's flow:

from ddigraph import iter_graph

names = {}
for chunk in iter_graph("tests/fixtures/lfs_lifecycle.xml"):
    for node in chunk.nodes:
        names[node.key] = node.properties.get("name", node.label)
    for edge in chunk.relationships:
        if edge.type in ("HAS_ENTRY_POINT", "HAS_CONSTRUCT", "THEN", "ELSE"):
            start, end = names[edge.start], names[edge.end]
            print(f"({start})-[:{edge.type}]->({end})", edge.ordinal, edge.resolution)

Expected output:

(Text(value='Main sequence', lang='en'))-[:HAS_CONSTRUCT]->(Text(value='SEX', lang='en')) 0 exact
(Text(value='Main sequence', lang='en'))-[:HAS_CONSTRUCT]->(Text(value='AGE', lang='en')) 1 exact
(Text(value='Main sequence', lang='en'))-[:HAS_CONSTRUCT]->(Text(value='REGION', lang='en')) 2 exact
(Text(value='Main sequence', lang='en'))-[:HAS_CONSTRUCT]->(Text(value='EDUC', lang='en')) 3 exact
(Text(value='Main sequence', lang='en'))-[:HAS_CONSTRUCT]->(Text(value='WORK', lang='en')) 4 exact
(Text(value='Main sequence', lang='en'))-[:HAS_CONSTRUCT]->(Text(value='Worked last week?', lang='en')) 5 exact
(Text(value='LFS questionnaire', lang='en'))-[:HAS_CONSTRUCT]->(Text(value='Main sequence', lang='en')) 0 exact
(Text(value='Job search', lang='en'))-[:HAS_CONSTRUCT]->(Text(value='LOOK', lang='en')) 0 exact
(Text(value='Job search', lang='en'))-[:HAS_CONSTRUCT]->(Text(value='AVAIL', lang='en')) 1 exact
(Dataset)-[:HAS_ENTRY_POINT]->(Text(value='LFS questionnaire', lang='en')) None exact
(Text(value='Worked last week?', lang='en'))-[:ELSE]->(Text(value='Job search', lang='en')) None exact
(Text(value='Worked last week?', lang='en'))-[:THEN]->(Text(value='HOURS', lang='en')) None exact

That is the questionnaire from Module 3, now as objects you can act on. The main sequence asks SEX, AGE, REGION, EDUC and WORK. Then the choice "Worked last week?" sends a person who worked to HOURS, and everyone else to the job search questions, LOOK and AVAIL. An edge has two more fields:

  • ordinal is the edge's place in an ordered list, from 0: the constructs of a sequence, the codes of a code list. It is None on an edge whose order means nothing, such as THEN and ELSE.
  • resolution says how a reference found its end. exact means it found the version the reference named. The Dataset's edge comes from the file's <TopLevelReference>, which names the questionnaire, so it is exact too. An edge that comes from no reference has None, as Exercise 3 shows.

The edges do not come in file order. They come after the nodes, in a fixed sorted order, so the same file always gives the same stream. Here the main sequence's edges come before the questionnaire's own edge.

This file is DDI 3.3, which gives each code an ID. So a code is a node too, and the path from a code list to a category has two steps: (CodeList)-[:CONTAINS]->(Code)-[:HAS_CATEGORY]->(Category). In DDI 3.1, a code has no ID of its own, so its category hangs off the code list: (CodeList)-[:HAS_CATEGORY]->(Category). Module 5 queries both shapes.


6. Stubs

A reference can name an object that the file does not hold, such as a code list kept in another file. ddigraph keeps the edge anyway. It ends at a stub: a node whose unresolved field holds the reason. The sample survey's files have none: every reference in them finds its object. So this section uses ir_cdi_valid.xml, a small DDI-CDI test file made to have two broken references. It is not a survey. It holds a few labour force categories, some declared at odd versions, for the parser to resolve:

from ddigraph import iter_graph, urn

labels = {}
stubs = set()
for chunk in iter_graph("tests/fixtures/ir_cdi_valid.xml"):
    for node in chunk.nodes:
        labels[node.key] = node.label
        if node.unresolved is not None:
            stubs.add(node.key)
            print(node.label, urn.text(node.identity), node.unresolved)
    for edge in chunk.relationships:
        if edge.end in stubs:
            print(f"({labels[edge.start]})-[:{edge.type}]->(stub {labels[edge.end]})")

Expected output:

CDICategory urn:ddi:example.org:cat-unemployed:2.0 version_not_in_file
CDICode urn:ddi:example.org:code-3:1 not_in_file
(CDICodeList)-[:HAS_CODE]->(stub CDICode)
(CDICode)-[:DENOTES]->(stub CDICategory)

The last two lines are the edges that end at the stubs. The code list still lists its third code, and the second code still points at its category. The reasons say why each end is missing:

  • not_in_file: no object with that agency and ID is in the file.
  • version_not_in_file: the file holds cat-unemployed, but not version 2.0, which the reference asks for.

A stub has the identity the reference gave. So when a later load brings the real object, it fills the stub in place, and the edge is already there. Dropping the edge would lose the fact that the link exists. In Neo4j, a stub also carries the label Unresolved, so you can list them. Node identity has the details.


7. Why the order matters

The stream keeps one rule: a relationship comes after both of its ends, in its own chunk or an earlier one. Each node comes once.

For your code, the rule means: handle a chunk's nodes before its edges, and keep what you need about each node. You will never meet an edge whose end you have not seen. That is why the names dictionary in section 5 always has the key it looks up.


Exercises

Scenario

Your team wants a small report of what a DDI file holds, without installing any database. You write it in plain Python on top of the stream.

Exercise 1 (O1, O2). Count the nodes and relationships of tests/fixtures/lfs_codebook.xml, without ddigraph preview. Print the totals, then the five most common node types.

Expected output:

80 nodes, 48 relationships
  DDIGenericIdentifiable   26
  Category                 21
  Variable                 7
  Concept                  7
  Question                 5
Answer
import collections

from ddigraph import iter_graph

nodes = collections.Counter()
edges = collections.Counter()
for chunk in iter_graph("tests/fixtures/lfs_codebook.xml"):
    nodes.update(node.label for node in chunk.nodes)
    edges.update(edge.type for edge in chunk.relationships)

print(sum(nodes.values()), "nodes,", sum(edges.values()), "relationships")
for label, count in nodes.most_common(5):
    print(f"  {label:24} {count}")
80 nodes, 48 relationships
  DDIGenericIdentifiable   26
  Category                 21
  Variable                 7
  Concept                  7
  Question                 5

These are the counts ddigraph preview gave in Module 3. The previewer counts the same stream; your code has the same access it does. Types with equal counts come in the order the file first meets them: here the variable SEX comes before its concept.

Exercise 2 (O3). Read tests/fixtures/lfs_codebook.xml with ir.parse, as the dataset lfs_2025q3. Count its identities by kind. Then check, for every node, that urn.key of its identity equals its key, and that urn.parse reads its text form back.

Expected output:

[('Derived', 65), ('Scoped', 15)]
True
Answer
import collections

from ddigraph import ir, urn

kinds = collections.Counter()
consistent = True
for chunk in ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="lfs_2025q3"):
    for node in chunk.nodes:
        kinds[type(node.identity).__name__] += 1
        text = urn.text(node.identity)
        consistent = consistent and urn.key(node.identity) == node.key
        consistent = consistent and urn.parse(text) == node.identity
print(sorted(kinds.items()))
print(consistent)
[('Derived', 65), ('Scoped', 15)]
True

A Codebook file has no DDI URNs: an element with an ID is scoped to the dataset, and one without is derived from its parent. Fourteen nodes come from an element with an ID: the 7 variables, the 5 questions, the data file F1 and the study's universe. The fifteenth scoped identity is the Dataset node. The 65 others, such as the 21 categories, come from elements with no ID. The key is always the hash of the text form, and the text form always reads back.

Exercise 3 (O4). In tests/fixtures/lfs_lifecycle.xml, the code list "Labour force status (ILO)", cl-ilo, holds its three codes in order, with CONTAINS edges. Print each such edge's ordinal, the URN of its start, the URN of its end, and its resolution.

Expected output:

0 urn:ddi:example.nso:cl-ilo:1 -> urn:ddi:example.nso:code-ilo-1:1 None
1 urn:ddi:example.nso:cl-ilo:1 -> urn:ddi:example.nso:code-ilo-2:1 None
2 urn:ddi:example.nso:cl-ilo:1 -> urn:ddi:example.nso:code-ilo-3:1 None
Answer
from ddigraph import iter_graph, urn

names = {}
for chunk in iter_graph("tests/fixtures/lfs_lifecycle.xml"):
    for node in chunk.nodes:
        names[node.key] = urn.text(node.identity)
    for edge in chunk.relationships:
        if edge.type == "CONTAINS" and names[edge.start] == "urn:ddi:example.nso:cl-ilo:1":
            print(edge.ordinal, names[edge.start], "->", names[edge.end], edge.resolution)
0 urn:ddi:example.nso:cl-ilo:1 -> urn:ddi:example.nso:code-ilo-1:1 None
1 urn:ddi:example.nso:cl-ilo:1 -> urn:ddi:example.nso:code-ilo-2:1 None
2 urn:ddi:example.nso:cl-ilo:1 -> urn:ddi:example.nso:code-ilo-3:1 None

The ordinal keeps the list's order, 0 to 2: employed, unemployed, not in the labour force. It holds whatever order the edges arrive in. The resolution is None, because the codes are written inside the code list: no reference had to find them. Each code's edge to its category comes from a reference, and is exact. The dictionary is filled from each chunk's nodes before its edges are read, so every end is already in it.

Exercise 4 (O4, O5). Parse the test file tests/fixtures/ir_cdi_valid.xml from section 6 again, with resolve="latest-declared". Print the stubs, then each DENOTES edge with its resolution. Which stub is gone, and why?

Expected output:

stub urn:ddi:example.org:code-3:1 not_in_file
urn:ddi:example.org:code-1:1 -> urn:ddi:example.org:cat-employed:1 exact
urn:ddi:example.org:code-2:1 -> urn:ddi:example.org:cat-unemployed:1.10 latest-declared
Answer
from ddigraph import iter_graph, urn

names = {}
for chunk in iter_graph("tests/fixtures/ir_cdi_valid.xml", resolve="latest-declared"):
    for node in chunk.nodes:
        names[node.key] = urn.text(node.identity)
        if node.unresolved is not None:
            print("stub", names[node.key], node.unresolved)
    for edge in chunk.relationships:
        if edge.type == "DENOTES":
            print(names[edge.start], "->", names[edge.end], edge.resolution)
stub urn:ddi:example.org:code-3:1 not_in_file
urn:ddi:example.org:code-1:1 -> urn:ddi:example.org:cat-employed:1 exact
urn:ddi:example.org:code-2:1 -> urn:ddi:example.org:cat-unemployed:1.10 latest-declared

The stub for cat-unemployed:2.0 is gone. With latest-declared, a reference to a version the file lacks takes the highest version of the same agency and ID that the file has, here 1.10, and the edge says so in its resolution. code-3 is not in the file at any version, so it stays a stub.


Quiz

Question 1 (O2): Which field of a node tells you the file and line it came from?

A. identity

B. properties

C. provenance

D. key

Answer

C. provenance holds the source file, the flavor and the line. The identity (A) says which object the node is, not where it was read.

Question 2 (O3): Two Codebook files, for two quarters of the Labour Force Survey, both have a variable with the ID V1. You read them as the datasets lfs_2025q2 and lfs_2025q3. How many V1 nodes do you get?

A. One, because the IDs are equal.

B. Two, because a Codebook ID is scoped to its dataset.

C. None: ddigraph refuses the second file.

D. One, with the properties of the second file.

Answer

B. Their identities are urn:ddigraph:scoped:lfs_2025q2:V1 and urn:ddigraph:scoped:lfs_2025q3:V1, so their keys differ. Codebook files often reuse IDs such as V1, for the same variable or for a different one, and nothing in the file says which. A would be right for a DDI URN, which is the same in every dataset.

Question 3 (O3): A colleague keys nodes on ddi_id alone, to save time. What goes wrong?

A. Nothing: ddi_id is unique in every file.

B. The code is slower.

C. Nodes that share an ID, such as two versions of one question, fall onto one key and merge, with no error.

D. Python raises a KeyError.

Answer

C. Part of an identity is not unique: versions, agencies and datasets can share an ID. The merge is silent, which is why it is dangerous. node.key comes from the whole identity.

Question 4 (O4): Your code reads a chunk's edges first, then its nodes. What can happen?

A. Nothing: the order inside a chunk does not matter.

B. An edge can name an end whose node is later in the same chunk, so a lookup by key fails.

C. ddigraph raises an error.

D. The edges come back empty.

Answer

B. The stream promises that an edge comes after both of its ends, in its own chunk or an earlier one. If you read the edges first, the ends in the same chunk are not in your dictionary yet. Handle the nodes first.

Question 5 (O5): A question references a code list that lives in another file. What does ddigraph do?

A. It drops the reference, since the code list is missing.

B. It stops with an error.

C. It keeps the edge, which ends at a stub with the reason not_in_file. A later load of the other file fills the stub in.

D. It downloads the other file.

Answer

C. The stub keeps the link and the identity the reference gave. A is tempting, but dropping the edge would lose the fact that the question uses a code list at all.

Question 6 (O1): Why can iter_graph read a 65 MB file without holding the whole graph in memory?

A. It reads only the first part of the file.

B. It sorts on disk past a memory limit, then yields the graph one chunk at a time.

C. It compresses the graph.

D. It writes the graph to Neo4j as it reads.

Answer

B. The stream is a generator of chunks. Your code keeps only what it needs, such as a label for each key. A is wrong: ddigraph reads the whole file, because an edge can point at an object later in the file.


Check yourself

  • I can stream a DDI file as chunks of nodes and relationships with iter_graph or ir.parse. (O1)
  • I can name the six fields of a node and say what each holds. (O2)
  • I can tell the three kinds of identity apart, and get a text form and a key with ddigraph.urn. (O3)
  • I can follow edges by their start and end keys, and read their ordinal and resolution. (O4)
  • I can find stubs and say why ddigraph keeps them. (O5)

Next: Module 5: Ask the graph questions in memory