Skip to content

Module 12: Build your own pipeline and lens

Learning objectives

By the end of this module, you can:

  • O1. Write the graph stream to a target of your own in one pass, keyed by node.key, using the stream's two rules.
  • O2. Write a stream through a lens such as NetworkXLens, read it back, and say what a lens adds to a hand-written loop.
  • O3. Write a lens of your own with the four methods of the Lens protocol (ddl, write, purge, read), and check that it gives back the graph it was given.
  • O4. Read RDF that ddigraph wrote back into the same stream with read_graph, so a pipeline takes Turtle and JSON-LD as well as DDI XML.

Prerequisites: Module 11

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

Needs: No server. The networkx and rdf extras (pip install "ddigraph[networkx,rdf]"). The tabs of section 5 need the extra of each backend, and the Neo4j and PostgreSQL tabs use the servers you started in Module 2.

New in this module: ir.parse, iter_graph, GraphChunk, NetworkXLens, PandasLens, the Lens protocol, WriteResult, chunked, canonical, read_graph


1. What ships, and what you write

Before you write any code, check what ddigraph already does:

Target What ships
Neo4j ddigraph load, Neo4jLens
RDF files, SPARQL ddigraph export, RDFLens, OxigraphLens, ddigraph load out.ttl
PostgreSQL, DuckDB SQLLens
NetworkX, pandas NetworkXLens, PandasLens
JSON, CSV, Arrow files ddigraph export
Gremlin ddigraph.backends

A lens is a class that writes the graph to one store and reads it back. ddigraph ships seven: MemoryLens, Neo4jLens, RDFLens, OxigraphLens, SQLLens, NetworkXLens and PandasLens.

Any other target you write yourself: a search index, a document database, a spreadsheet, your own catalogue. You need only one thing, which you met in Module 4: the graph stream. ddigraph.ir.parse and ddigraph.iter_graph read any DDI flavor and give a stream of GraphChunks, each a list of nodes and a list of relationships.

2. One pass, thanks to two rules

Two rules of the stream make a target simple to write:

  1. Each node comes once, and node.key names it.
  2. A relationship comes after both of its ends, in its own chunk or an earlier one.

So you can write as the stream goes: each chunk's nodes, then its edges. When an edge arrives, both of its ends are already written. No second pass is needed. This module reads the sample Labour Force Survey in DDI-L, tests/fixtures/lfs_lifecycle.xml, with its questionnaire, questions, code lists and variables:

from ddigraph import ir

nodes, edges = {}, []

for chunk in ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id="lfs"):
    for node in chunk.nodes:
        nodes[node.key] = node
    for edge in chunk.relationships:
        assert edge.start in nodes and edge.end in nodes  # both ends came first
        edges.append((edge.start, edge.type, edge.end))

print(len(nodes), "nodes,", len(edges), "edges")

Expected output:

87 nodes, 108 edges

ir.parse takes the dataset_id the nodes belong to. It is optional for DDI-L and DDI-CDI, which default to the file name. A Codebook file needs it, since its IDs only mean something inside a dataset. ddigraph.iter_graph(path) does the same with the default ID.

3. Key on node.key, never on the ID

Key everything on node.key, and note that an edge's start and end are keys too. A key you build from part of the identity, such as the DDI ID alone, looks the same and is not. Two DDI-L objects can share an ID across agencies or versions.

Say a regional statistics office, with the agency ID example.rso, runs the same questionnaire. It publishes a copy of tests/fixtures/lfs_lifecycle.xml under its own agency, with the same IDs. This example reads both files, and keeps the nodes once by key and once by DDI ID:

from pathlib import Path

from ddigraph import iter_graph

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

by_key, by_id = {}, {}
for path in ("tests/fixtures/lfs_lifecycle.xml", "other_agency.xml"):
    for chunk in iter_graph(path):
        for node in chunk.nodes:
            by_key[node.key] = node
            by_id[node.properties.get("ddi_id", node.key)] = node

