Skip to content

Module 17: Neo4j in depth

Learning objectives

By the end of this module, you can:

  • O1. Run ddigraph bootstrap, list the constraint and the indexes it makes, and say what each one is for.
  • O2. Write Cypher recipes over the DDI graph: from a question to its variables and concepts, from a dataset's entry point down a code list, and to the stubs a dataset leaves.
  • O3. Load through the store with ddigraph load --store DIR, so that a reload sends Neo4j only what changed, and bring Neo4j back to the store's HEAD with ddigraph repair.
  • O4. Export a file with ddigraph export --format neo4j-import, and explain the blue/green steps of a bulk import.
  • O5. Point ddigraph at Aura Free with the .env file Aura gives you, and name the limits that matter.

Prerequisites: Module 7

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

Needs: Neo4j 5, in Docker or on Aura Free (Module 2 sets it up). The Gremlin and PostgreSQL tabs, there for comparison, need those servers. Sections 9 and 10 need no server.

New in this module: ddigraph bootstrap --dry-run, HAS_ENTRY_POINT, :Unresolved, Neo4jLens.purge, ddigraph load --store, ddigraph store diff, ddigraph repair, ddigraph export --format neo4j-import, neo4j-admin database import full


1. What bootstrap makes

In Module 7 you ran ddigraph bootstrap once, before the first load. Now look at what it made. It makes two kinds of thing:

  • A constraint is a rule the database enforces. ddigraph makes one: no two DDINode nodes may share a key.
  • An index is a lookup table. It lets Neo4j find the nodes with a given value without reading every node.

Run it again. Each statement says IF NOT EXISTS, so a second run changes nothing. --dry-run prints the statements and runs none:

ddigraph bootstrap
ddigraph bootstrap --dry-run | sed -n '1,2p'
ddigraph bootstrap --dry-run | tail -n 1

Expected output:

Schema ensured for database 'neo4j'
CREATE CONSTRAINT ddigraph_DDINode_key IF NOT EXISTS
FOR (n:DDINode) REQUIRE n.key IS UNIQUE;
Dry run: 55 statements (0 drops) would run on database 'neo4j'; none ran

The database can list what it holds. This script asks it, with the neo4j driver. Settings() reads the same variables and .env file as the command line, so the script finds your server the way ddigraph does:

from neo4j import GraphDatabase

from ddigraph.config import Settings

settings = Settings()
auth = (settings.neo4j_user, settings.neo4j_password.get_secret_value())
with GraphDatabase.driver(settings.neo4j_uri, auth=auth) as driver:
    constraints, _, _ = driver.execute_query(
        "SHOW CONSTRAINTS YIELD name, type, labelsOrTypes, properties "
        "WHERE name STARTS WITH 'ddigraph_' "
        "RETURN name, type, labelsOrTypes, properties"
    )
    indexes, _, _ = driver.execute_query(
        "SHOW INDEXES YIELD name, type, labelsOrTypes, properties "
        "WHERE name STARTS WITH 'ddigraph_' "
        "RETURN type, labelsOrTypes[0] AS label, properties[0] AS property "
        "ORDER BY label, property"
    )

for row in constraints:
    print(*row.values())
print(len(indexes), "indexes")
for row in indexes:
    if row["label"] == "DDINode":
        print(*row.values())

Expected output:

ddigraph_DDINode_key UNIQUENESS ['DDINode'] ['key']
55 indexes
RANGE DDINode dataset_id
RANGE DDINode ddi_id
RANGE DDINode key
RANGE DDINode urn

What each one is for:

  • The key constraint. A load writes each node with MERGE on its key. The constraint keeps keys unique, and Neo4j backs it with its own index, the key one above. Without it, each write would scan the whole database.
  • urn, ddi_id and dataset_id. These are the lookups your own queries make: a DDI-L object by its URN, any object by its DDI ID, and every node of a Codebook dataset.
  • The other 51. Each one indexes one property of one type, such as Software.name.

Free text, such as label or question_text, has no index. A range index refuses a value over about 8 KB, and a long question text can pass that. So a CONTAINS search reads every node of the type. For a large catalogue, make a full-text index yourself. Note that ddigraph bootstrap --drop-legacy drops every index whose name does not start with ddigraph_, yours included. The Neo4j backend page lists the whole schema.

2. Load this module's datasets

Every dataset ID in this module starts with m17-. A block that loads one uses --replace, so it can run twice and never touches anyone else's data.

The examples use a sample survey: a fictional Labour Force Survey, third quarter 2025. Two files hold it. lfs_lifecycle.xml is the DDI-L 3.3 version: the questionnaire and its routing, 8 questions, 6 code lists and 7 variables. lfs_codebook.xml is the same survey in DDI-Codebook 2.6.

The DDI-L file gives its objects URNs under the agency example.nso. A URN names the same node in every dataset, as Module 4 showed. Other modules load the same file, so a change you make to those nodes would show up in their datasets too. So this module gives the file an agency of its own first:

sed 's/example\.nso/m17.example.nso/g' tests/fixtures/lfs_lifecycle.xml > m17-survey.xml
ddigraph load m17-survey.xml --dataset-id m17-survey --replace
ddigraph load tests/fixtures/lfs_codebook.xml --dataset-id m17-codebook --replace

Expected output:

Pre-ingestion: connecting to Neo4j at ...
Ingestion complete: dataset_id=m17-survey, nodes_written=87, relationships_written=108, stubs=0, references=85, resolved=85, unresolved=0, conflicts=0
Pre-ingestion: connecting to Neo4j at ...
Ingestion complete: dataset_id=m17-codebook, nodes_written=80, relationships_written=48, stubs=0, references=41, resolved=41, unresolved=0, conflicts=0

A Codebook file needs no such step. Its IDs only mean something inside one file, so each of its nodes is scoped to its dataset, and carries a dataset_id property.

3. Count a dataset's nodes by type

A recipe here is a short Cypher query that answers one common question. The first one counts what a dataset holds. Each node points at its Dataset node with IN_DATASET, and has the label DDINode plus its type label:

MATCH (n)-[:IN_DATASET]->(:Dataset {dataset_id: 'm17-codebook'})
UNWIND [label IN labels(n) WHERE label <> 'DDINode'] AS type
RETURN type, count(*) AS nodes
ORDER BY nodes DESC, type
LIMIT 5

UNWIND turns the list of type labels into one row per label. ORDER BY nodes DESC, type puts the largest counts first, and breaks ties by name, so the order never changes.

To check what a query returns, run it from Python. ddigraph writes the same graph to other backends too, so the code box below has a tab for each. This module is about Neo4j: the other tabs show the same step elsewhere, for comparison, and Module 20 and Module 22 teach them. Each tab loads what it needs, runs alone, and cleans up after itself. Pick a tab, and the site remembers it for every code box.

from neo4j import GraphDatabase

import ddigraph
from ddigraph.config import Settings

ddigraph.load("tests/fixtures/lfs_codebook.xml", dataset_id="m17-codebook", replace=True)

COUNT = """
MATCH (n)-[:IN_DATASET]->(:Dataset {dataset_id: 'm17-codebook'})
UNWIND [label IN labels(n) WHERE label <> 'DDINode'] AS type
RETURN type, count(*) AS nodes
ORDER BY nodes DESC, type
LIMIT 5
"""

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(COUNT)

for record in records:
    print(*record.values())
DDIGenericIdentifiable 26
Category 21
Concept 7
Variable 7
Question 5

The Neo4j data stays loaded, for the next recipes and for Browser.

from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.process.anonymous_traversal import traversal
from gremlin_python.process.traversal import T

from ddigraph.backends.gremlin import write_gremlin

