Skip to content

Module 7: Your first graph database: Neo4j

Learning objectives

By the end of this module, you can:

  • O1. Create ddigraph's schema in Neo4j with ddigraph bootstrap, and say what it creates.
  • O2. Load a DDI file into its own dataset with ddigraph load --dataset-id, reload it with --replace, and read the load's report.
  • O3. Explore a dataset in Neo4j Browser with Cypher: count nodes by type, list variables, and follow a code list to its categories.
  • O4. Run Cypher from Python with the neo4j driver, with parameters, and read the records.
  • O5. Keep each query to one dataset through its IN_DATASET edges, and remove a dataset when you are done.

Prerequisites: Module 6

Time: 50 min self-paced / 70 min instructor-led.

Needs: Neo4j 5, in Docker or on Aura Free (Module 2 sets it up). The tabs for other backends are optional: Gremlin Server and PostgreSQL from Module 2, and the duckdb and oxigraph extras.

New in this module: ddigraph bootstrap, ddigraph load, --dataset-id, --replace, Neo4j Browser, Cypher MATCH and RETURN, IN_DATASET, the neo4j driver, execute_query, Neo4jLens.purge


1. Why a database

So far the graph has lived in memory, and vanished when the script ended. A graph database keeps it. Many people and programs can then query it, and it can grow far beyond one file. Neo4j is the graph database ddigraph knows best. It has its own query language, Cypher, and a web page, Neo4j Browser, that draws what a query returns.

Start your server, and check that ddigraph reaches it, as in Module 2. Every command below reads the same DDIGRAPH_NEO4J_ variables or .env file.


2. Create the schema

A database needs a little preparation before the first load: a constraint that keeps each node's key unique, and indexes that make lookups fast. --dry-run prints the statements without running them, so it needs no server:

ddigraph bootstrap --dry-run > schema.txt
head -n 4 schema.txt
tail -n 1 schema.txt

Expected output:

CREATE CONSTRAINT ddigraph_DDINode_key IF NOT EXISTS
FOR (n:DDINode) REQUIRE n.key IS UNIQUE;
CREATE RANGE INDEX ddigraph_DDINode_urn IF NOT EXISTS
FOR (n:DDINode) ON (n.urn);
Dry run: 55 statements (0 drops) would run on database 'neo4j'; none ran

Every node ddigraph writes has the label DDINode, beside its type label. The constraint makes its key unique, and the range indexes cover the properties that queries often look up, such as urn and ddi_id. One schema serves all three flavors. Now run it for real:

ddigraph bootstrap

Expected output:

Schema ensured for database 'neo4j'

Each statement says IF NOT EXISTS, so running it again changes nothing. Run it once per database, before the first load.


3. Load a file

ddigraph load reads a file, detects its flavor and writes the graph. Load the Labour Force Survey twice: its codebook and its DDI-L file, each into a dataset of its own:

ddigraph load tests/fixtures/lfs_codebook.xml --dataset-id m07-codebook --replace
ddigraph load tests/fixtures/lfs_lifecycle.xml --dataset-id m07-survey --replace

Expected output:

Pre-ingestion: connecting to Neo4j at ... (database 'neo4j'); credentials from ...; dry-run/validate-only is OFF; format: codebook
Ingestion complete: dataset_id=m07-codebook, nodes_written=80, relationships_written=48, stubs=0, references=41, resolved=41, unresolved=0, conflicts=0
Pre-ingestion: connecting to Neo4j at ... (database 'neo4j'); credentials from ...; dry-run/validate-only is OFF; format: lifecycle
Ingestion complete: dataset_id=m07-survey, nodes_written=87, relationships_written=108, stubs=0, references=85, resolved=85, unresolved=0, conflicts=0
  • --dataset-id names the dataset: the file's place in the database. It defaults to the file name. One database can hold many datasets, so pick a name you will recognize.
  • --replace removes the dataset first, then loads the file again. A plain reload only adds and updates, so an element you deleted from the file would stay. A node that another dataset also holds is kept for it.
  • The report. nodes_written and relationships_written match the preview of Module 3. references counts the links the file makes, such as a variable's link to its question, and resolved those whose end was found: all of them here. unresolved counts the links whose end is not in the file, and conflicts the elements dropped because an earlier element had the same key. Both are 0, as they should be for a clean file. A file that reuses an ID, or points at an object kept elsewhere, shows them here.