print(len(by_key), "nodes by key,", len(by_id), "by DDI ID")

Expected output:

174 nodes by key, 88 by DDI ID

Each file has 87 nodes: its Dataset node and 86 DDI objects. Keyed by DDI ID, the 86 objects of the national office silently became the regional office's. Only the two Dataset nodes, which have no DDI ID, stayed apart. Nothing raised an error. You would only see fewer nodes than you had, and the wrong agency on many of them.

4. A real target, by hand

Here is a NetworkX graph built from the stream, in a few lines:

import networkx as nx

from ddigraph import ir

graph = nx.DiGraph()

for chunk in ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id="lfs"):
    for node in chunk.nodes:
        graph.add_node(node.key, kind=node.label, **node.properties)
    for edge in chunk.relationships:
        graph.add_edge(edge.start, edge.end, type=edge.type)

print(graph.number_of_nodes(), "nodes,", graph.number_of_edges(), "edges")
print("acyclic:", nx.is_directed_acyclic_graph(graph))

Expected output:

87 nodes, 108 edges
acyclic: True

Note kind=, not label=. DDI records carry their own label property, so **node.properties already gives one. Passing label=node.label as well raises TypeError: got multiple values for keyword argument 'label'. And a text property, such as label, arrives as a Text, with its language. Keep it, or store its .value.

5. Write through a lens

That loop is fine for a quick look, but it skips the rules a real store needs. Which file did each node come from? What happens to a property you added when you load the file again? Is each value of the type the model says?

A lens keeps those rules for you. NetworkXLens writes the stream to a networkx.MultiDiGraph:

from ddigraph import ir
from ddigraph.lens.networkx import NetworkXLens

lens = NetworkXLens()
chunks = ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id="lfs")
result = lens.write(chunks, dataset_id="lfs")
print(result.nodes, "nodes,", result.relationships, "relationships")

question = lens.graph.nodes["bf1edd4946eed1c2ce250123ecb48b53"]  # the HOURS question
print(question["node_labels"], question["identity"], list(question["memberships"]))

labels = [node.label for chunk in lens.read(dataset_id="lfs") for node in chunk.nodes]
print(len(labels), "nodes read back, first:", labels[:5])

Expected output:

87 nodes, 108 relationships
['QuestionItem'] urn:ddi:example.nso:q-hours:1 ['lfs']
87 nodes read back, first: ['Dataset', 'Category', 'QuestionConstruct', 'Category', 'QuestionConstruct']

Three things came for free:

  • Membership. The node records each dataset that holds it, in memberships, with where it was read there.
  • Reloads. Writing the same file again changes nothing. A property you add yourself is never touched.
  • Reads. read() gives the stream back, sorted by key, with the Dataset node first.

Every lens follows the same rules, which ddigraph.lens.memory lists, so every lens gives back the same stream. Pick a backend: each tab writes the same file, as the dataset m12-lfs, and reads it back. The Neo4j and PostgreSQL tabs purge the dataset before and after:

MemoryLens needs no extra. It is the reference lens that the others are checked against:

from ddigraph import ir
from ddigraph.lens.memory import MemoryLens

lens = MemoryLens()
result = lens.write(
    ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id="m12-lfs"),
    dataset_id="m12-lfs",
)
print(result.nodes, "nodes,", result.relationships, "relationships written")
labels = [node.label for chunk in lens.read(dataset_id="m12-lfs") for node in chunk.nodes]
print(len(labels), "nodes read back, first:", labels[:5])
87 nodes, 108 relationships written
87 nodes read back, first: ['Dataset', 'Category', 'QuestionConstruct', 'Category', 'QuestionConstruct']

Needs the Neo4j server and the DDIGRAPH_NEO4J_* variables you set in Module 2. A node that another dataset holds stays when this one is purged:

import os

from neo4j import GraphDatabase