connection = DriverRemoteConnection("ws://localhost:8182/gremlin", "g")
g = traversal().with_(connection)
write_gremlin(g, "tests/fixtures/lfs_codebook.xml", dataset_id="m17-codebook")

counts = (
    g.V()
    .has("Dataset", "dataset_id", "m17-codebook")
    .in_("IN_DATASET")
    .groupCount()
    .by(T.label)
    .next()
)
for label, count in sorted(counts.items(), key=lambda pair: (-pair[1], pair[0]))[:5]:
    print(label, count)

# Clean up: the dataset's vertices, then its Dataset vertex
g.V().has("Dataset", "dataset_id", "m17-codebook").in_("IN_DATASET").drop().iterate()
g.V().has("Dataset", "dataset_id", "m17-codebook").drop().iterate()
connection.close()
DDIGenericIdentifiable 26
Category 21
Concept 7
Variable 7
Question 5

A Gremlin vertex has one label, its type, so there is no DDINode to filter out. groupCount() gives a dictionary, which Python sorts.

import psycopg

from ddigraph import ir
from ddigraph.lens.sql import SQLLens

COUNT = """
SELECT l.type_label AS type, count(*) AS nodes
FROM ddigraph_memberships AS m
JOIN ddigraph_labels AS l ON l.key = m.key AND l.flavor = m.flavor
WHERE m.dataset = $1
GROUP BY l.type_label
ORDER BY nodes DESC, type
LIMIT 5
"""

with psycopg.connect("postgresql://postgres:postgres@localhost:5432/postgres") as connection:
    lens = SQLLens(connection)
    lens.write(
        ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m17-codebook"),
        dataset_id="m17-codebook",
    )
    rows = lens.fetch(COUNT, ["m17-codebook"])
    lens.purge("m17-codebook")  # clean up

for row in rows:
    print(*row)
DDIGenericIdentifiable 26
Category 21
Concept 7
Variable 7
Question 5

A membership row stands for IN_DATASET. The type label is joined on the key and the flavor, since a label that several flavors share is a row for each.

import duckdb

from ddigraph import ir
from ddigraph.lens.sql import SQLLens

COUNT = """
SELECT l.type_label AS type, count(*) AS nodes
FROM ddigraph_memberships AS m
JOIN ddigraph_labels AS l ON l.key = m.key AND l.flavor = m.flavor
WHERE m.dataset = $1
GROUP BY l.type_label
ORDER BY nodes DESC, type
LIMIT 5
"""

lens = SQLLens(duckdb.connect())
lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m17-codebook"),
    dataset_id="m17-codebook",
)
for row in lens.fetch(COUNT, ["m17-codebook"]):
    print(*row)
DDIGenericIdentifiable 26
Category 21
Concept 7
Variable 7
Question 5

The same SQL as PostgreSQL, on a database that lives in memory and needs no server.

Every tab prints the same five rows: it is one graph. DDIGenericIdentifiable is what a Codebook element becomes when ddigraph's model has no type of its own for it, such as stdyInfo or location, with or without an ID. Here 7 of the 26 are location elements, one in each variable.

4. A variable's concepts, and a question's variables

In a Codebook file, a variable points at its concept with USES_CONCEPT:

MATCH (v:Variable {dataset_id: 'm17-codebook'})-[:USES_CONCEPT]->(c:Concept)
RETURN v.name AS variable, c.label AS concept
ORDER BY variable

A Codebook node carries a dataset_id property, and bootstrap indexes it. So {dataset_id: 'm17-codebook'} finds this module's variables with one index lookup.

from neo4j import GraphDatabase

import ddigraph
from ddigraph.config import Settings

ddigraph.load("tests/fixtures/lfs_codebook.xml", dataset_id="m17-codebook", replace=True)

CONCEPTS = """
MATCH (v:Variable {dataset_id: 'm17-codebook'})-[:USES_CONCEPT]->(c:Concept)
RETURN v.name AS variable, c.label AS concept
ORDER BY variable
"""

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(CONCEPTS)

for record in records:
    print(" | ".join(record.values()))
AGE | Demographic characteristics
AGEGRP | Demographic characteristics
EDUC | Educational attainment
HOURS | Working time
ILOSTAT | Labour market status
REGION | Place of residence
SEX | Demographic characteristics
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.process.anonymous_traversal import traversal

from ddigraph.backends.gremlin import write_gremlin

connection = DriverRemoteConnection("ws://localhost:8182/gremlin", "g")
g = traversal().with_(connection)
write_gremlin(g, "tests/fixtures/lfs_codebook.xml", dataset_id="m17-codebook")

rows = (
    g.V()
    .has("Variable", "dataset_id", "m17-codebook")
    .as_("v")
    .out("USES_CONCEPT")
    .as_("c")
    .select("v", "c")
    .by("name")
    .by("ddi_label")
    .toList()
)
for row in sorted(rows, key=lambda row: row["v"]):
    print(row["v"], "|", row["c"])

# Clean up: the dataset's vertices, then its Dataset vertex
g.V().has("Dataset", "dataset_id", "m17-codebook").in_("IN_DATASET").drop().iterate()
g.V().has("Dataset", "dataset_id", "m17-codebook").drop().iterate()
connection.close()
AGE | Demographic characteristics
AGEGRP | Demographic characteristics
EDUC | Educational attainment
HOURS | Working time
ILOSTAT | Labour market status
REGION | Place of residence
SEX | Demographic characteristics

In Gremlin, label means the vertex's own label, its type. So ddigraph writes the DDI label as ddi_label.

import psycopg

from ddigraph import ir
from ddigraph.lens.sql import SQLLens

CONCEPTS = """
SELECT variable.string_value, concept.string_value
FROM ddigraph_memberships AS m
JOIN ddigraph_labels AS l ON l.key = m.key AND l.flavor = m.flavor
JOIN ddigraph_relationships AS r ON r.start_key = m.key AND r.type = 'USES_CONCEPT'
LEFT JOIN ddigraph_properties AS variable ON variable.key = r.start_key AND variable.name = 'name'
LEFT JOIN ddigraph_properties AS concept ON concept.key = r.end_key AND concept.name = 'label'
WHERE m.dataset = $1 AND l.type_label = 'Variable'
ORDER BY 1
"""

with psycopg.connect("postgresql://postgres:postgres@localhost:5432/postgres") as connection:
    lens = SQLLens(connection)
    lens.write(
        ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m17-codebook"),
        dataset_id="m17-codebook",
    )
    rows = lens.fetch(CONCEPTS, ["m17-codebook"])
    lens.purge("m17-codebook")  # clean up

for row in rows:
    print(" | ".join(row))
AGE | Demographic characteristics
AGEGRP | Demographic characteristics
EDUC | Educational attainment
HOURS | Working time
ILOSTAT | Labour market status
REGION | Place of residence
SEX | Demographic characteristics

Each property is a row of ddigraph_properties, so each value you want is one more join.

import duckdb

from ddigraph import ir
from ddigraph.lens.sql import SQLLens

CONCEPTS = """
SELECT variable.string_value, concept.string_value
FROM ddigraph_memberships AS m
JOIN ddigraph_labels AS l ON l.key = m.key AND l.flavor = m.flavor
JOIN ddigraph_relationships AS r ON r.start_key = m.key AND r.type = 'USES_CONCEPT'
LEFT JOIN ddigraph_properties AS variable ON variable.key = r.start_key AND variable.name = 'name'
LEFT JOIN ddigraph_properties AS concept ON concept.key = r.end_key AND concept.name = 'label'
WHERE m.dataset = $1 AND l.type_label = 'Variable'
ORDER BY 1
"""

lens = SQLLens(duckdb.connect())
lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m17-codebook"),
    dataset_id="m17-codebook",
)
for row in lens.fetch(CONCEPTS, ["m17-codebook"]):
    print(" | ".join(row))