The same step works on other backends, from Python. Pick a tab. Each one loads the survey's codebook into a dataset of its own and prints what it wrote. The tabs other than Neo4j remove their data at the end.

import ddigraph

ddigraph.bootstrap()
result = ddigraph.load("tests/fixtures/lfs_codebook.xml", dataset_id="m07-codebook", replace=True)
print(result.nodes_written, "nodes,", result.relationships_written, "relationships")
80 nodes, 48 relationships

ddigraph.load is the command's Python twin. It reads the server's address from the same settings.

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)
result = write_gremlin(g, "tests/fixtures/lfs_codebook.xml", dataset_id="m07-codebook")
print(result.nodes, "nodes,", result.relationships, "relationships")

# Clean up: the dataset's vertices, then its Dataset vertex
g.V().has("Dataset", "dataset_id", "m07-codebook").in_("IN_DATASET").drop().iterate()
g.V().has("Dataset", "dataset_id", "m07-codebook").drop().iterate()
connection.close()
80 nodes, 48 relationships

ddigraph writes to Gremlin but has no reader for it, so you query it with gremlinpython. write_gremlin is safe to run twice: it updates what is there.

import psycopg

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

with psycopg.connect("postgresql://postgres:postgres@localhost:5432/postgres") as connection:
    lens = SQLLens(connection)
    lens.purge("m07-codebook")
    chunks = ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m07-codebook")
    result = lens.write(chunks, dataset_id="m07-codebook")
    print(result.nodes, "nodes,", result.relationships, "relationships")
    lens.purge("m07-codebook")
80 nodes, 48 relationships

The SQL lens keeps the graph in plain tables whose names start with ddigraph_. purge removes one dataset.

import duckdb

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

lens = SQLLens(duckdb.connect())
chunks = ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m07-codebook")
result = lens.write(chunks, dataset_id="m07-codebook")
print(result.nodes, "nodes,", result.relationships, "relationships")
80 nodes, 48 relationships

DuckDB runs inside Python, with the same tables as PostgreSQL. This database lives in memory, so there is nothing to clean up.

from ddigraph import ir
from ddigraph.lens.oxigraph import OxigraphLens

lens = OxigraphLens()
chunks = ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m07-codebook")
result = lens.write(chunks, dataset_id="m07-codebook")
print(result.nodes, "nodes,", result.relationships, "relationships")
80 nodes, 48 relationships

Oxigraph stores the graph as RDF, which Module 8 explains. OxigraphLens() keeps it in memory; give it a folder to keep it on disk.

Every backend wrote the same 80 nodes and 48 relationships: one graph, five homes.


4. Explore in Neo4j Browser

Open http://localhost:7474 (or your Aura instance's page), and log in. Type a query in the box at the top, then press the run button or Ctrl+Enter.

Cypher draws patterns with brackets and arrows. (v:Variable) is a node with the label Variable, bound to the name v. -[:USES_CONCEPT]-> is an edge of that type. {dataset_id: 'm07-codebook'} asks for a property value. MATCH finds the pattern, and RETURN says what to show.

First, a picture. The codebook's seven variables and all they point at make about 40 nodes, too many to read. This query takes three variables of m07-codebook and the nodes they point at: SEX, a question with two categories, ILOSTAT, a derived variable, and HOURS, a number asked of employed people only:

MATCH (v:Variable)-[:IN_DATASET]->(:Dataset {dataset_id: 'm07-codebook'})
WHERE v.name IN ['SEX', 'ILOSTAT', 'HOURS']
MATCH p = (v)-[r]->(x)
WHERE type(r) <> 'IN_DATASET'
RETURN p

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 Codebook graph: the variables SEX, ILOSTAT and HOURS of m07-codebook, and the questions, concepts, categories, universe and data file they point at

gremlin-visualizer showing the same Codebook graph from Gremlin Server: the variables SEX, ILOSTAT and HOURS and the nodes they point at

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','m07-codebook').in('IN_DATASET').hasLabel('Variable').has('name', within('SEX','ILOSTAT','HOURS')).union(identity(), out().not(hasLabel('Dataset'))).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 same Codebook graph drawn by NetworkX and matplotlib: the variables SEX, ILOSTAT and HOURS and the nodes they point at

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

Each variable sits in the middle of its links: the hub you saw in Module 3's preview. All three share the data file, lfs_2025q3.csv. SEX and HOURS each have a question; ILOSTAT has none, as it is derived. Only HOURS has a universe of its own, "Employed persons aged 15 and over". Drag the nodes, and double-click one to see its neighbors.