from ddigraph import ir
from ddigraph.lens.neo4j import Neo4jLens

auth = (os.environ["DDIGRAPH_NEO4J_USER"], os.environ["DDIGRAPH_NEO4J_PASSWORD"])
with GraphDatabase.driver(os.environ["DDIGRAPH_NEO4J_URI"], auth=auth) as driver:
    lens = Neo4jLens(driver)
    lens.purge("m12-lfs")
    result = lens.write(
        ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id="m12-lfs"),
        dataset_id="m12-lfs",
    )
    print(result.nodes, "nodes,", result.relationships, "relationships written")
    labels = [node.label for chunk in lens.read(dataset_id="m12-lfs") for node in chunk.nodes]
    print(len(labels), "nodes read back, first:", labels[:5])
    lens.purge("m12-lfs")
87 nodes, 108 relationships written
87 nodes read back, first: ['Dataset', 'Category', 'QuestionConstruct', 'Category', 'QuestionConstruct']

Needs the PostgreSQL server of Module 2 and the postgres extra:

import psycopg

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

with psycopg.connect(
    "postgresql://postgres:postgres@localhost:5432/postgres", autocommit=True
) as connection:
    lens = SQLLens(connection)
    lens.purge("m12-lfs")
    result = lens.write(
        ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id="m12-lfs"),
        dataset_id="m12-lfs",
    )
    print(result.nodes, "nodes,", result.relationships, "relationships written")
    labels = [node.label for chunk in lens.read(dataset_id="m12-lfs") for node in chunk.nodes]
    print(len(labels), "nodes read back, first:", labels[:5])
    lens.purge("m12-lfs")
87 nodes, 108 relationships written
87 nodes read back, first: ['Dataset', 'Category', 'QuestionConstruct', 'Category', 'QuestionConstruct']

Needs the duckdb extra. duckdb.connect() with no file name keeps the database in memory:

import duckdb

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

lens = SQLLens(duckdb.connect())
result = lens.write(
    ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id="m12-lfs"),
    dataset_id="m12-lfs",
)
print(result.nodes, "nodes,", result.relationships, "relationships written")
labels = [node.label for chunk in lens.read(dataset_id="m12-lfs") for node in chunk.nodes]
print(len(labels), "nodes read back, first:", labels[:5])
87 nodes, 108 relationships written
87 nodes read back, first: ['Dataset', 'Category', 'QuestionConstruct', 'Category', 'QuestionConstruct']

Needs the oxigraph extra. OxigraphLens() with no folder keeps the store in memory:

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

lens = OxigraphLens()
result = lens.write(
    ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id="m12-lfs"),
    dataset_id="m12-lfs",
)
print(result.nodes, "nodes,", result.relationships, "relationships written")
labels = [node.label for chunk in lens.read(dataset_id="m12-lfs") for node in chunk.nodes]
print(len(labels), "nodes read back, first:", labels[:5])
87 nodes, 108 relationships written
87 nodes read back, first: ['Dataset', 'Category', 'QuestionConstruct', 'Category', 'QuestionConstruct']

Needs the networkx extra. The graph is in lens.graph:

from ddigraph import ir
from ddigraph.lens.networkx import NetworkXLens

lens = NetworkXLens()
result = lens.write(
    ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id="m12-lfs"),
    dataset_id="m12-lfs",
)
print(result.nodes, "nodes,", result.relationships, "relationships written")
labels = [node.label for chunk in lens.read(dataset_id="m12-lfs") for node in chunk.nodes]
print(len(labels), "nodes read back, first:", labels[:5])
87 nodes, 108 relationships written
87 nodes read back, first: ['Dataset', 'Category', 'QuestionConstruct', 'Category', 'QuestionConstruct']

Needs the pandas extra. The frames are in lens.nodes, lens.memberships and lens.relationships:

from ddigraph import ir
from ddigraph.lens.pandas import PandasLens