AGE | Demographic characteristics
AGEGRP | Demographic characteristics
EDUC | Educational attainment
HOURS | Working time
ILOSTAT | Labour market status
REGION | Place of residence
SEX | Demographic characteristics

Look at Demographic characteristics: three variables use it. And Section 3 counted 7 concepts, not 5. A Codebook file writes each variable's concept out in full, inside its <var>. So each one becomes a node of its own: here, three nodes with the same text. DDI-Codebook has no way to share one concept between variables.

Now go the other way: start at a question and find its variables. In the Codebook file, a <qstn> sits inside its <var>, so each question has one variable. The derived variables, AGEGRP and ILOSTAT, have no question at all. The DDI-L file says more. A variable refers to each question it comes from, with REFERENCES_QUESTION, and to a concept that it shares with other variables:

MATCH (q:QuestionItem)-[:IN_DATASET]->(:Dataset {dataset_id: 'm17-survey'})
MATCH (q)<-[:REFERENCES_QUESTION]-(v:Variable)
OPTIONAL MATCH (v)-[:USES_CONCEPT]->(c:Concept)
RETURN q.name AS question, v.name AS variable, c.label AS concept
ORDER BY question, variable

A DDI-L node may belong to several datasets, so it has no dataset_id property: the query starts from the Dataset node instead. (v:Variable) matters here, since a question construct also points at its question with REFERENCES_QUESTION. OPTIONAL MATCH keeps a variable that has no concept, with a null there.

from pathlib import Path

from neo4j import GraphDatabase

import ddigraph
from ddigraph.config import Settings

survey = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
survey = survey.replace("example.nso", "m17.example.nso")
Path("m17-survey.xml").write_text(survey, encoding="utf-8")
ddigraph.load("m17-survey.xml", dataset_id="m17-survey", replace=True)

QUESTIONS = """
MATCH (q:QuestionItem)-[:IN_DATASET]->(:Dataset {dataset_id: 'm17-survey'})
MATCH (q)<-[:REFERENCES_QUESTION]-(v:Variable)
OPTIONAL MATCH (v)-[:USES_CONCEPT]->(c:Concept)
RETURN q.name AS question, v.name AS variable, c.label AS concept
ORDER BY question, variable
"""

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(QUESTIONS)

for record in records:
    print(" | ".join(str(value) for value in record.values()))

Expected output:

AGE | AGE | Demographic characteristics
AGE | AGEGRP | Demographic characteristics
AVAIL | ILOSTAT | Labour market status
EDUC | EDUC | Educational attainment
HOURS | HOURS | Working time
LOOK | ILOSTAT | Labour market status
REGION | REGION | Place of residence
SEX | SEX | Demographic characteristics
WORK | ILOSTAT | Labour market status

Two rows answer questions the Codebook file cannot. The question AGE feeds two variables: AGE, as asked, and AGEGRP, grouped from it. The variable ILOSTAT comes from three questions: WORK, LOOK and AVAIL. And SEX, AGE and AGEGRP share one concept node here, so this dataset has 5 concepts, not 7.

To see part of it as a picture, run this in Neo4j Browser and switch to the graph view. It keeps the two concepts that several variables share, and each question's own link to its concept:

MATCH (q:QuestionItem)-[:IN_DATASET]->(:Dataset {dataset_id: 'm17-survey'})
MATCH path = (q)<-[:REFERENCES_QUESTION]-(v:Variable)-[:USES_CONCEPT]->(c:Concept)
WHERE c.label IN ['Demographic characteristics', 'Labour market status']
OPTIONAL MATCH asked = (q)-[:USES_CONCEPT]->(c)
RETURN path, asked

The same graph in three viewers: pick a tab. Each circle is a node, coloured by its type, as the legend under the picture says. Each arrow is a relationship, named by its type. Click a picture to see it full size.

Neo4j Browser showing the questions SEX, AGE, WORK, LOOK and AVAIL, the variables SEX, AGE, AGEGRP and ILOSTAT that refer to them, and their concepts Demographic characteristics and Labour market status

gremlin-visualizer showing the variables SEX, AGE, AGEGRP and ILOSTAT with their questions and their two concepts, from Gremlin Server

Gremlin Server has no viewer of its own. This picture is from the open-source gremlin-visualizer, which draws what this traversal returns, in colours of its own:

g.V().has('Dataset','dataset_id','m17-survey').in('IN_DATASET').hasLabel('Variable').where(out('USES_CONCEPT').has('ddi_label',within('Demographic characteristics','Labour market status'))).union(identity(),out('REFERENCES_QUESTION','USES_CONCEPT')).dedup()

The viewer's physics is turned off here, and each node sits where it is in the NetworkX tab. You could do the same by dragging the nodes.

The variables SEX, AGE, AGEGRP and ILOSTAT with their questions and their two concepts, drawn by NetworkX and matplotlib

NetworkX has no viewer either. This picture is drawn with networkx.draw_networkx and matplotlib, from the graph to_networkx gives.

5. From an entry point down to the categories

A DDI-L file has no single root. So each load gives its Dataset node a HAS_ENTRY_POINT edge to each place a reader starts from: the object its TopLevelReference names, and each Instrument and StudyUnit. Here, that is the questionnaire. From the instrument, HAS_CONSTRUCT walks the flow of the questionnaire. An IfThenElse adds a branch: THEN leads to what is asked when its condition holds, and ELSE to what is asked when it does not:

MATCH (:Dataset {dataset_id: 'm17-survey'})-[:HAS_ENTRY_POINT]->(i:Instrument)
MATCH path = (i)-[:HAS_CONSTRUCT|THEN|ELSE*1..10]->(c)
RETURN length(path) AS depth, type(last(relationships(path))) AS edge,
       [label IN labels(c) WHERE label <> 'DDINode'][0] AS construct, c.name AS name
ORDER BY [r IN relationships(path) | coalesce(r.ordinal, 0)], edge DESC

*1..10 follows one to ten edges, of any of the three types. length(path) counts them. relationships(path) lists them. Each HAS_CONSTRUCT edge has an ordinal: its place in its sequence, from 0. So sorting on the list of ordinals puts the constructs in the order of the interview. THEN and ELSE have no ordinal, and edge DESC puts THEN first.

from pathlib import Path

from neo4j import GraphDatabase

import ddigraph
from ddigraph.config import Settings

survey = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
survey = survey.replace("example.nso", "m17.example.nso")
Path("m17-survey.xml").write_text(survey, encoding="utf-8")
ddigraph.load("m17-survey.xml", dataset_id="m17-survey", replace=True)

FLOW = """
MATCH (:Dataset {dataset_id: 'm17-survey'})-[:HAS_ENTRY_POINT]->(i:Instrument)
MATCH path = (i)-[:HAS_CONSTRUCT|THEN|ELSE*1..10]->(c)
RETURN length(path) AS depth, type(last(relationships(path))) AS edge,
       [label IN labels(c) WHERE label <> 'DDINode'][0] AS construct, c.name AS name
ORDER BY [r IN relationships(path) | coalesce(r.ordinal, 0)], edge DESC
"""

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(FLOW)

for depth, edge, construct, name in records:
    branch = "" if edge == "HAS_CONSTRUCT" else f"{edge}: "
    print("  " * (depth - 1) + branch + construct, name)

Expected output:

Sequence Main sequence
  QuestionConstruct SEX
  QuestionConstruct AGE
  QuestionConstruct REGION
  QuestionConstruct EDUC
  QuestionConstruct WORK
  IfThenElse Worked last week?
    THEN: QuestionConstruct HOURS
    ELSE: Sequence Job search
      QuestionConstruct LOOK
      QuestionConstruct AVAIL