Always start from the dataset

One database holds many datasets: the two you loaded, and any others. (v:Variable) alone would find the variables of every dataset. Every member of a dataset has an IN_DATASET edge to its Dataset node, so -[:IN_DATASET]->(:Dataset {dataset_id: 'm07-codebook'}) keeps the query to one file. The queries in this module all start that way.

Count the nodes by type. labels(n) lists a node's labels; UNWIND turns the list into rows, and the WHERE drops DDINode, which every node has:

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

Neo4j Browser's result table for the count of nodes by type in m07-codebook

The result is a table, as in the preview of Module 3: 26 DDIGenericIdentifiable, 21 Category, 7 Concept, 7 Variable and 5 Question nodes. The top row, DDIGenericIdentifiable, is the catch-all type you met there. A Codebook element that ddigraph has no type of its own for becomes a DDIGenericIdentifiable node, and keeps its XML tag in element_tag. List those tags:

MATCH (n:DDIGenericIdentifiable)-[:IN_DATASET]->(:Dataset {dataset_id: 'm07-codebook'})
RETURN n.element_tag AS tag, count(*) AS nodes
ORDER BY nodes DESC, tag

Here they are parts of the study, file and variable descriptions, such as seven location elements, one per variable, and the two derivation elements of AGEGRP and ILOSTAT. List the variables with their questions. OPTIONAL MATCH keeps a variable even when it has no question:

MATCH (v:Variable)-[:IN_DATASET]->(:Dataset {dataset_id: 'm07-codebook'})
OPTIONAL MATCH (v)-[:ASKED_AS]->(q:Question)
RETURN v.name AS variable, v.label AS label, q.question_text AS question
ORDER BY v.ddi_id

AGEGRP and ILOSTAT come back with an empty question: they are derived. A plain MATCH would drop them.

Follow a question to its code list and its categories, in the Lifecycle dataset. [:CONTAINS*0..1] means "zero or one CONTAINS edge", so the same query works whether the categories hang off the codes (DDI 3.2 and 3.3) or off the code list (DDI 3.1), as Module 5 explained:

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

The order of the categories is kept on an edge's ordinal. With codes, it is on the CONTAINS edge from the list to each code. Each code has one category, so its HAS_CATEGORY edge always has the ordinal 0. Without codes, the order is on HAS_CATEGORY. c is the list of CONTAINS edges the pattern took, none or one, and coalesce takes the first ordinal that is there. The three questions WORK, LOOK and AVAIL all lead to the same list, "Yes or no".

Walk the questionnaire from its entry point. [:HAS_CONSTRUCT|THEN|ELSE*1..4] follows one to four edges of those three types:

MATCH (:Dataset {dataset_id: 'm07-survey'})-[:HAS_ENTRY_POINT]->(i:Instrument)
MATCH path = (i)-[:HAS_CONSTRUCT|THEN|ELSE*1..4]->(c)
RETURN i.name AS instrument, length(path) AS depth, labels(c) AS construct, c.name AS name

The main sequence asks SEX, AGE, REGION, EDUC and WORK, then branches at "Worked last week?". THEN leads to HOURS, for people who worked. ELSE leads to the "Job search" sequence, LOOK and AVAIL.

The Neo4j backend page has more queries, and Graph relationships lists every edge type.


5. Count nodes by type, from Python

Browser is for looking. A program asks the same questions through a driver: the library that talks to the server. Here is the count by type from Python, then the same count on the other backends. Pick a tab.

from neo4j import GraphDatabase

import ddigraph
from ddigraph.config import Settings

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