lens = PandasLens()
result = lens.write(
    ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id="m12-lfs"),
    dataset_id="m12-lfs",
)
print(result.nodes, "nodes,", result.relationships, "relationships written")
labels = [node.label for chunk in lens.read(dataset_id="m12-lfs") for node in chunk.nodes]
print(len(labels), "nodes read back, first:", labels[:5])
87 nodes, 108 relationships written
87 nodes read back, first: ['Dataset', 'Category', 'QuestionConstruct', 'Category', 'QuestionConstruct']

The nodes come back in the same order from every store: by key, with the Dataset node first. So code that reads a lens never needs to know which lens it is.

6. A lens of your own

A lens is any class with the four methods of the ddigraph.lens.Lens protocol. A protocol is a list of methods: a class that has them is a Lens, with no base class to inherit.

  • ddl() returns the statements that prepare the store, such as constraints. An in-memory store needs none.
  • write(chunks, *, dataset_id, dry_run=False) writes a stream into a dataset, and returns a WriteResult with the counts.
  • purge(dataset_id) removes a dataset, and returns how many nodes it deleted.
  • read(*, dataset_id=None) gives the stored graph back as a stream.

Here is a small lens that keeps each dataset in two dicts. chunked, from ddigraph.lens.memory, puts nodes and relationships back into chunks in the order every lens reads them. canonical, from ddigraph.conform, gives the same value for two streams that describe the same graph, whatever their order:

from ddigraph import ir
from ddigraph.conform import canonical
from ddigraph.lens import Lens, WriteResult
from ddigraph.lens.memory import chunked


class DictLens:
    """A lens that keeps each dataset's nodes and relationships in two dicts."""

    def __init__(self):
        self.datasets = {}

    def ddl(self):
        return []  # nothing to prepare in memory

    def write(self, chunks, *, dataset_id, dry_run=False):
        nodes, edges = {}, {}
        for chunk in chunks:
            for node in chunk.nodes:
                nodes[node.key] = node
            for edge in chunk.relationships:
                if edge.start not in nodes or edge.end not in nodes:
                    raise ValueError(f"{edge.type}: an end came after its relationship")
                edges[(edge.start, edge.type, edge.end, edge.ordinal)] = edge
        if not dry_run:
            self.datasets[dataset_id] = (nodes, edges)
        return WriteResult(nodes=len(nodes), relationships=len(edges), dry_run=dry_run)

    def purge(self, dataset_id):
        nodes, _edges = self.datasets.pop(dataset_id, ({}, {}))
        return len(nodes)

    def read(self, *, dataset_id=None):
        for name in [dataset_id] if dataset_id else sorted(self.datasets):
            nodes, edges = self.datasets[name]
            yield from chunked(nodes.values(), edges.values())


lens = DictLens()
print("a Lens:", isinstance(lens, Lens))
print(lens.write(ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id="lfs"), dataset_id="lfs"))

back = canonical(lens.read(dataset_id="lfs"))
print(
    "same graph:", back == canonical(ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id="lfs"))
)
print("purged:", lens.purge("lfs"), "nodes; datasets left:", list(lens.datasets))

Expected output:

a Lens: True
WriteResult(nodes=87, relationships=108, stubs=0, dry_run=False)
same graph: True
purged: 87 nodes; datasets left: []

isinstance(lens, Lens) is true because the class has the four methods. The same graph line is the most important test of any lens: what you read back must be what you wrote. ddigraph calls it PutGet, and checks it for every lens it ships.

This lens keeps each dataset apart. A full lens does more: it shares a node that two datasets hold, keeps a property it does not own, and checks each value's type. Those are the seven rules of ddigraph.lens.memory. A lens that keeps its data in memory can reuse them: LensBase, in the same module, has the checks and the write loop, and you supply the storage. The custom adapters page covers a backend of your own in more depth.

7. Streaming, if you need it