The Python adds two spaces for each step down. The routing is plain to see: a person who worked last week is asked HOURS, and anyone else is asked LOOK and AVAIL.

Now a question a survey manager might ask: which parts of the questionnaire feed the variable ILOSTAT? Follow the flow down to a question construct, then to its question, then back along a REFERENCES_QUESTION edge from the variable:

MATCH (:Dataset {dataset_id: 'm17-survey'})-[:HAS_ENTRY_POINT]->(i:Instrument)
MATCH path = (i)-[:HAS_CONSTRUCT|THEN|ELSE*1..10]->(qc:QuestionConstruct)
MATCH (qc)-[:REFERENCES_QUESTION]->(:QuestionItem)<-[:REFERENCES_QUESTION]-(:Variable {name: 'ILOSTAT'})
RETURN [n IN nodes(path) | n.name] AS route
ORDER BY [r IN relationships(path) | coalesce(r.ordinal, 0)]
from pathlib import Path

from neo4j import GraphDatabase

import ddigraph
from ddigraph.config import Settings

survey = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
survey = survey.replace("example.nso", "m17.example.nso")
Path("m17-survey.xml").write_text(survey, encoding="utf-8")
ddigraph.load("m17-survey.xml", dataset_id="m17-survey", replace=True)

ROUTES = """
MATCH (:Dataset {dataset_id: 'm17-survey'})-[:HAS_ENTRY_POINT]->(i:Instrument)
MATCH path = (i)-[:HAS_CONSTRUCT|THEN|ELSE*1..10]->(qc:QuestionConstruct)
MATCH (qc)-[:REFERENCES_QUESTION]->(:QuestionItem)<-[:REFERENCES_QUESTION]-(:Variable {name: 'ILOSTAT'})
RETURN [n IN nodes(path) | n.name] AS route
ORDER BY [r IN relationships(path) | coalesce(r.ordinal, 0)]
"""

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(ROUTES)

for record in records:
    print(" > ".join(record["route"]))

Expected output:

LFS questionnaire > Main sequence > WORK
LFS questionnaire > Main sequence > Worked last week? > Job search > LOOK
LFS questionnaire > Main sequence > Worked last week? > Job search > AVAIL

Everyone is asked WORK. LOOK and AVAIL sit in the ELSE branch, so only people who did not work answer them. That fits the rule ILOSTAT follows: a person who worked last week is employed, whatever else they would say.

The next recipe goes down a code list. In DDI 3.2 and 3.3, each Code has an ID of its own, so it is a node: the code list CONTAINS its codes, in order, and each code has the HAS_CATEGORY edge. In DDI 3.1, or for a code with no ID, the edge starts at the code list itself. [:CONTAINS*0..1] takes zero or one CONTAINS step, so one pattern covers both:

MATCH (q:QuestionItem)-[:IN_DATASET]->(:Dataset {dataset_id: 'm17-survey'})
MATCH (q)-[:USES_CODELIST]->(cl:CodeList)-[c:CONTAINS*0..1]->()-[h:HAS_CATEGORY]->(cat:Category)
WITH q, cl, cat
ORDER BY coalesce(head(c).ordinal, h.ordinal)
RETURN q.name AS question, cl.label AS code_list, collect(cat.label) AS categories
ORDER BY question

The first ORDER BY puts the categories in the order of the codes, or of the edges when there are no code nodes. collect keeps that order as it gathers each question's categories into a list.

from pathlib import Path

from neo4j import GraphDatabase

import ddigraph
from ddigraph.config import Settings

survey = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
survey = survey.replace("example.nso", "m17.example.nso")
Path("m17-survey.xml").write_text(survey, encoding="utf-8")
ddigraph.load("m17-survey.xml", dataset_id="m17-survey", replace=True)

CODES = """
MATCH (q:QuestionItem)-[:IN_DATASET]->(:Dataset {dataset_id: 'm17-survey'})
MATCH (q)-[:USES_CODELIST]->(cl:CodeList)-[c:CONTAINS*0..1]->()-[h:HAS_CATEGORY]->(cat:Category)
WITH q, cl, cat
ORDER BY coalesce(head(c).ordinal, h.ordinal)
RETURN q.name AS question, cl.label AS code_list, collect(cat.label) AS categories
ORDER BY question
"""

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(CODES)

for question, code_list, categories in records:
    print(question, "|", code_list, "|", ", ".join(categories))
AVAIL | Yes or no | Yes, No
EDUC | Highest level of education | Primary or less (ISCED 0-1), Lower secondary (ISCED 2), Upper secondary (ISCED 3), Post-secondary non-tertiary (ISCED 4), Tertiary (ISCED 5-8)
LOOK | Yes or no | Yes, No
REGION | Region | Capital region, North, South, East, West
SEX | Sex | Male, Female
WORK | Yes or no | Yes, No
from pathlib import Path

from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.process.anonymous_traversal import traversal
from gremlin_python.process.graph_traversal import __

from ddigraph.backends.gremlin import write_gremlin

survey = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
survey = survey.replace("example.nso", "m17.example.nso")
Path("m17-survey.xml").write_text(survey, encoding="utf-8")

connection = DriverRemoteConnection("ws://localhost:8182/gremlin", "g")
g = traversal().with_(connection)
write_gremlin(g, "m17-survey.xml", dataset_id="m17-survey")

rows = (
    g.V()
    .has("Dataset", "dataset_id", "m17-survey")
    .in_("IN_DATASET")
    .hasLabel("QuestionItem")
    .where(__.out("USES_CODELIST"))
    .order()
    .by("name")
    .project("question", "code_list", "categories")
    .by("name")
    .by(__.out("USES_CODELIST").values("ddi_label"))
    .by(
        __.out("USES_CODELIST")
        .union(__.identity(), __.outE("CONTAINS").order().by("ordinal").inV())
        .out("HAS_CATEGORY")
        .values("ddi_label")
        .fold()
    )
    .toList()
)
for row in rows:
    print(row["question"], "|", row["code_list"], "|", ", ".join(row["categories"]))

# Clean up: the dataset's vertices, then its Dataset vertex
g.V().has("Dataset", "dataset_id", "m17-survey").in_("IN_DATASET").drop().iterate()
g.V().has("Dataset", "dataset_id", "m17-survey").drop().iterate()
connection.close()
AVAIL | Yes or no | Yes, No
EDUC | Highest level of education | Primary or less (ISCED 0-1), Lower secondary (ISCED 2), Upper secondary (ISCED 3), Post-secondary non-tertiary (ISCED 4), Tertiary (ISCED 5-8)
LOOK | Yes or no | Yes, No
REGION | Region | Capital region, North, South, East, West
SEX | Sex | Male, Female
WORK | Yes or no | Yes, No

union(__.identity(), ...) is Gremlin's [:CONTAINS*0..1]: it keeps the code list itself, and adds its codes, sorted by the ordinal of their CONTAINS edges. fold() gathers each question's categories into a list, as collect does.

from pathlib import Path

import psycopg

from ddigraph import ir
from ddigraph.lens.sql import SQLLens