query = """
MATCH (n)-[:IN_DATASET]->(:Dataset {dataset_id: $dataset})
UNWIND labels(n) AS label
WITH label WHERE label <> 'DDINode'
RETURN label, count(*) AS nodes
ORDER BY nodes DESC, label
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, _summary, _keys = driver.execute_query(
        query, dataset="m07-codebook", database_=settings.neo4j_database
    )
for record in records:
    print(record["label"], record["nodes"])
DDIGenericIdentifiable 26
Category 21
Concept 7
Variable 7
Question 5
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="m07-codebook")

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

# Clean up: the dataset's vertices, then its Dataset vertex
g.V().has("Dataset", "dataset_id", "m07-codebook").in_("IN_DATASET").drop().iterate()
g.V().has("Dataset", "dataset_id", "m07-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 drop. groupCount returns a dictionary, which Python sorts.

import psycopg

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

query = """
SELECT l.type_label, 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 = %s
GROUP BY l.type_label
ORDER BY nodes DESC, l.type_label
LIMIT 5
"""
with psycopg.connect("postgresql://postgres:postgres@localhost:5432/postgres") as connection:
    lens = SQLLens(connection)
    lens.purge("m07-codebook")
    lens.write(
        ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m07-codebook"),
        dataset_id="m07-codebook",
    )
    for label, total in connection.execute(query, ["m07-codebook"]).fetchall():
        print(label, total)
    lens.purge("m07-codebook")
DDIGenericIdentifiable 26
Category 21
Concept 7
Variable 7
Question 5

ddigraph_memberships plays the part of IN_DATASET: one row per node and dataset. Its flavor picks the node's type label in ddigraph_labels.

import duckdb

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

query = """
SELECT l.type_label, 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 = ?
GROUP BY l.type_label
ORDER BY nodes DESC, l.type_label
LIMIT 5
"""
connection = duckdb.connect()
lens = SQLLens(connection)
lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m07-codebook"),
    dataset_id="m07-codebook",
)
for label, total in connection.execute(query, ["m07-codebook"]).fetchall():
    print(label, total)
DDIGenericIdentifiable 26
Category 21
Concept 7
Variable 7
Question 5

The SQL is the PostgreSQL tab's, with DuckDB's ? for the parameter where psycopg writes %s.

from ddigraph import ir
from ddigraph.lens.oxigraph import OxigraphLens

query = """
PREFIX ddigraph: <https://pbisson44.github.io/ddigraph/ns/1.0/>
SELECT ?type (COUNT(?node) AS ?nodes)
WHERE {
  ?membership ddigraph:dataset "m07-codebook" ;
              ddigraph:member ?node .
  ?node a ?class .
  FILTER(STRSTARTS(STR(?class), STR(ddigraph:)))
  BIND(STRAFTER(STR(?class), STR(ddigraph:)) AS ?type)
}
GROUP BY ?type
ORDER BY DESC(?nodes) ?type
LIMIT 5
"""
lens = OxigraphLens()
lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m07-codebook"),
    dataset_id="m07-codebook",
)
for row in lens.store.query(query):
    print(row["type"].value, row["nodes"].value)
DDIGenericIdentifiable 26
Category 21
Concept 7
Variable 7
Question 5

This is SPARQL, the query language of RDF. Each node has two classes, a published one and ddigraph's own, so the FILTER keeps ddigraph's. A membership is a resource of its own, which plays the part of IN_DATASET.

Read the Neo4j tab line by line:

  • Settings() reads the server's address, user and password, the way every ddigraph command does.
  • GraphDatabase.driver(uri, auth=...) opens a connection to the server. The with block closes it at the end.
  • execute_query(query, dataset=..., database_=...) runs one query. Each keyword argument is a parameter: $dataset in the query takes the value "m07-codebook". Arguments that end in _, such as database_, are options of the driver, not parameters.
  • The records. execute_query returns the records, a summary and the column names. A record reads like a dictionary: record["label"].

Pass values as parameters, never by pasting them into the query text. The server checks their types, a value cannot change the query, and the server can reuse the query's plan.


6. A variable's concept and categories

Now follow edges from one variable, REGION, to its concept and its categories. The categories come in order, by the edge's ordinal. Pick a tab:

from neo4j import GraphDatabase

import ddigraph
from ddigraph.config import Settings

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

query = """
MATCH (v:Variable {name: $variable})-[:IN_DATASET]->(:Dataset {dataset_id: $dataset})
MATCH (v)-[r:USES_CONCEPT|USES_CATEGORY]->(target)
RETURN CASE type(r) WHEN 'USES_CONCEPT' THEN 'concept' ELSE 'category' END AS kind,
       target.label AS label