The examples above hold the whole graph in memory. For a 65 MB file with tens of thousands of nodes, that may be fine, or it may not.

If it is not, write each chunk to your store as it comes, and keep nothing. An edge's ends are always in its chunk or an earlier one, so they are already in the store when the edge arrives. That is what Neo4jLens does: one transaction per chunk. Module 13 looks at big files.

8. RDF back in

read_graph reads RDF that ddigraph wrote back into the same stream, as in Module 8. So anything you build on the stream reads Turtle, JSON-LD, N-Triples and RDF/XML files too:

import ddigraph
from ddigraph.rdf.reader import read_graph

ddigraph.export("tests/fixtures/lfs_lifecycle.xml", "lfs.ttl", format="turtle")

labels = sorted({node.label for chunk in read_graph("lfs.ttl") for node in chunk.nodes})
print(labels)

Expected output:

['Category', 'Code', 'CodeList', 'Concept', 'Dataset', 'IfThenElse', 'Instrument', 'QuestionConstruct', 'QuestionItem', 'Sequence', 'Universe', 'Variable']

The same labels the XML gave, back out of RDF. That is the two-type trick of Module 8 at work: without the ddigraph: type, this would return Question where the file said QuestionItem.

read_graph reads one dataset at a time. A file that holds several needs dataset_id=. RDF that ddigraph did not write raises ValueError, rather than giving a half-read graph.


Exercises

Scenario

Your team wants a small catalogue of what each DDI file holds, and keeps a copy of each graph on disk. The files come as DDI XML from some partners, and as Turtle or JSON-LD exports from others.

Exercise 1 (O1). Write a one-pass pipeline that reports, for each node type, which relationship types it takes part in, going out (-TYPE->) or coming in (<-TYPE-). Run it on the survey's three files, tests/fixtures/lfs_lifecycle.xml, tests/fixtures/lfs_codebook.xml and tests/fixtures/lfs_cdi.xml, and print the first four types of each file, sorted.

Expected output:

--- tests/fixtures/lfs_lifecycle.xml
  Category: <-HAS_CATEGORY-
  Code: -HAS_CATEGORY->, <-CONTAINS-
  CodeList: -CONTAINS->, <-USES_CODELIST-
  Concept: <-USES_CONCEPT-
--- tests/fixtures/lfs_codebook.xml
  Category: <-USES_CATEGORY-
  Citation: -DESCRIBES->
  Concept: <-USES_CONCEPT-
  Contributor: -CONTRIBUTES_TO->
--- tests/fixtures/lfs_cdi.xml
  CDICategory: <-DENOTES-
  CDICode: -DENOTES->, -USES->, <-HAS_CODE-
  CDICodeList: -HAS_CODE->, -IS_DEFINED_BY->, <-TAKES_VALUES_FROM-
  CDIConcept: <-HAS_CONCEPT-, <-IS_DEFINED_BY-
Answer
import collections

from ddigraph import iter_graph

for path in (
    "tests/fixtures/lfs_lifecycle.xml",
    "tests/fixtures/lfs_codebook.xml",
    "tests/fixtures/lfs_cdi.xml",
):
    labels = {}
    shapes = collections.defaultdict(set)
    for chunk in iter_graph(path):
        for node in chunk.nodes:
            labels[node.key] = node.label
        for edge in chunk.relationships:
            shapes[labels[edge.start]].add(f"-{edge.type}->")
            shapes[labels[edge.end]].add(f"<-{edge.type}-")

    print(f"--- {path}")
    for label in sorted(shapes)[:4]:
        print(f"  {label}: {', '.join(sorted(shapes[label]))}")
--- tests/fixtures/lfs_lifecycle.xml
  Category: <-HAS_CATEGORY-
  Code: -HAS_CATEGORY->, <-CONTAINS-
  CodeList: -CONTAINS->, <-USES_CODELIST-
  Concept: <-USES_CONCEPT-