CODES = """
WITH holder AS (
    SELECT key AS code_list, key AS holder, NULL AS ordinal FROM ddigraph_nodes
    UNION ALL
    SELECT start_key, end_key, ordinal FROM ddigraph_relationships WHERE type = 'CONTAINS'
)
SELECT question.string_value, code_list.string_value,
       string_agg(category.string_value, ', ' ORDER BY coalesce(h.ordinal, has.ordinal))
FROM ddigraph_memberships AS m
JOIN ddigraph_labels AS l ON l.key = m.key AND l.flavor = m.flavor
JOIN ddigraph_relationships AS uses ON uses.start_key = m.key AND uses.type = 'USES_CODELIST'
JOIN holder AS h ON h.code_list = uses.end_key
JOIN ddigraph_relationships AS has ON has.start_key = h.holder AND has.type = 'HAS_CATEGORY'
LEFT JOIN ddigraph_properties AS question ON question.key = m.key AND question.name = 'name'
LEFT JOIN ddigraph_properties AS code_list ON code_list.key = uses.end_key AND code_list.name = 'label'
LEFT JOIN ddigraph_properties AS category ON category.key = has.end_key AND category.name = 'label'
WHERE m.dataset = $1 AND l.type_label = 'QuestionItem'
GROUP BY 1, 2
ORDER BY 1
"""

survey = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
survey = survey.replace("example.nso", "m17.example.nso")
Path("m17-survey.xml").write_text(survey, encoding="utf-8")

with psycopg.connect("postgresql://postgres:postgres@localhost:5432/postgres") as connection:
    lens = SQLLens(connection)
    lens.write(ir.parse("m17-survey.xml", dataset_id="m17-survey"), dataset_id="m17-survey")
    rows = lens.fetch(CODES, ["m17-survey"])
    lens.purge("m17-survey")  # clean up

for row in rows:
    print(" | ".join(row))
AVAIL | Yes or no | Yes, No
EDUC | Highest level of education | Primary or less (ISCED 0-1), Lower secondary (ISCED 2), Upper secondary (ISCED 3), Post-secondary non-tertiary (ISCED 4), Tertiary (ISCED 5-8)
LOOK | Yes or no | Yes, No
REGION | Region | Capital region, North, South, East, West
SEX | Sex | Male, Female
WORK | Yes or no | Yes, No

SQL has no *0..1. The holder table pairs each node with itself, and each code list with each code it contains, with the code's place. So one join covers both cases. Variables use code lists too, so the type label keeps only the questions. string_agg gathers each question's categories, as collect does.

from pathlib import Path

import duckdb

from ddigraph import ir
from ddigraph.lens.sql import SQLLens

CODES = """
WITH holder AS (
    SELECT key AS code_list, key AS holder, NULL AS ordinal FROM ddigraph_nodes
    UNION ALL
    SELECT start_key, end_key, ordinal FROM ddigraph_relationships WHERE type = 'CONTAINS'
)
SELECT question.string_value, code_list.string_value,
       string_agg(category.string_value, ', ' ORDER BY coalesce(h.ordinal, has.ordinal))
FROM ddigraph_memberships AS m
JOIN ddigraph_labels AS l ON l.key = m.key AND l.flavor = m.flavor
JOIN ddigraph_relationships AS uses ON uses.start_key = m.key AND uses.type = 'USES_CODELIST'
JOIN holder AS h ON h.code_list = uses.end_key
JOIN ddigraph_relationships AS has ON has.start_key = h.holder AND has.type = 'HAS_CATEGORY'
LEFT JOIN ddigraph_properties AS question ON question.key = m.key AND question.name = 'name'
LEFT JOIN ddigraph_properties AS code_list ON code_list.key = uses.end_key AND code_list.name = 'label'
LEFT JOIN ddigraph_properties AS category ON category.key = has.end_key AND category.name = 'label'
WHERE m.dataset = $1 AND l.type_label = 'QuestionItem'
GROUP BY 1, 2
ORDER BY 1
"""

survey = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
survey = survey.replace("example.nso", "m17.example.nso")
Path("m17-survey.xml").write_text(survey, encoding="utf-8")

lens = SQLLens(duckdb.connect())
lens.write(ir.parse("m17-survey.xml", dataset_id="m17-survey"), dataset_id="m17-survey")
for row in lens.fetch(CODES, ["m17-survey"]):
    print(" | ".join(row))
AVAIL | Yes or no | Yes, No
EDUC | Highest level of education | Primary or less (ISCED 0-1), Lower secondary (ISCED 2), Upper secondary (ISCED 3), Post-secondary non-tertiary (ISCED 4), Tertiary (ISCED 5-8)
LOOK | Yes or no | Yes, No
REGION | Region | Capital region, North, South, East, West
SEX | Sex | Male, Female
WORK | Yes or no | Yes, No

Compare the tabs. Cypher and Gremlin follow the edges in a few lines; SQL needs a join for each step and each value. That is the case for a graph database, in one picture.

AGE and HOURS take a number, so they have no code list and no row. Now look at WORK, LOOK and AVAIL: all three use Yes or no. It is one code list, written once, that three questions refer to. To list only the code lists that several questions share, group by the code list:

MATCH (q:QuestionItem)-[:IN_DATASET]->(:Dataset {dataset_id: 'm17-survey'})
MATCH (q)-[:USES_CODELIST]->(cl:CodeList)
WITH cl, q
ORDER BY q.name
WITH cl, collect(q.name) AS questions
WHERE size(questions) > 1
RETURN cl.label AS code_list, questions
from pathlib import Path

from neo4j import GraphDatabase

import ddigraph
from ddigraph.config import Settings

survey = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
survey = survey.replace("example.nso", "m17.example.nso")
Path("m17-survey.xml").write_text(survey, encoding="utf-8")
ddigraph.load("m17-survey.xml", dataset_id="m17-survey", replace=True)

SHARED = """
MATCH (q:QuestionItem)-[:IN_DATASET]->(:Dataset {dataset_id: 'm17-survey'})
MATCH (q)-[:USES_CODELIST]->(cl:CodeList)
WITH cl, q
ORDER BY q.name
WITH cl, collect(q.name) AS questions
WHERE size(questions) > 1
RETURN cl.label AS code_list, questions
"""

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(SHARED)

for record in records:
    print(record["code_list"], "|", record["questions"])

Expected output:

Yes or no | ['AVAIL', 'LOOK', 'WORK']

This is how you find what an edit would touch. Change the Yes or no list, and three questions change with it. A Codebook file has no shared lists: each <var> writes out its own categories.

6. Stubs: what a file refers to but does not hold

DDI-L files often share their parts. One file may hold the questions, and another the code lists they use. When a file refers to something it does not hold, the load still writes the edge. The edge ends at a stub: a node with the extra label Unresolved and an unresolved_reason, such as not_in_file. When a later load brings the real node, it fills the stub in place. The label and the reason go, and the edges stay.

A list such as Yes or no often lives in a file of common code lists, which each questionnaire refers to. This block plays that out. It cuts the Yes or no code list and its two categories out of the survey file, and loads what is left as m17-questions. Then it loads the whole file as m17-survey. It starts by purging both datasets with Neo4jLens.purge, so the stub is there whatever ran before:

from pathlib import Path

from neo4j import GraphDatabase

import ddigraph
from ddigraph.config import Settings
from ddigraph.lens.neo4j import Neo4jLens

survey = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
survey = survey.replace("example.nso", "m17.example.nso")
# The Yes or no code list and its two categories: three fragments in a row
start = survey.rindex("<Fragment>", 0, survey.index("cl-yesno:1</r:URN>"))
end = survey.index("</Fragment>", survey.index("cat-yesno-2:1</r:URN>")) + len("</Fragment>")
Path("m17-survey.xml").write_text(survey, encoding="utf-8")
Path("m17-questions.xml").write_text(survey[:start] + survey[end:], encoding="utf-8")

STUBS = """
MATCH (s:Unresolved)-[:IN_DATASET]->(:Dataset {dataset_id: 'm17-questions'})
MATCH (n)-[r]->(s)
RETURN n.name AS start, type(r) AS edge, s.identity AS stub, s.unresolved_reason AS reason
ORDER BY start
"""