ORDER BY type(r) DESC, r.ordinal
"""
settings = Settings()
auth = (settings.neo4j_user, settings.neo4j_password.get_secret_value())
with GraphDatabase.driver(settings.neo4j_uri, auth=auth) as driver:
    records, _summary, _keys = driver.execute_query(
        query, variable="REGION", dataset="m07-codebook", database_=settings.neo4j_database
    )
for record in records:
    print(record["kind"], record["label"])
concept Place of residence
category Capital region
category North
category South
category East
category West
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

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


def variable():
    """The variable REGION of the dataset m07-codebook."""
    return (
        g.V()
        .has("Variable", "name", "REGION")
        .where(__.out("IN_DATASET").has("dataset_id", "m07-codebook"))
    )


for label in variable().out("USES_CONCEPT").values("ddi_label").toList():
    print("concept", label)
for label in (
    variable().outE("USES_CATEGORY").order().by("ordinal").inV().values("ddi_label").toList()
):
    print("category", label)

# Clean up: the dataset's vertices, then its Dataset vertex
g.V().has("Dataset", "dataset_id", "m07-codebook").in_("IN_DATASET").drop().iterate()
g.V().has("Dataset", "dataset_id", "m07-codebook").drop().iterate()
connection.close()
concept Place of residence
category Capital region
category North
category South
category East
category West

Gremlin writes a node's label property as ddi_label, since label means the vertex's type there. A traversal is used up once it runs, so variable() builds a fresh one each time.

import psycopg

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

query = """
SELECT CASE r.type WHEN 'USES_CONCEPT' THEN 'concept' ELSE 'category' END AS kind,
       p.string_value AS label
FROM ddigraph_memberships AS m
JOIN ddigraph_labels AS l ON l.key = m.key AND l.flavor = m.flavor
JOIN ddigraph_properties AS i ON i.key = m.key AND i.name = 'name'
JOIN ddigraph_relationships AS r ON r.start_key = m.key
JOIN ddigraph_properties AS p ON p.key = r.end_key AND p.name = 'label'
WHERE m.dataset = %s AND l.type_label = 'Variable' AND i.string_value = %s
  AND r.type IN ('USES_CONCEPT', 'USES_CATEGORY')
ORDER BY r.type DESC, r.ordinal
"""
with psycopg.connect("postgresql://postgres:postgres@localhost:5432/postgres") as connection:
    lens = SQLLens(connection)
    lens.purge("m07-codebook")
    lens.write(
        ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m07-codebook"),
        dataset_id="m07-codebook",
    )
    for kind, label in connection.execute(query, ["m07-codebook", "REGION"]).fetchall():
        print(kind, label)
    lens.purge("m07-codebook")
concept Place of residence
category Capital region
category North
category South
category East
category West

Each property is a row of ddigraph_properties, so the query joins it once for the variable's name and once for each end's label.

import duckdb

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

query = """
SELECT CASE r.type WHEN 'USES_CONCEPT' THEN 'concept' ELSE 'category' END AS kind,
       p.string_value AS label
FROM ddigraph_memberships AS m
JOIN ddigraph_labels AS l ON l.key = m.key AND l.flavor = m.flavor
JOIN ddigraph_properties AS i ON i.key = m.key AND i.name = 'name'
JOIN ddigraph_relationships AS r ON r.start_key = m.key
JOIN ddigraph_properties AS p ON p.key = r.end_key AND p.name = 'label'
WHERE m.dataset = ? AND l.type_label = 'Variable' AND i.string_value = ?
  AND r.type IN ('USES_CONCEPT', 'USES_CATEGORY')