--- tests/fixtures/lfs_codebook.xml
  Category: <-USES_CATEGORY-
  Citation: -DESCRIBES->
  Concept: <-USES_CONCEPT-
  Contributor: -CONTRIBUTES_TO->
--- tests/fixtures/lfs_cdi.xml
  CDICategory: <-DENOTES-
  CDICode: -DENOTES->, -USES->, <-HAS_CODE-
  CDICodeList: -HAS_CODE->, -IS_DEFINED_BY->, <-TAKES_VALUES_FROM-
  CDIConcept: <-HAS_CONCEPT-, <-IS_DEFINED_BY-

One loop, three flavors, no branching on which is which. The label of an edge's end is always known when the edge arrives, because of rule 2. iter_graph gives the Codebook file its default dataset ID.

Exercise 2 (O2). The survey used the same questionnaire in the third and the fourth quarter of 2025. Write tests/fixtures/lfs_lifecycle.xml twice to one NetworkXLens, as the datasets lfs-2025q3 and lfs-2025q4. After each write, print how many nodes were written and how many the graph holds. Then print the datasets that hold the HOURS question (key bf1edd4946eed1c2ce250123ecb48b53), purge lfs-2025q4, and print the counts and the question's datasets again.

Expected output:

lfs-2025q3 87 nodes written; 87 in the graph
lfs-2025q4 87 nodes written; 88 in the graph
question in: ['lfs-2025q3', 'lfs-2025q4']
purged: 1 node
87 nodes; question in: ['lfs-2025q3']
Answer
from ddigraph import ir
from ddigraph.lens.networkx import NetworkXLens

lens = NetworkXLens()
for quarter in ("lfs-2025q3", "lfs-2025q4"):
    result = lens.write(
        ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id=quarter), dataset_id=quarter
    )
    print(quarter, result.nodes, "nodes written;", lens.graph.number_of_nodes(), "in the graph")

question = lens.graph.nodes["bf1edd4946eed1c2ce250123ecb48b53"]
print("question in:", sorted(question["memberships"]))
print("purged:", lens.purge("lfs-2025q4"), "node")
print(lens.graph.number_of_nodes(), "nodes;", "question in:", sorted(question["memberships"]))
lfs-2025q3 87 nodes written; 87 in the graph
lfs-2025q4 87 nodes written; 88 in the graph
question in: ['lfs-2025q3', 'lfs-2025q4']
purged: 1 node
87 nodes; question in: ['lfs-2025q3']

The 86 DDI objects have the same keys in both quarters, so the lens keeps one of each, held by both datasets. Only the Dataset node is new. A purge deletes only what no other dataset holds: here, the lfs-2025q4 Dataset node. That is the lens rule called isolation.

Exercise 3 (O3). Write a lens, JsonLinesLens(folder), that keeps each dataset in a file <folder>/<dataset>.jsonl, one JSON line per node or relationship. Use msgspec.json.encode to write an IR Node or Relationship, and msgspec.json.decode(line, type=Node) to read one back. Check that it is a Lens, write the survey's DDI-CDI file, tests/fixtures/lfs_cdi.xml, as the dataset lfs-cdi, list the folder, check PutGet with canonical, and purge.

Expected output:

a Lens: True
WriteResult(nodes=91, relationships=92, stubs=0, dry_run=False)
['lfs-cdi.jsonl']
same graph: True
purged: 91 nodes
Answer
from pathlib import Path

import msgspec

from ddigraph import ir
from ddigraph.conform import canonical
from ddigraph.ir.model import Node, Relationship
from ddigraph.lens import Lens, WriteResult
from ddigraph.lens.memory import chunked