settings = Settings()
auth = (settings.neo4j_user, settings.neo4j_password.get_secret_value())
with GraphDatabase.driver(settings.neo4j_uri, auth=auth) as driver:
    lens = Neo4jLens(driver)
    lens.purge("m17-questions")
    lens.purge("m17-survey")

    result = ddigraph.load("m17-questions.xml", dataset_id="m17-questions")
    print("stubs:", result.stubs, result.unresolved)
    for record in driver.execute_query(STUBS).records:
        print(" | ".join(str(value) for value in record.values()))

    ddigraph.load("m17-survey.xml", dataset_id="m17-survey")
    print("stubs left:", len(driver.execute_query(STUBS).records))

Expected output:

stubs: 1 {'not_in_file': 3}
AVAIL | USES_CODELIST | urn:ddi:m17.example.nso:cl-yesno:1 | not_in_file
LOOK | USES_CODELIST | urn:ddi:m17.example.nso:cl-yesno:1 | not_in_file
WORK | USES_CODELIST | urn:ddi:m17.example.nso:cl-yesno:1 | not_in_file
stubs left: 0

One stub, and three edges end at it: WORK, LOOK and AVAIL all refer to the missing list. result.unresolved counts those references by reason, so it says 3. The second load brought the list, and filled the stub in place.

Here is the recipe on its own, for Browser:

MATCH (s:Unresolved)-[:IN_DATASET]->(:Dataset {dataset_id: 'm17-questions'})
MATCH (n)-[r]->(s)
RETURN n.name AS start, type(r) AS edge, s.identity AS stub, s.unresolved_reason AS reason
ORDER BY start

A stub holds only key, identity and unresolved_reason. So find one by its identity, not by urn. ddigraph store stubs DATASET gives the same list from the store, with no database, and names the datasets that hold each real node. See Stubs.

7. Reload only what changed: the store

A plain ddigraph load adds and updates, but it never removes. If you delete a variable from the file and load it again, the variable stays in Neo4j. --replace fixes that by purging the dataset first, then writing it all again.

The store (Module 11) gives a third way. It keeps each version of a file on disk as a numbered generation. Its HEAD names the latest one. With --store DIR, a load first writes the file to the store as the next generation. It then sends Neo4j only the delta: what was added, changed or removed since the generation Neo4j holds. Neo4j keeps a small marker node per dataset that names that generation.

This block loads the Codebook file through a store in my-store. It then makes an edit that public files often need: it merges the two oldest age groups, 55-64 and 65 and over, into one group, 55 and over. Small groups are merged so that no one can be picked out. Then it loads the edited file:

cp tests/fixtures/lfs_codebook.xml m17-store.xml
ddigraph load m17-store.xml --store my-store | tail -n 2

# The edit: merge the age groups 55-64 and 65 and over into 55 and over
sed -e 's/<labl>55-64</<labl>55 and over</' \
    -e 's|<catgry><catValu>6</catValu><labl>65 and over</labl></catgry>||' \
    tests/fixtures/lfs_codebook.xml > m17-store.xml
ddigraph load m17-store.xml --store my-store | tail -n 2
ddigraph store diff m17-store 1 2 --store my-store

Expected output:

Ingestion complete: dataset_id=m17-store, nodes_written=80, relationships_written=48, stubs=0, references=41, resolved=41, unresolved=0, conflicts=0
Store: generation=1, delta_from=None, nodes_removed=0, relationships_removed=0
Ingestion complete: dataset_id=m17-store, nodes_written=1, relationships_written=1, stubs=0, references=40, resolved=40, unresolved=0, conflicts=0
Store: generation=2, delta_from=1, nodes_removed=2, relationships_removed=2
Nodes: 1 added, 2 removed, 0 changed
Relationships: 1 added, 2 removed

Read the two Store: lines:

  • The first load wrote the whole file. delta_from=None says so. (With a new store folder, ddigraph purges the dataset first, since it cannot trust what Neo4j holds.)
  • The second load wrote one node and one edge: the new category 55 and over, and the edge from AGEGRP to it. It removed two nodes, the old categories 55-64 and 65 and over, and AGEGRP's two edges to them. A Codebook category has no ID, so ddigraph names it by what it holds. A new label makes a new node.

The second sed expression empties the line of 65 and over, but keeps the line. That matters: each node records the line it starts on. Delete the whole line, and each node below it moves up one line, so the store counts it as changed and writes it again.

The dataset ID comes from the file name, m17-store. A plain load would have left the two old age groups in Neo4j, and --replace would have written all 80 nodes again. The store guide explains each step, and what happens after a crash.

8. Put Neo4j back: repair

Someone may edit the graph in Neo4j by hand, or a script may delete a node. The store still knows what the dataset should be. ddigraph repair DATASET compares the two and writes back only what differs.

It does not compare node by node. It splits the keys into 4,096 buckets by their first three hex digits, and hashes each bucket on both sides. Only the buckets whose hashes differ are read and fixed. --dry-run counts what differs and writes nothing.

Here a short Python script plays the person who edits the graph by hand. It deletes the category North, and gives the variable REGION a new label:

cp tests/fixtures/lfs_codebook.xml m17-store.xml
ddigraph load m17-store.xml --store my-store > /dev/null

python - <<'EOF'
from neo4j import GraphDatabase

from ddigraph.config import Settings

settings = Settings()
auth = (settings.neo4j_user, settings.neo4j_password.get_secret_value())
with GraphDatabase.driver(settings.neo4j_uri, auth=auth) as driver:
    driver.execute_query("MATCH (c:Category {dataset_id: 'm17-store', label: 'North'}) DETACH DELETE c")
    driver.execute_query("MATCH (v:Variable {dataset_id: 'm17-store', name: 'REGION'}) SET v.label = 'Region'")
EOF

ddigraph repair m17-store --store my-store --dry-run
ddigraph repair m17-store --store my-store
ddigraph repair m17-store --store my-store --dry-run

Expected output:

Dataset 'm17-store' against generation 1: 2 buckets differed; would write nodes: 1 added, 0 removed, 1 changed; relationships: 1 added, 0 removed
Dataset 'm17-store' against generation 1: 2 buckets differed; wrote nodes: 1 added, 0 removed, 1 changed; relationships: 1 added, 0 removed
Dataset 'm17-store' against generation 1: 0 buckets differed; would write nodes: 0 added, 0 removed, 0 changed; relationships: 0 added, 0 removed

The repair put back the category North and its edge from the variable REGION, and the label Region of residence. The last dry run finds nothing left to fix. Since a dry run only reads, it makes a cheap check to run on a schedule.

A repair never touches a property the spec does not own, such as one you added, or another dataset's nodes. See Repairing Neo4j.

9. Bulk import with neo4j-admin

ddigraph load writes through Cypher, one transaction per chunk, and merges each node on its key. That is right for keeping a database up to date. To build a new database from a very large file, Neo4j has a faster tool: neo4j-admin database import full. It writes the database files directly, with no transactions and no lookups. But it can only build a new database, or overwrite one that is stopped.

ddigraph export --format neo4j-import writes the files it reads. The export needs no server:

ddigraph export tests/fixtures/lfs_codebook.xml --format neo4j-import -o codebook-import
ls codebook-import

Expected output:

Wrote codebook-import
Format: neo4j-import
Nodes: 80  Relationships: 48
import.sh
nodes.csv
relationships.csv

nodes.csv has one row per node, with a typed column for each property. relationships.csv has one row per edge. It starts with an IN_DATASET edge from each node to the Dataset node, then holds the file's own edges. import.sh runs neo4j-admin on the two files. These files hold the same graph that ddigraph load writes; tests/test_neo4j_import_live.py imports every sample file this way and checks that.