ORDER BY r.type DESC, r.ordinal
"""
connection = duckdb.connect()
lens = SQLLens(connection)
lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m07-codebook"),
    dataset_id="m07-codebook",
)
for kind, label in connection.execute(query, ["m07-codebook", "REGION"]).fetchall():
    print(kind, label)
concept Place of residence
category Capital region
category North
category South
category East
category West
from ddigraph import ir
from ddigraph.lens.oxigraph import OxigraphLens

query = """
PREFIX ddigraph: <https://pbisson44.github.io/ddigraph/ns/1.0/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
SELECT ?kind ?label
WHERE {
  ?membership ddigraph:dataset "m07-codebook" ;
              ddigraph:member ?variable .
  ?variable a ddigraph:Variable ;
            ddigraph:name "REGION" .
  ?edge rdf:subject ?variable ;
        rdf:predicate ?type ;
        rdf:object ?target .
  FILTER(?type IN (ddigraph:usesConcept, ddigraph:usesCategory))
  OPTIONAL { ?edge ddigraph:ordinal ?ordinal }
  ?target rdfs:label|skos:prefLabel ?label .
  BIND(IF(?type = ddigraph:usesConcept, "concept", "category") AS ?kind)
}
ORDER BY DESC(?type) ?ordinal
"""
lens = OxigraphLens()
lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m07-codebook"),
    dataset_id="m07-codebook",
)
for row in lens.store.query(query):
    print(row["kind"].value, row["label"].value)
concept Place of residence
category Capital region
category North
category South
category East
category West

A plain RDF triple has no order, so the query reads each edge's statement (rdf:subject, rdf:predicate, rdf:object), which carries its ordinal. A concept's or a category's label is skos:prefLabel in RDF.

In Cypher, [r:USES_CONCEPT|USES_CATEGORY] matches an edge of either type, and binds it to r. type(r) gives its type, and r.ordinal its place in the list. The concept edge has no ordinal, so it sorts by its type alone.


7. Clean up

When you no longer need a dataset, remove it. Neo4jLens.purge deletes the dataset's members that no other dataset holds, with their edges, then its Dataset node:

from neo4j import GraphDatabase

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

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, database=settings.neo4j_database)
    for dataset in ("m07-codebook", "m07-survey"):
        lens.purge(dataset)
    records, _summary, _keys = driver.execute_query(
        "MATCH (d:Dataset) WHERE d.dataset_id STARTS WITH 'm07-' RETURN count(d) AS left",
        database_=settings.neo4j_database,
    )
print("m07 datasets left:", records[0]["left"])

Expected output:

m07 datasets left: 0

A DDI-L node, named by its URN, can belong to several datasets. Purging one dataset keeps such a node for the others. A Codebook node is scoped to its dataset, so it always goes. To start a dataset over, ddigraph load --replace does the same purge before it loads.


Exercises

Scenario

Your team keeps the Labour Force Survey in one Neo4j database, one dataset per wave. You load the survey's files, answer a few questions about them, and leave the database as you found it.

Exercise 1 (O1, O2). Run ddigraph bootstrap twice, then load tests/fixtures/lfs_lifecycle.xml twice as the dataset m07-survey, with --replace. What changes the second time?

Expected output:

Schema ensured for database 'neo4j'
Schema ensured for database 'neo4j'
Pre-ingestion: ...
Ingestion complete: dataset_id=m07-survey, nodes_written=87, ...
Pre-ingestion: ...
Ingestion complete: dataset_id=m07-survey, nodes_written=87, ...
Answer
ddigraph bootstrap
ddigraph bootstrap
ddigraph load tests/fixtures/lfs_lifecycle.xml --dataset-id m07-survey --replace
ddigraph load tests/fixtures/lfs_lifecycle.xml --dataset-id m07-survey --replace
Schema ensured for database 'neo4j'
Schema ensured for database 'neo4j'
Pre-ingestion: connecting to Neo4j at ... (database 'neo4j'); credentials from ...; dry-run/validate-only is OFF; format: lifecycle
Ingestion complete: dataset_id=m07-survey, nodes_written=87, relationships_written=108, stubs=0, references=85, resolved=85, unresolved=0, conflicts=0
Pre-ingestion: connecting to Neo4j at ... (database 'neo4j'); credentials from ...; dry-run/validate-only is OFF; format: lifecycle
Ingestion complete: dataset_id=m07-survey, nodes_written=87, relationships_written=108, stubs=0, references=85, resolved=85, unresolved=0, conflicts=0

Nothing changes. The schema statements are IF NOT EXISTS, and --replace empties the dataset before each load, so the second load writes the same graph again. Both commands are safe to repeat.

Exercise 2 (O3, O5). In Neo4j Browser, list each question of m07-survey with its code list and its categories, in order. Then run the same query from Python, to check the rows.

Expected output:

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

In Browser:

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

From Python:

from neo4j import GraphDatabase

import ddigraph
from ddigraph.config import Settings

ddigraph.load("tests/fixtures/lfs_lifecycle.xml", dataset_id="m07-survey", replace=True)

query = """
MATCH (q:QuestionItem)-[:IN_DATASET]->(:Dataset {dataset_id: $dataset})
MATCH (q)-[:USES_CODELIST]->(cl:CodeList)-[c:CONTAINS*0..1]->()-[h:HAS_CATEGORY]->(cat:Category)
RETURN q.name AS question, cl.label AS code_list, cat.label AS category
ORDER BY question, coalesce(c[0].ordinal, h.ordinal)
"""
settings = Settings()
auth = (settings.neo4j_user, settings.neo4j_password.get_secret_value())
with GraphDatabase.driver(settings.neo4j_uri, auth=auth) as driver:
    records, _summary, _keys = driver.execute_query(
        query, dataset="m07-survey", database_=settings.neo4j_database
    )
for record in records:
    print(record["question"], "|", record["code_list"], "|", record["category"])
AVAIL | Yes or no | Yes
AVAIL | Yes or no | No
EDUC | Highest level of education | Primary or less (ISCED 0-1)
EDUC | Highest level of education | Lower secondary (ISCED 2)
EDUC | Highest level of education | Upper secondary (ISCED 3)
EDUC | Highest level of education | Post-secondary non-tertiary (ISCED 4)
EDUC | Highest level of education | Tertiary (ISCED 5-8)
LOOK | Yes or no | Yes
LOOK | Yes or no | No
REGION | Region | Capital region
REGION | Region | North
REGION | Region | South
REGION | Region | East
REGION | Region | West
SEX | Sex | Male
SEX | Sex | Female
WORK | Yes or no | Yes
WORK | Yes or no | No

The first MATCH keeps the query to m07-survey. The *0..1 reads the categories whether they hang off the codes or off the code list, and the coalesce of the two ordinals keeps their order, as section 4 explained. Sort by h.ordinal alone, and the categories of each list come in no set order, since each code's HAS_CATEGORY edge has the ordinal 0. AGE and HOURS are not listed: their answer is a number.

Exercise 3 (O4). From Python, list the variables of m07-codebook with the label of their universe (IN_UNIVERSE), in the file's order. Pass the dataset as a parameter. Keep the variables that have no universe.

Expected output:

SEX None
AGE None
AGEGRP None
REGION None
EDUC None
ILOSTAT None
HOURS Employed persons aged 15 and over
Answer
from neo4j import GraphDatabase

import ddigraph
from ddigraph.config import Settings

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

query = """
MATCH (v:Variable)-[:IN_DATASET]->(:Dataset {dataset_id: $dataset})
OPTIONAL MATCH (v)-[:IN_UNIVERSE]->(u:Universe)
RETURN v.name AS variable, u.label AS universe
ORDER BY v.ddi_id
"""
settings = Settings()
auth = (settings.neo4j_user, settings.neo4j_password.get_secret_value())
with GraphDatabase.driver(settings.neo4j_uri, auth=auth) as driver:
    records, _summary, _keys = driver.execute_query(
        query, dataset="m07-codebook", database_=settings.neo4j_database
    )
for record in records:
    print(record["variable"], record["universe"])
SEX None
AGE None
AGEGRP None
REGION None
EDUC None
ILOSTAT None
HOURS Employed persons aged 15 and over

A Codebook variable states a universe only where it narrows the study's, "Persons aged 15 and over living in private households". Only HOURS does: only employed people are asked about their hours. OPTIONAL MATCH keeps the other six and gives None for them. A plain MATCH would drop those rows. The ORDER BY uses ddi_id, V1 to V7, which follows the file.

Exercise 4 (O5). The next wave of the survey has the same codebook. Load tests/fixtures/lfs_codebook.xml twice, as m07-wave1 and m07-wave2. Show that each wave has its own SEX variable, then remove both waves. Finish by removing every m07- dataset, so the database is as you found it.

Expected output:

m07-wave1 urn:ddigraph:scoped:m07-wave1:V1
m07-wave2 urn:ddigraph:scoped:m07-wave2:V1
m07-wave1 removed: 80 nodes
m07-wave2 removed: 80 nodes
m07 datasets left: 0
Answer
from neo4j import GraphDatabase

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

waves = ("m07-wave1", "m07-wave2")
for wave in waves:
    ddigraph.load("tests/fixtures/lfs_codebook.xml", dataset_id=wave, replace=True)

query = """
MATCH (v:Variable {name: 'SEX'})-[:IN_DATASET]->(d:Dataset)
WHERE d.dataset_id IN $waves
RETURN d.dataset_id AS dataset, v.identity AS identity
ORDER BY dataset
"""
settings = Settings()
auth = (settings.neo4j_user, settings.neo4j_password.get_secret_value())
with GraphDatabase.driver(settings.neo4j_uri, auth=auth) as driver:
    records, _summary, _keys = driver.execute_query(
        query, waves=list(waves), database_=settings.neo4j_database
    )
    for record in records:
        print(record["dataset"], record["identity"])
    lens = Neo4jLens(driver, database=settings.neo4j_database)
    for wave in waves:
        print(wave, "removed:", lens.purge(wave), "nodes")
    for dataset in ("m07-codebook", "m07-survey"):
        lens.purge(dataset)
    records, _summary, _keys = driver.execute_query(
        "MATCH (d:Dataset) WHERE d.dataset_id STARTS WITH 'm07-' RETURN count(d) AS left",
        database_=settings.neo4j_database,
    )
print("m07 datasets left:", records[0]["left"])
m07-wave1 urn:ddigraph:scoped:m07-wave1:V1
m07-wave2 urn:ddigraph:scoped:m07-wave2:V1
m07-wave1 removed: 80 nodes
m07-wave2 removed: 80 nodes
m07 datasets left: 0

A Codebook ID, here V1, is scoped to its dataset, so the same file loaded twice gives two separate graphs. Without the IN_DATASET anchor, a query for SEX would mix both waves, and any other dataset's SEX too. Each purge removes its wave's 79 members and its Dataset node. The last purges remove the datasets of the earlier exercises.


Quiz

Question 1 (O1): What does ddigraph bootstrap create?

A. A new database called ddigraph.

B. A uniqueness constraint on each node's key, and range indexes, each IF NOT EXISTS.

C. One constraint per DDI flavor.

D. The nodes of the sample files.

Answer

B. One schema serves every flavor, and running it again changes nothing. It writes no data (D): that is what ddigraph load does.

Question 2 (O2): You delete a variable from a file, then reload it with ddigraph load and the same --dataset-id, without --replace. What happens to the deleted variable in Neo4j?

A. It disappears, because the file no longer has it.

B. It stays, because a plain reload only adds and updates.

C. The load fails.

D. It moves to a new dataset.

Answer

B. A load writes what the file holds; it does not look for what is gone. --replace empties the dataset first, so the database matches the file again.

Question 3 (O5): MATCH (v:Variable) RETURN count(v) returns 42, but your file has 7 variables. Why?

A. The load wrote each variable many times.

B. The database holds other datasets too, and the query does not start from your dataset.

C. Neo4j counts edges, not nodes.

D. count includes the indexes.

Answer

B. Start from the dataset: MATCH (v:Variable)-[:IN_DATASET]->(:Dataset {dataset_id: 'm07-codebook'}). A is tempting, but the key constraint makes a second copy of a node impossible.

Question 4 (O3): Why does the code list query use -[:CONTAINS*0..1]->() before -[:HAS_CATEGORY]->?

A. To follow every edge in the graph.

B. So that it finds the categories whether they hang off the codes (DDI 3.2 and 3.3) or off the code list (DDI 3.1).

C. Because HAS_CATEGORY edges always start at a Code.

D. To make the query faster.

Answer

B. Zero CONTAINS edges covers the DDI 3.1 shape, and one covers the shape with codes. C is wrong: in a DDI 3.1 file the edge starts at the code list.

Question 5 (O4): Why pass dataset='m07-codebook' to execute_query, rather than pasting the name into the query text?

A. The driver refuses query text that holds a string.

B. A parameter cannot change the query, the server checks its type, and the server can reuse the query's plan.

C. Parameters make the result sorted.

D. It is the only way to choose the database.

Answer

B. Values from users or files belong in parameters. A is wrong: the Browser queries above hold strings. The database is a driver option, database_ (D).

Question 6 (O2): A load reports conflicts=3. What does that mean?

A. Three nodes clash with another dataset.

B. Three elements of the file claimed a key that an earlier element already had, so ddigraph kept the first and dropped them.

C. The load failed three times and was retried.

D. Three references point at stubs.

Answer

B. The survey's files load with conflicts=0, as a clean file should. A file where two elements share an ID reports them. Stubs (D) are counted by stubs, and other datasets never cause conflicts (A).


Check yourself

  • I can create ddigraph's schema with ddigraph bootstrap and say what it creates. (O1)
  • I can load a file into its own dataset, reload it with --replace, and read the load's report. (O2)
  • I can explore a dataset in Neo4j Browser: count nodes by type, list variables, and follow a code list to its categories. (O3)
  • I can run Cypher from Python with the neo4j driver, with parameters, and read the records. (O4)
  • I can keep a query to one dataset through IN_DATASET, and remove a dataset when I am done. (O5)

Next: Module 8: Linked data: RDF out and back in