class JsonLinesLens:
    """Each dataset in a file of its own, with one JSON line per node or relationship."""

    def __init__(self, folder):
        self.folder = Path(folder)
        self.folder.mkdir(exist_ok=True)

    def ddl(self):
        return []

    def write(self, chunks, *, dataset_id, dry_run=False):
        result = WriteResult(dry_run=dry_run)
        lines = []
        for chunk in chunks:
            for node in chunk.nodes:
                lines.append(b"N" + msgspec.json.encode(node))
                result.nodes += 1
            for edge in chunk.relationships:
                lines.append(b"R" + msgspec.json.encode(edge))
                result.relationships += 1
        if not dry_run:
            (self.folder / f"{dataset_id}.jsonl").write_bytes(b"\n".join(lines) + b"\n")
        return result

    def purge(self, dataset_id):
        path = self.folder / f"{dataset_id}.jsonl"
        if not path.exists():
            return 0
        count = sum(line.startswith(b"N") for line in path.read_bytes().splitlines())
        path.unlink()
        return count

    def read(self, *, dataset_id=None):
        names = (
            [dataset_id]
            if dataset_id
            else sorted(path.stem for path in self.folder.glob("*.jsonl"))
        )
        for name in names:
            nodes, edges = [], []
            for line in (self.folder / f"{name}.jsonl").read_bytes().splitlines():
                if line.startswith(b"N"):
                    nodes.append(msgspec.json.decode(line[1:], type=Node))
                else:
                    edges.append(msgspec.json.decode(line[1:], type=Relationship))
            yield from chunked(nodes, edges)


lens = JsonLinesLens("graphs")
print("a Lens:", isinstance(lens, Lens))
print(
    lens.write(ir.parse("tests/fixtures/lfs_cdi.xml", dataset_id="lfs-cdi"), dataset_id="lfs-cdi")
)
print(sorted(path.name for path in Path("graphs").iterdir()))
same = canonical(lens.read(dataset_id="lfs-cdi")) == canonical(
    ir.parse("tests/fixtures/lfs_cdi.xml", dataset_id="lfs-cdi")
)
print("same graph:", same)
print("purged:", lens.purge("lfs-cdi"), "nodes")
a Lens: True
WriteResult(nodes=91, relationships=92, stubs=0, dry_run=False)
['lfs-cdi.jsonl']
same graph: True
purged: 91 nodes

The IR types are msgspec structs, so they encode and decode with no code of your own, and the identity, the provenance and each Text survive. Each line starts with N or R, so read knows which type to decode. A file per dataset makes purge one unlink.

Exercise 4 (O4). Write a function graph(path) that reads a file with read_graph when its extension is .ttl, .jsonld, .nt or .rdf, and with iter_graph otherwise. Export the survey's DDI-L file, tests/fixtures/lfs_lifecycle.xml, as lfs.jsonld, and its DDI-CDI file, tests/fixtures/lfs_cdi.xml, as lfs_cdi.ttl. Then count the nodes and relationships of the DDI-L file, of lfs.jsonld and of lfs_cdi.ttl.

Expected output:

tests/fixtures/lfs_lifecycle.xml: 87 nodes, 108 relationships
lfs.jsonld: 87 nodes, 108 relationships
lfs_cdi.ttl: 91 nodes, 92 relationships
Answer
from pathlib import Path

import ddigraph
from ddigraph import iter_graph
from ddigraph.rdf.reader import read_graph

RDF = {".ttl", ".jsonld", ".nt", ".rdf"}


def graph(path):
    """Read a DDI file, or an RDF file that ddigraph wrote, as the graph stream."""
    return read_graph(path) if Path(path).suffix in RDF else iter_graph(path)


ddigraph.export("tests/fixtures/lfs_lifecycle.xml", "lfs.jsonld", format="jsonld")
ddigraph.export("tests/fixtures/lfs_cdi.xml", "lfs_cdi.ttl", format="turtle")
for path in ("tests/fixtures/lfs_lifecycle.xml", "lfs.jsonld", "lfs_cdi.ttl"):
    nodes = relationships = 0
    for chunk in graph(path):
        nodes += len(chunk.nodes)
        relationships += len(chunk.relationships)
    print(f"{path}: {nodes} nodes, {relationships} relationships")