The import itself needs a Neo4j you run yourself, with a shell on its machine. So the steps below are not run by this course's tests. On Community Edition, Neo4j serves one user database at a time. So you build the new database beside the old one, then switch. Call the database that serves now blue (neo4j on a new install), and the new one green:

# 1. Import green while blue serves. Run it as the user that runs Neo4j.
sh codebook-import/import.sh green

# 2. Switch: in conf/neo4j.conf, set
#      initial.dbms.default_database=green
#    then restart Neo4j. Blue stays on disk, stopped.

# 3. Point ddigraph at green, and make the schema neo4j-admin did not make
export DDIGRAPH_NEO4J_DATABASE=green
ddigraph bootstrap

# 4. To roll back, set the default database back to neo4j and restart.

Three things to know:

  • No marker. The import writes no store marker. So the first load --store of that dataset afterwards writes it whole, once.
  • One graph per import. To add more files later, load them with ddigraph load once green serves.
  • Docker. Copy the folder into the container, run the script with docker exec, edit /var/lib/neo4j/conf/neo4j.conf, and run docker restart.

Bulk import and large files shows each step with its output.

10. Aura Free

Aura is Neo4j's hosted service, and Aura Free is its free tier. When you create an instance, Aura gives you a text file of settings to download. Rename it .env and put it in the folder you run ddigraph from. It uses Neo4j's own names, without the DDIGRAPH_ prefix, and ddigraph reads them as they are.

There is a catch. A DDIGRAPH_ variable wins over the .env file. If you set DDIGRAPH_NEO4J_URI in Module 2, unset it first. Try it in a folder of its own, so the example file does not follow you around:

mkdir -p aura-test && cd aura-test
cat > .env <<'EOF'
NEO4J_URI=neo4j+s://abcd1234.databases.neo4j.io
NEO4J_USERNAME=neo4j
NEO4J_PASSWORD=change-me
AURA_INSTANCEID=abcd1234
AURA_INSTANCENAME=Instance01
EOF
unset DDIGRAPH_NEO4J_URI DDIGRAPH_NEO4J_USER DDIGRAPH_NEO4J_PASSWORD
python -c "from ddigraph.config import Settings; s = Settings(); print(s.neo4j_uri, s.neo4j_user)"

Expected output:

neo4j+s://abcd1234.databases.neo4j.io neo4j

The neo4j+s:// scheme turns TLS on and trusts the system's certificates. Do not add --encrypted to it. ddigraph ignores the AURA_ lines. Then ddigraph bootstrap and ddigraph load work as on Docker.