tests/fixtures/lfs_lifecycle.xml: 87 nodes, 108 relationships
lfs.jsonld: 87 nodes, 108 relationships
lfs_cdi.ttl: 91 nodes, 92 relationships

Both readers give the same kind of stream, so the rest of the pipeline never knows where the graph came from. The JSON-LD file gives back the graph of the XML it came from. read_graph accepts both RDF files because ddigraph wrote them.


Quiz

Question 1 (O1): Why can a target write each chunk's edges right after its nodes, with no second pass?

A. Because the stream sorts edges by type.

B. Because a relationship always comes after both of its ends, in its own chunk or an earlier one.

C. Because each chunk holds a whole DDI fragment.

D. Because a target can create a missing end on the fly.

Answer

B. That is rule 2 of the stream. D is how some databases behave, which makes it tempting, but it would create empty nodes and hide real errors. C is false: a chunk holds a number of nodes, not a fragment.

Question 2 (O1): A pipeline keys nodes on node.properties['ddi_id']. It loads two agencies' files and finds fewer nodes than expected, with no error. Why?

A. Some nodes have no ddi_id.

B. Two agencies' objects can share an ID, so one silently replaced the other; node.key is unique to the whole identity.

C. The files were read with the wrong flavor.

D. The stream drops duplicate nodes across files.

Answer

B. An ID is unique only with its agency and version. A is true of the Dataset node, which is why it is tempting, but it would raise a KeyError, not lose nodes quietly. Always key on node.key.

Question 3 (O2): You write the same file twice through a lens, under the same dataset ID. What changes the second time?

A. Every node is duplicated.

B. Nothing: the lens writes each node by its key, and a property you added yourself is kept.

C. The lens raises an error, since the nodes exist.

D. The old dataset is purged first.

Answer

B. A lens writes nodes by key, so a reload changes nothing. D is what ddigraph load --replace does on purpose, which is why it is tempting, but a lens's write never purges.

Question 4 (O3): Which of these makes a class a ddigraph.lens.Lens?

A. Inheriting from ddigraph.lens.Lens.

B. Having the methods ddl, write, purge and read.

C. Registering the class with ddigraph.lens.register.

D. Having a graph attribute.

Answer

B. Lens is a protocol: a class with those four methods is one, and isinstance checks the methods. A is how many libraries work, hence the temptation, but no base class is needed. There is no register function.

Question 5 (O3): Your lens passes isinstance(lens, Lens). What is the most important test still to run?

A. That ddl() returns a list.

B. PutGet: canonical(lens.read(dataset_id=...)) equals canonical of the stream you wrote.

C. That write is fast.

D. That purge returns 0 for an unknown dataset.

Answer

B. isinstance checks only that the methods exist, not what they do. A lens that loses a property or an edge still passes it. The PutGet test catches that, whatever the order the lens reads in.

Question 6 (O4): You give read_graph a Turtle export that holds two datasets. What must you add?

A. format="turtle".

B. dataset_id=, to say which dataset to read.

C. Nothing: it reads both, one after the other.

D. A SPARQL query to split them.

Answer

B. read_graph reads one dataset at a time. ddigraph.rdf.reader.datasets(graph) lists the ones an rdflib graph holds. A is not needed: the format comes from the extension. C is tempting, but a stream holds one dataset.


Check yourself

  • I can write the graph stream to a target of my own in one pass, keyed by node.key. (O1)
  • I can write a stream through a lens such as NetworkXLens, read it back, and say what a lens adds to a hand-written loop. (O2)
  • I can write a lens of my own with the four methods of the Lens protocol, and check that it gives back the graph it was given. (O3)
  • I can read RDF that ddigraph wrote back into the same stream with read_graph. (O4)

Next: Module 13: Big, broken and untrusted files