The limits that matter for ddigraph, at the time of writing (check Aura's site for the current ones):

  • Size. A free instance holds at most 200,000 nodes and 400,000 relationships. Each sample file here is tiny, but a large catalogue may not fit.
  • One database. You cannot create a second one, so there is no blue/green switch.
  • No neo4j-admin. You have no shell on the server, so Section 9's import does not apply. Load with ddigraph load, and use --store to keep reloads small.
  • Pauses. A free instance that sits idle for 72 hours is paused. Resume it from the Aura console before you connect. Neo4j deletes a free instance, and its data, once it has been paused for 30 days, so keep your files and your store: they rebuild it.
  • Distance. Each transaction crosses the internet. Keep the chunk size modest, as the tuning page suggests.

Exercises

Scenario

Your team runs a metadata catalogue on Neo4j. You must show a colleague how to find things in it, keep it in step with the files, and plan a move to a new server.

Exercise 1 (O1, O2). A universe is the group of people a variable describes. Which variables state a universe of their own? Load tests/fixtures/lfs_codebook.xml as m17-codebook. Write one query that lists each of its variables with its universe, or None. Use the dataset_id index to stay in that dataset. Then ask the same of the DDI-L dataset m17-survey, starting from its Dataset node. Print each row, and compare.

Expected output:

Codebook:
AGE | None
...
HOURS | Employed persons aged 15 and over
...
DDI-L:
AGE | Persons aged 15 and over living in private households
...
Answer
from pathlib import Path

from neo4j import GraphDatabase

import ddigraph
from ddigraph.config import Settings

ddigraph.load("tests/fixtures/lfs_codebook.xml", dataset_id="m17-codebook", replace=True)
survey = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
survey = survey.replace("example.nso", "m17.example.nso")
Path("m17-survey.xml").write_text(survey, encoding="utf-8")
ddigraph.load("m17-survey.xml", dataset_id="m17-survey", replace=True)

CODEBOOK = """
MATCH (v:Variable {dataset_id: 'm17-codebook'})
OPTIONAL MATCH (v)-[:IN_UNIVERSE]->(u:Universe)
RETURN v.name AS variable, u.label AS universe
ORDER BY variable
"""
LIFECYCLE = """
MATCH (v:Variable)-[:IN_DATASET]->(:Dataset {dataset_id: 'm17-survey'})
OPTIONAL MATCH (v)-[:IN_UNIVERSE]->(u:Universe)
RETURN v.name AS variable, u.label AS universe
ORDER BY variable
"""

settings = Settings()
auth = (settings.neo4j_user, settings.neo4j_password.get_secret_value())
with GraphDatabase.driver(settings.neo4j_uri, auth=auth) as driver:
    for title, query in [("Codebook:", CODEBOOK), ("DDI-L:", LIFECYCLE)]:
        print(title)
        for record in driver.execute_query(query).records:
            print(" | ".join(str(value) for value in record.values()))
Codebook:
AGE | None
AGEGRP | None
EDUC | None
HOURS | Employed persons aged 15 and over
ILOSTAT | None
REGION | None
SEX | None
DDI-L:
AGE | Persons aged 15 and over living in private households
AGEGRP | Persons aged 15 and over living in private households
EDUC | Persons aged 15 and over living in private households
HOURS | Employed persons aged 15 and over
ILOSTAT | Persons aged 15 and over living in private households
REGION | Persons aged 15 and over living in private households
SEX | Persons aged 15 and over living in private households

In the Codebook file, only HOURS has an IN_UNIVERSE edge. A Codebook variable states a universe only where it narrows the study's. The other six take the study's universe, persons aged 15 and over living in private households. That universe is a node too, but no edge reaches it, so a query cannot follow one. In DDI-L, each variable refers to its universe, so the query finds all seven. The dataset_id index makes the first MATCH one lookup. The OPTIONAL MATCH keeps a variable that has no universe.

Exercise 2 (O3). Load tests/fixtures/lfs_codebook.xml through a store, as the dataset m17-edit-store. Then add a category to the variable EDUC, for people who did not answer: code 9, Not stated. Load it again. Print the last line of each load, and the result of a repair dry run.

Expected output:

Store: generation=1, delta_from=None, nodes_removed=0, relationships_removed=0
Store: generation=2, delta_from=1, nodes_removed=0, relationships_removed=0
Dataset 'm17-edit-store' against generation 2: 0 buckets differed; would write nodes: 0 added, 0 removed, 0 changed; relationships: 0 added, 0 removed
Answer
cp tests/fixtures/lfs_codebook.xml m17-edit-store.xml
ddigraph load m17-edit-store.xml --store my-store | tail -n 1
sed 's|<labl>Tertiary (ISCED 5-8)</labl></catgry>|&<catgry missing="Y"><catValu>9</catValu><labl>Not stated</labl></catgry>|' \
    tests/fixtures/lfs_codebook.xml > m17-edit-store.xml
ddigraph load m17-edit-store.xml --store my-store | tail -n 1
ddigraph repair m17-edit-store --store my-store --dry-run
Store: generation=1, delta_from=None, nodes_removed=0, relationships_removed=0
Store: generation=2, delta_from=1, nodes_removed=0, relationships_removed=0
Dataset 'm17-edit-store' against generation 2: 0 buckets differed; would write nodes: 0 added, 0 removed, 0 changed; relationships: 0 added, 0 removed

In sed, & stands for the text it matched, so the new category goes right after Tertiary, on the same line. No other node moves. missing="Y" marks a code for a missing answer. The second load is a delta from generation 1: it wrote only the new category and its edge from EDUC. Neo4j then holds HEAD, so the dry run finds no bucket to fix.

Exercise 3 (O4). Export tests/fixtures/lfs_codebook.xml with --format neo4j-import. Read relationships.csv with Python's csv module, and print how many rows there are of each type, most common first.

Expected output:

IN_DATASET 79
...
total 127
Answer
import csv
from collections import Counter

from ddigraph import export

export("tests/fixtures/lfs_codebook.xml", "codebook-import", format="neo4j-import")

with open("codebook-import/relationships.csv", newline="", encoding="utf-8") as f:
    types = Counter(row[":TYPE"] for row in csv.DictReader(f))
for name, count in sorted(types.items(), key=lambda item: (-item[1], item[0])):
    print(name, count)
print("total", sum(types.values()))
IN_DATASET 79
USES_CATEGORY 21
IN_FILE 7
USES_CONCEPT 7
ASKED_AS 5
DESCRIBES 3
ASSOCIATED_WITH 2
CONTRIBUTES_TO 1
COVERS 1
IN_UNIVERSE 1
total 127

Each of the 80 nodes but the Dataset node has an IN_DATASET row, so 79. The other 48 are the file's own edges, the 48 the export reported: 21 from the variables to their categories, 7 to the data file, and so on. neo4j-admin imports exactly these rows.

Exercise 4 (O5). In a new folder, write an Aura-style .env file. Print the URI ddigraph reads with the .env file alone. Then print it again with DDIGRAPH_NEO4J_URI set for one command.

Expected output:

neo4j+s://abcd1234.databases.neo4j.io
bolt://localhost:7687
Answer
mkdir -p aura-test && cd aura-test
printf 'NEO4J_URI=neo4j+s://abcd1234.databases.neo4j.io\nNEO4J_USERNAME=neo4j\nNEO4J_PASSWORD=change-me\n' > .env
unset DDIGRAPH_NEO4J_URI
python -c "from ddigraph.config import Settings; print(Settings().neo4j_uri)"
DDIGRAPH_NEO4J_URI=bolt://localhost:7687 python -c "from ddigraph.config import Settings; print(Settings().neo4j_uri)"
neo4j+s://abcd1234.databases.neo4j.io
bolt://localhost:7687

A DDIGRAPH_ variable wins over the bare NEO4J_ names of the .env file. A stale variable in your shell can point ddigraph at the wrong server.


Quiz

Question 1 (O1): Why does ddigraph bootstrap put a uniqueness constraint on key?

A. To stop two datasets from holding the same node.

B. Each write merges a node on its key. The constraint keeps keys unique, and its index makes each merge a lookup, not a scan.

C. Neo4j needs a constraint before it accepts any node.

D. It makes CONTAINS searches on question_text fast.

Answer

B. A load runs MERGE on key for every node. The constraint stops duplicates, and the index behind it makes each lookup fast. A is tempting, but two datasets may share a node: it then has an IN_DATASET edge to each.

Question 2 (O1): A search with WHERE q.question_text CONTAINS 'work' is slow on a large catalogue. Why?

A. bootstrap was not run.

B. CONTAINS cannot use any kind of index.

C. Free text such as question_text has no index, since a range index refuses long values. The query reads every question.

D. The question text is stored on the Dataset node.

Answer

C. ddigraph indexes keys, IDs, URNs and short typed properties, not free text. For text search, make a full-text index yourself. Then remember that bootstrap --drop-legacy would drop it.

Question 3 (O2): On a DDI 3.3 file, MATCH (cl:CodeList)-[:CONTAINS*0..1]->()-[:HAS_CATEGORY]->(cat) finds the categories. Why not write (cl:CodeList)-[:HAS_CATEGORY]->(cat)?

A. HAS_CATEGORY only exists in Codebook files.

B. In DDI 3.2 and 3.3 each code has an ID, so it is a node. The HAS_CATEGORY edge starts at the code, one step below the code list.

C. The shorter pattern is fine; the longer one only sorts the result.

D. Neo4j cannot match two relationships in one pattern.

Answer

B. The shortcut finds nothing when codes have IDs. *0..1 also covers a code with no ID, as in DDI 3.1, where the edge starts at the code list. So C is wrong: the shorter pattern misses most files.

Question 4 (O2): You load questions.xml. Its questions use the Yes or no code list, which lives in common-codes.xml. What does Neo4j hold for that code list before you load common-codes.xml?

A. Nothing: the load drops the reference.

B. The load fails until common-codes.xml is loaded.

C. A copy of the code list, with no categories.

D. A stub: a node labelled Unresolved with unresolved_reason not_in_file, at the end of the USES_CODELIST edge.

Answer

D. The edge is kept and ends at a stub. Loading common-codes.xml later fills the stub in place, so the edge needs no rewrite. A is what you might expect from a strict parser, but ddigraph keeps the reference.

Question 5 (O3): You deleted a variable from a file and reloaded it with a plain ddigraph load (no --store, no --replace). What happens to the variable in Neo4j?

A. It stays. A plain load adds and updates, but never removes.

B. It goes, since the file no longer holds it.

C. It becomes a stub.

D. The load refuses the file.

Answer

A. Only --replace, which purges first, or a load through the store, which sends the delta, removes what the file dropped. The store's delta also removes it in one small write, not a whole reload.

Question 6 (O3): ddigraph repair DATASET --dry-run reports 3 buckets differed. What does it compare?

A. The file on disk with Neo4j, element by element.

B. Hashes of 4,096 buckets of keys, in Neo4j and in the store's HEAD. Only the buckets that differ are read.

C. The dataset's node count with the store's.

D. Two generations of the store, as store diff does.

Answer

B. Repair reads the store, not the file. It hashes the same buckets on both sides, so it only reads the few that differ. D is store diff, which never looks at Neo4j.

Question 7 (O4): Why does a bulk import on Community Edition use a blue/green switch?

A. neo4j-admin only writes CSV files.

B. Community Edition serves one user database at a time, and the import cannot write into the database that serves. So you import a new one beside it, then switch with a restart.

C. The import needs two copies to check each other.

D. Blue/green is only needed on Aura.

Answer

B. You import green while blue serves, set green as the default database, and restart. Blue stays on disk for a rollback. D is backwards: Aura gives you no neo4j-admin at all.

Question 8 (O5): Your folder holds Aura's .env file, but ddigraph load still connects to bolt://localhost:7687. What is the likely cause?

A. ddigraph cannot read Aura's variable names.

B. Aura needs --encrypted.

C. DDIGRAPH_NEO4J_URI is still set in your shell, and it wins over the .env file.

D. The .env file must be in your home folder.

Answer

C. ddigraph reads NEO4J_URI and the other bare names, but a DDIGRAPH_ variable wins. Unset it. B is wrong: the neo4j+s:// scheme already turns TLS on.


Check yourself

  • I can run ddigraph bootstrap, list the constraint and the indexes it makes, and say what each one is for. (O1)
  • I can write Cypher recipes from a question to its variables and concepts, from an entry point down a code list, and to a dataset's stubs. (O2)
  • I can load through the store so a reload sends only the delta, and bring Neo4j back to HEAD with ddigraph repair. (O3)
  • I can export a file for neo4j-admin and explain the blue/green steps of a bulk import. (O4)
  • I can point ddigraph at Aura Free with its .env file, and name the limits that matter. (O5)

Next: Module 18: NetworkX