Skip to content

Module 5: Ask the graph questions in memory

Learning objectives

By the end of this module, you can:

  • O1. Load a DDI file into a MemoryLens, and say what a lens is.
  • O2. Write a Query from node, edge and prop patterns, and read its rows with evaluate or run.
  • O3. Narrow and sort the rows with compare, missing, asc, desc and limit.
  • O4. Count nodes or edges with count(), one type at a time.
  • O5. Find each code list's categories, whether they hang off the codes or off the code list.

Prerequisites: Module 4

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

Needs: No server.

New in this module: ddigraph.lens.memory.MemoryLens, ddigraph.query: Query, node, edge, prop, key, compare, missing, exists, not_, asc, desc, count, evaluate, run


1. Load a file into memory

In Module 4 you walked the stream by hand. That works, but every question needs a new loop. A query states the question and lets ddigraph walk the graph.

First, the graph needs a home. In ddigraph, a place that stores the graph is a lens. Neo4j, an RDF graph and a SQL database each have one. The simplest is MemoryLens, which keeps the graph in Python, with no server and no extra:

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

lens = MemoryLens()
chunks = ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="codebook")
print(lens.write(chunks, dataset_id="codebook"))

Expected output:

WriteResult(nodes=80, relationships=48, stubs=0, dry_run=False)

This is the Labour Force Survey's codebook. lens.write takes the stream and the dataset to file it under. It returns what it wrote: the 80 nodes and 48 edges the preview counted in Module 3. A lens can hold several datasets; each node remembers the ones it belongs to.

MemoryLens is also the reference lens. The query you write below runs unchanged on Neo4j, RDF and SQL, and every engine must give the same rows as this one. Module 10 shows that.


2. Your first query

List the survey's variables, with their labels:

from ddigraph import ir
from ddigraph.lens.memory import MemoryLens
from ddigraph.query import Query, asc, evaluate, node, prop

lens = MemoryLens()
lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="codebook"), dataset_id="codebook"
)

query = Query(
    match=[node("v", "Variable")],
    returns=[prop("v", "name"), prop("v", "label")],
    order_by=[asc(prop("v", "name"))],
)
for name, label in evaluate(query, lens):
    print(name, label.value)

Expected output:

Text(value='AGE', lang=None) Age in completed years
Text(value='AGEGRP', lang=None) Age group
Text(value='EDUC', lang=None) Highest level of education
Text(value='HOURS', lang=None) Usual weekly hours in the main job
Text(value='ILOSTAT', lang=None) Labour force status (ILO)
Text(value='REGION', lang=None) Region of residence
Text(value='SEX', lang=None) Sex of the person

A Query has three main parts:

  • match lists the patterns to find. node("v", "Variable") binds the name v to every node whose type is Variable.
  • returns lists what to give back for each match. prop("v", "label") is the label property of the node bound to v.
  • order_by sorts the rows. asc sorts from smallest to largest.

evaluate(query, lens) runs the query and returns a list of rows. Each row is a tuple, with one value per returned term. A text property comes back as a Text, as in Module 4, so the code prints label.value. A name is a plain string, so it prints as it is.


3. Follow edges: which questions feed a variable?

An edge pattern joins two bound names. In the survey's DDI-L file, a variable points at each question it comes from with REFERENCES_QUESTION. Ask which questions feed each variable:

from ddigraph import ir
from ddigraph.lens.memory import MemoryLens
from ddigraph.query import Query, asc, edge, node, prop, run

lens = MemoryLens()
lens.write(ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id="survey"), dataset_id="survey")

query = Query(
    match=[node("v", "Variable"), node("q", "QuestionItem"), edge("v", "REFERENCES_QUESTION", "q")],
    returns=[prop("v", "name"), prop("q", "name")],
    order_by=[asc(prop("v", "name")), asc(prop("q", "name"))],
)
for variable, question in run(query, lens):
    print(variable, "<-", question)

Expected output:

Text(value='AGE', lang='en') <- Text(value='AGE', lang='en')
Text(value='AGEGRP', lang='en') <- Text(value='AGE', lang='en')
Text(value='EDUC', lang='en') <- Text(value='EDUC', lang='en')
Text(value='HOURS', lang='en') <- Text(value='HOURS', lang='en')
Text(value='ILOSTAT', lang='en') <- Text(value='AVAIL', lang='en')
Text(value='ILOSTAT', lang='en') <- Text(value='LOOK', lang='en')
Text(value='ILOSTAT', lang='en') <- Text(value='WORK', lang='en')
Text(value='REGION', lang='en') <- Text(value='REGION', lang='en')
Text(value='SEX', lang='en') <- Text(value='SEX', lang='en')
  • edge("v", "REFERENCES_QUESTION", "q") matches a REFERENCES_QUESTION edge from v to q. The direction matters: the edge starts at the variable, as the preview's (Variable)-[:REFERENCES_QUESTION]->(QuestionItem) showed. Turn it round and the query finds nothing.
  • Each name must be bound by a node pattern before an edge uses it.
  • run(query, lens) does the same as evaluate on a memory lens. Given a Neo4j driver instead, it writes the query as Cypher and runs it there.

Most variables come from the question of the same name. Two do not, as no one is asked them. AGEGRP is grouped from the answer to AGE. ILOSTAT, the labour force status, is derived from three answers: did the person work last week (WORK), look for work (LOOK), and could they start (AVAIL)? The graph keeps that trail.

The Codebook file cannot say as much. There a variable points only at the question it was asked as, with ASKED_AS, so AGEGRP and ILOSTAT have no question at all. A query answers from the graph, so what the file put in the graph is what you check first.


4. The same graph, other tools

The graph is the same whichever tool holds it. Here is one question, "which concept does each variable use?", asked three ways. Pick a tab: Memory is the query of this module. NetworkX and pandas turn the same stream into a NetworkX graph or into tables, and walk them by hand. They need the networkx and pandas extras, which ddigraph[all] holds.

from ddigraph import ir
from ddigraph.lens.memory import MemoryLens
from ddigraph.query import Query, asc, edge, evaluate, node, prop

lens = MemoryLens()
chunks = ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m05-codebook")
lens.write(chunks, dataset_id="m05-codebook")

query = Query(
    match=[node("v", "Variable"), node("c", "Concept"), edge("v", "USES_CONCEPT", "c")],
    returns=[prop("v", "name"), prop("c", "label")],
    order_by=[asc(prop("v", "name")), asc(prop("c", "label"))],
)
for variable, concept in evaluate(query, lens):
    print(variable, "->", concept.value)
Text(value='AGE', lang=None) -> Demographic characteristics
Text(value='AGEGRP', lang=None) -> Demographic characteristics
Text(value='EDUC', lang=None) -> Educational attainment
Text(value='HOURS', lang=None) -> Working time
Text(value='ILOSTAT', lang=None) -> Labour market status
Text(value='REGION', lang=None) -> Place of residence
Text(value='SEX', lang=None) -> Demographic characteristics
from ddigraph.backends.networkx import to_networkx

G = to_networkx("tests/fixtures/lfs_codebook.xml", dataset_id="m05-codebook")
pairs = []
for start, end, (edge_type, _ordinal) in G.edges(keys=True):
    if edge_type == "USES_CONCEPT" and "Variable" in G.nodes[start]["node_labels"]:
        pairs.append((G.nodes[start]["name"], G.nodes[end]["label"]))
for variable, concept in sorted(pairs):
    print(variable, "->", concept)
AGE -> Demographic characteristics
AGEGRP -> Demographic characteristics
EDUC -> Educational attainment
HOURS -> Working time
ILOSTAT -> Labour market status
REGION -> Place of residence
SEX -> Demographic characteristics

Each node is keyed by its key, and its types are in node_labels. An edge's key in the graph is its type and its ordinal. A text property is a plain string here, with its language in label_lang.

from ddigraph.backends.pandas import to_dataframes

frames = to_dataframes("tests/fixtures/lfs_codebook.xml", dataset_id="m05-codebook")
variables = frames.of("Variable")[["key", "name"]]
concepts = frames.of("Concept")[["key", "label"]]
uses = frames.relationships[frames.relationships["type"] == "USES_CONCEPT"]
pairs = uses.merge(variables, left_on="start", right_on="key").merge(
    concepts, left_on="end", right_on="key", suffixes=("_variable", "_concept")
)
for row in pairs.sort_values("name").itertuples():
    print(row.name, "->", row.label)
AGE -> Demographic characteristics
AGEGRP -> Demographic characteristics
EDUC -> Educational attainment
HOURS -> Working time
ILOSTAT -> Labour market status
REGION -> Place of residence
SEX -> Demographic characteristics

frames.of(label) gives one table per type. An edge is a row of frames.relationships, and each join brings in one of its ends by key.

All three print the same lines, because all three read the same stream. The query states what you want; the other two say how to walk to it. Three variables measure "Demographic characteristics": SEX, AGE and AGEGRP. Section 6 counts how often the file writes that concept. Module 18 and Module 19 cover those tools in depth.


5. Narrow, sort and limit

A where filter keeps only the rows that pass it. Which variables have no question text? Which ones measure demographic characteristics? And which are the two highest levels of education?

from ddigraph import ir
from ddigraph.lens.memory import MemoryLens
from ddigraph.query import Query, asc, compare, desc, edge, evaluate, missing, node, prop

lens = MemoryLens()
lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="codebook"), dataset_id="codebook"
)

no_text = Query(
    match=[node("v", "Variable")],
    where=missing(prop("v", "question_text")),
    returns=[prop("v", "name")],
    order_by=[asc(prop("v", "name"))],
)
print("No question text:", evaluate(no_text, lens))

demographic = Query(
    match=[node("v", "Variable"), node("c", "Concept"), edge("v", "USES_CONCEPT", "c")],
    where=compare(prop("c", "label"), "==", "Demographic characteristics"),
    returns=[prop("v", "name")],
    order_by=[asc(prop("v", "name"))],
)
print("Demographic:", evaluate(demographic, lens))

top_two = Query(
    match=[node("v", "Variable"), node("c", "Category"), edge("v", "USES_CATEGORY", "c")],
    where=compare(prop("v", "name"), "==", "EDUC"),
    returns=[prop("c", "code"), prop("c", "name")],
    order_by=[desc(prop("c", "code")), asc(prop("c", "name"))],
    limit=2,
)
print("Top two:", evaluate(top_two, lens))

Expected output:

No question text: [(Text(value='AGEGRP', lang=None),), (Text(value='ILOSTAT', lang=None),)]
Demographic: [(Text(value='AGE', lang=None),), (Text(value='AGEGRP', lang=None),), (Text(value='SEX', lang=None),)]
Top two: [('5', Text(value='Tertiary (ISCED 5-8)', lang=None)), ('4', Text(value='Post-secondary non-tertiary (ISCED 4)', lang=None))]
  • missing(prop(...)) keeps the nodes that lack the property. AGEGRP and ILOSTAT have no question text because they are derived, not asked. exists is the opposite of missing.
  • compare(term, op, value) compares a property with a value, using ==, !=, <, <=, > or >=. A text property compares by its string.
  • desc sorts from largest to smallest. limit=2 keeps the first two rows. A limit needs an order_by over every returned term, so that every engine keeps the same rows.
  • A Codebook category keeps its value in code, as text. So the codes sort as text: "10" would come before "9". Here each code has one digit.

One rule surprises people: a filter on a missing value is unknown, as in SQL, and an unknown row is dropped. So not_(compare(prop("v", "question_text"), "==", "What is your sex?")) does not find AGEGRP and ILOSTAT, which have no question text at all. Use missing for those. Queries across engines lists every rule.


6. Count

count() returns the number of rows a match gives. It is returned alone: a query has no "group by". To count by type, run one query per type:

from ddigraph import ir
from ddigraph.lens.memory import MemoryLens
from ddigraph.query import Query, count, edge, evaluate, node, prop

lens = MemoryLens()
lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="codebook"), dataset_id="codebook"
)

for label in ("Variable", "Question", "Category", "Concept", "Universe"):
    [(total,)] = evaluate(Query(match=[node("n", label)], returns=[count()]), lens)
    print(f"{label:8} {total}")

uses_concept = Query(
    match=[node("v", "Variable"), node("c", "Concept"), edge("v", "USES_CONCEPT", "c")],
    returns=[count()],
)
print("USES_CONCEPT edges:", evaluate(uses_concept, lens))

concepts = Query(match=[node("c", "Concept")], returns=[prop("c", "label")], distinct=True)
print("Different concepts:", len(evaluate(concepts, lens)))

Expected output:

Variable 7
Question 5
Category 21
Concept  7
Universe 2
USES_CONCEPT edges: [(7,)]
Different concepts: 5

A count query gives one row with one value, so [(total,)] = ... unpacks it. With an edge pattern, each matching edge is one row, so the count is the number of edges. The rows are a multiset: two edges between the same two nodes give two rows. distinct=True on the Query drops the repeats.

Read the counts as an analyst would:

  • 5 questions for 7 variables. AGEGRP and ILOSTAT are derived, so no one is asked them.
  • 21 categories. They are the categories of the five coded variables: 2 for SEX, 6 for AGEGRP, 5 for REGION, 5 for EDUC and 3 for ILOSTAT. AGE and HOURS are numbers, with no categories.
  • 7 concepts, but 5 different ones. A Codebook file writes the concept again inside each variable, so "Demographic characteristics" is there three times, for SEX, AGE and AGEGRP. DDI-L, as you will see, defines a concept once and points at it.
  • 2 universes. The study's, "Persons aged 15 and over living in private households", and the narrower one of HOURS, "Employed persons aged 15 and over". Only employed people are asked about their hours.

7. Which code lists hold the most categories?

A code list's categories hang off it in one of two ways, as Module 4 said:

  • In DDI 3.1, a code has no ID. Its category hangs off the code list: (CodeList)-[:HAS_CATEGORY]->(Category).
  • In DDI 3.2 and 3.3, each code has an ID, so it is a node: (CodeList)-[:CONTAINS]->(Code)-[:HAS_CATEGORY]->(Category).

A tool that asks only one way misses the other files. The survey file lfs_lifecycle.xml is DDI 3.3, of the second kind. The code below writes a small file of the first kind: the code list of a question the survey could add for employed people, "Status in employment", saved by a tool that gives its codes no ID. It loads both files, asks both ways, and adds up the rows:

from collections import Counter
from pathlib import Path

from ddigraph import ir
from ddigraph.lens.memory import MemoryLens
from ddigraph.query import Query, edge, evaluate, key, node, prop

# A code list whose codes have no ID, as in DDI 3.1: each category hangs off the list.
Path("status.xml").write_text("""<FragmentInstance xmlns="ddi:instance:3_3"
    xmlns:r="ddi:reusable:3_3" xmlns:l="ddi:logicalproduct:3_3">
  <Fragment><l:CodeList><r:URN>urn:ddi:example.nso:cl-status:1</r:URN>
    <r:Label><r:Content>Status in employment</r:Content></r:Label>
    <l:Code><r:CategoryReference><r:URN>urn:ddi:example.nso:cat-employee:1</r:URN>
      <r:TypeOfObject>Category</r:TypeOfObject></r:CategoryReference><r:Value>1</r:Value></l:Code>
    <l:Code><r:CategoryReference><r:URN>urn:ddi:example.nso:cat-employer:1</r:URN>
      <r:TypeOfObject>Category</r:TypeOfObject></r:CategoryReference><r:Value>2</r:Value></l:Code>
    <l:Code><r:CategoryReference><r:URN>urn:ddi:example.nso:cat-own-account:1</r:URN>
      <r:TypeOfObject>Category</r:TypeOfObject></r:CategoryReference><r:Value>3</r:Value></l:Code>
    <l:Code><r:CategoryReference><r:URN>urn:ddi:example.nso:cat-family-worker:1</r:URN>
      <r:TypeOfObject>Category</r:TypeOfObject></r:CategoryReference><r:Value>4</r:Value></l:Code>
  </l:CodeList></Fragment>
  <Fragment><l:Category><r:URN>urn:ddi:example.nso:cat-employee:1</r:URN>
    <r:Label><r:Content>Employee</r:Content></r:Label></l:Category></Fragment>
  <Fragment><l:Category><r:URN>urn:ddi:example.nso:cat-employer:1</r:URN>
    <r:Label><r:Content>Employer</r:Content></r:Label></l:Category></Fragment>
  <Fragment><l:Category><r:URN>urn:ddi:example.nso:cat-own-account:1</r:URN>
    <r:Label><r:Content>Own-account worker</r:Content></r:Label></l:Category></Fragment>
  <Fragment><l:Category><r:URN>urn:ddi:example.nso:cat-family-worker:1</r:URN>
    <r:Label><r:Content>Contributing family worker</r:Content></r:Label></l:Category></Fragment>
</FragmentInstance>""")

lens = MemoryLens()
for path, dataset in [("tests/fixtures/lfs_lifecycle.xml", "survey"), ("status.xml", "status")]:
    lens.write(ir.parse(path, dataset_id=dataset), dataset_id=dataset)

# DDI 3.1: a code has no ID, so its category hangs off the code list.
direct = Query(
    match=[node("l", "CodeList"), node("c", "Category"), edge("l", "HAS_CATEGORY", "c")],
    returns=[prop("l", "label"), key("c")],
)
# DDI 3.2 and 3.3: the code list contains codes, and each code has a category.
through_codes = Query(
    match=[
        node("l", "CodeList"),
        node("x", "Code"),
        node("c", "Category"),
        edge("l", "CONTAINS", "x"),
        edge("x", "HAS_CATEGORY", "c"),
    ],
    returns=[prop("l", "label"), key("c")],
)
rows = evaluate(direct, lens) + evaluate(through_codes, lens)
sizes = Counter(label.value for label, _category in rows)
for label, size in sorted(sizes.items(), key=lambda item: (-item[1], item[0])):
    print(f"{label}: {size}")

Expected output:

Age group: 6
Highest level of education: 5
Region: 5
Status in employment: 4
Labour force status (ILO): 3
Sex: 2
Yes or no: 2

Each query returns one row per category, with the code list's label and the category's key. collections.Counter then counts the rows of each code list. The sort puts the largest first, and breaks a tie by name.

"Yes or no" counts 2, not 6: three questions use it, but it is one list with two categories. Run only direct, and only "Status in employment" is left: the survey's six lists hang their categories off their codes. Run only through_codes, and "Status in employment" disappears. Cypher can say "zero or one CONTAINS edge" in one pattern, (cl:CodeList)-[:CONTAINS*0..1]->()-[:HAS_CATEGORY]->(cat), as you will see in Module 7. ddigraph.query keeps to what every engine can run, so it asks the two shapes in turn.


8. A query is checked when you build it

A query names types, edge types and properties. ddigraph checks every name against its model as soon as you build the Query, before it reads any data. A typing slip fails at once, with a hint:

from ddigraph.query import Query, count, key, node, prop

attempts = [
    lambda: Query(match=[node("q", "QuestionItm")], returns=[key("q")]),
    lambda: Query(match=[node("q", "QuestionItem")], returns=[prop("q", "questin_text")]),
    lambda: Query(match=[node("n", "Variable")], returns=[prop("n", "label"), count()]),
]
for attempt in attempts:
    try:
        attempt()
    except ValueError as error:
        print(error)

Expected output:

Unknown label 'QuestionItm'; did you mean 'QuestionItem'?
q:QuestionItem has no property 'questin_text'; did you mean 'question_text'?
count(*) is returned alone

In a hand-written loop, the same slip would return nothing, with no error. Here it cannot reach the data.


Exercises

Scenario

A methodologist on the Labour Force Survey asks you four questions about its DDI files: which code list each question uses, which variables a filter loses, how many codes and categories the DDI-CDI file holds, and which code lists are the largest. You have no database yet, so you answer in memory.

Exercise 1 (O1, O2). Load tests/fixtures/lfs_lifecycle.xml into a MemoryLens as the dataset survey. For each question item, print its name, its question text and the label of the code list it uses (USES_CODELIST), sorted by name.

Expected output:

Text(value='AVAIL', lang='en') | If you found a job, could you start within the next two weeks? | Yes or no
Text(value='EDUC', lang='en') | What is the highest level of education you have completed? | Highest level of education
Text(value='LOOK', lang='en') | In the last four weeks, did you look for work? | Yes or no
Text(value='REGION', lang='en') | In which region do you live? | Region
Text(value='SEX', lang='en') | What is your sex? | Sex
Text(value='WORK', lang='en') | Last week, did you do any work for pay or profit, even for one hour? | Yes or no
Answer
from ddigraph import ir
from ddigraph.lens.memory import MemoryLens
from ddigraph.query import Query, asc, edge, node, prop, run

lens = MemoryLens()
lens.write(ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id="survey"), dataset_id="survey")

query = Query(
    match=[node("q", "QuestionItem"), node("l", "CodeList"), edge("q", "USES_CODELIST", "l")],
    returns=[prop("q", "name"), prop("q", "question_text"), prop("l", "label")],
    order_by=[asc(prop("q", "name"))],
)
for name, text, code_list in run(query, lens):
    print(name, "|", text.value, "|", code_list.value)
Text(value='AVAIL', lang='en') | If you found a job, could you start within the next two weeks? | Yes or no
Text(value='EDUC', lang='en') | What is the highest level of education you have completed? | Highest level of education
Text(value='LOOK', lang='en') | In the last four weeks, did you look for work? | Yes or no
Text(value='REGION', lang='en') | In which region do you live? | Region
Text(value='SEX', lang='en') | What is your sex? | Sex
Text(value='WORK', lang='en') | Last week, did you do any work for pay or profit, even for one hour? | Yes or no

name is a plain string, so it prints as it is. question_text and label are texts, so the code prints their .value. AGE and HOURS are missing: their answer is a number, not a code. Three questions share the list "Yes or no". DDI-L defines it once, and each question points at it.

Exercise 2 (O3). In tests/fixtures/lfs_codebook.xml, a colleague lists every variable but SEX with the filter "question text is not 'What is your sex?'". Run that filter, with the names sorted. Then list the variables that have no question text. Which variables did the first filter lose, and why?

Expected output:

not SEX: [Text(value='AGE', lang=None), Text(value='EDUC', lang=None), Text(value='HOURS', lang=None), Text(value='REGION', lang=None)]
no question text: [Text(value='AGEGRP', lang=None), Text(value='ILOSTAT', lang=None)]
Answer
from ddigraph import ir
from ddigraph.lens.memory import MemoryLens
from ddigraph.query import Query, asc, compare, evaluate, missing, node, not_, prop

lens = MemoryLens()
lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="codebook"), dataset_id="codebook"
)

not_sex = Query(
    match=[node("v", "Variable")],
    where=not_(compare(prop("v", "question_text"), "==", "What is your sex?")),
    returns=[prop("v", "name")],
    order_by=[asc(prop("v", "name"))],
)
print("not SEX:", [name for (name,) in evaluate(not_sex, lens)])

no_text = Query(
    match=[node("v", "Variable")],
    where=missing(prop("v", "question_text")),
    returns=[prop("v", "name")],
    order_by=[asc(prop("v", "name"))],
)
print("no question text:", [name for (name,) in evaluate(no_text, lens)])
not SEX: [Text(value='AGE', lang=None), Text(value='EDUC', lang=None), Text(value='HOURS', lang=None), Text(value='REGION', lang=None)]
no question text: [Text(value='AGEGRP', lang=None), Text(value='ILOSTAT', lang=None)]

The first filter loses AGEGRP and ILOSTAT, the two derived variables. They have no question text, so "question text == 'What is your sex?'" is unknown for them. not_ of unknown is still unknown, and an unknown row is dropped. missing is never unknown. To list every variable but SEX, filter on a property every variable has: compare(prop("v", "name"), "!=", "SEX").

Exercise 3 (O4). Load tests/fixtures/lfs_cdi.xml, the survey in DDI-CDI. Count its CDICodeList, CDICode and CDICategory nodes, then its DENOTES edges from a code to a category.

Expected output:

CDICodeList 5
CDICode     21
CDICategory 21
DENOTES     21
Answer
from ddigraph import ir
from ddigraph.lens.memory import MemoryLens
from ddigraph.query import Query, count, edge, evaluate, node

lens = MemoryLens()
lens.write(ir.parse("tests/fixtures/lfs_cdi.xml", dataset_id="cdi"), dataset_id="cdi")

for label in ("CDICodeList", "CDICode", "CDICategory"):
    [(total,)] = evaluate(Query(match=[node("n", label)], returns=[count()]), lens)
    print(f"{label:11} {total}")

denotes = Query(
    match=[node("x", "CDICode"), node("c", "CDICategory"), edge("x", "DENOTES", "c")],
    returns=[count()],
)
[(total,)] = evaluate(denotes, lens)
print(f"{'DENOTES':11} {total}")
CDICodeList 5
CDICode     21
CDICategory 21
DENOTES     21

Each code denotes one category, so the last three counts agree. A count that did not match would point at a code with no category, or at a stub, as in Module 4. There are 5 code lists for 7 variables, because AGE and HOURS are numbers.

Exercise 4 (O5). DDI-CDI links a code list to its categories its own way: (CDICodeList)-[:HAS_CODE]->(CDICode)-[:DENOTES]->(CDICategory). Load tests/fixtures/lfs_cdi.xml, and print each code list's name with its number of categories, largest first.

Expected output:

Age group: 6
Highest level of education: 5
Region: 5
Labour force status (ILO): 3
Sex: 2
Answer
from collections import Counter

from ddigraph import ir
from ddigraph.lens.memory import MemoryLens
from ddigraph.query import Query, edge, evaluate, key, node, prop

lens = MemoryLens()
lens.write(ir.parse("tests/fixtures/lfs_cdi.xml", dataset_id="cdi"), dataset_id="cdi")

query = Query(
    match=[
        node("l", "CDICodeList"),
        node("x", "CDICode"),
        node("c", "CDICategory"),
        edge("l", "HAS_CODE", "x"),
        edge("x", "DENOTES", "c"),
    ],
    returns=[prop("l", "name"), key("c")],
)
sizes = Counter(name.value for name, _category in evaluate(query, lens))
for name, size in sorted(sizes.items(), key=lambda item: (-item[1], item[0])):
    print(f"{name}: {size}")
Age group: 6
Highest level of education: 5
Region: 5
Labour force status (ILO): 3
Sex: 2

The pattern is the DDI 3.3 shape with CDI names: the codes sit between the list and its categories. A CDI name is a plain string, so it needs no .value. The DDI-L file has one list more, "Yes or no". It serves the questions WORK, LOOK and AVAIL, and DDI-CDI 1.0 holds no questions.


Quiz

Question 1 (O1): What does lens.write(chunks, dataset_id='codebook') return?

A. The rows of a query.

B. A WriteResult that counts the nodes, edges and stubs it wrote.

C. Nothing: it only stores the graph.

D. A copy of the graph as a list.

Answer

B. The counts let you check a load at once, as in section 1: 80 nodes and 48 edges, as the preview said. Rows (A) come from evaluate or run.

Question 2 (O2): A query matches node('q', 'QuestionItem'), node('v', 'Variable') and edge('q', 'REFERENCES_QUESTION', 'v'). It returns no rows. Why?

A. REFERENCES_QUESTION is not a real edge type.

B. The edge points the wrong way: REFERENCES_QUESTION goes from the variable to the question.

C. MemoryLens cannot follow edges.

D. The names q and v are reserved.

Answer

B. An edge pattern follows the direction of the IR. A is tempting, but a misspelled type would raise a ValueError when you build the query, not return an empty list.

Question 3 (O3): Why does not_(compare(prop('v', 'question_text'), '==', 'What is your sex?')) skip AGEGRP and ILOSTAT?

A. not_ only works on text properties.

B. A comparison with a missing value is unknown, not_ of unknown is unknown, and an unknown row is dropped.

C. AGEGRP and ILOSTAT are stubs.

D. compare is case-sensitive.

Answer

B. This is SQL's rule, and every engine follows it. The two derived variables have no question text. To find them, use missing(prop('v', 'question_text')), which is never unknown.

Question 4 (O4): Query(match=[node('n', 'Variable')], returns=[prop('n', 'label'), count()]) raises a ValueError. Why?

A. count() is returned alone: a query has no group by.

B. Variable has no label property.

C. count() needs an edge pattern.

D. A query needs an order_by to count.

Answer

A. The message says count(*) is returned alone. To count by some value, run one count query per value, or return the rows and count them in Python with collections.Counter.

Question 5 (O5): You ask a DDI 3.3 file for (CodeList)-[:HAS_CATEGORY]->(Category) and get no rows, yet its code lists have categories. Why?

A. DDI 3.3 has no categories.

B. In DDI 3.3 each code has an ID, so it is a node, and the categories hang off the codes: CONTAINS, then HAS_CATEGORY.

C. The file must be loaded into Neo4j first.

D. HAS_CATEGORY is a CDI edge type.

Answer

B. Ask through the codes too, as section 7 does. Only a code with no ID, as in DDI 3.1, leaves the edge on its code list.

Question 6 (O2): When does ddigraph notice that you wrote node('q', 'QuestionItm')?

A. Never: the query returns no rows.

B. When evaluate reads the first node.

C. As soon as you build the Query, before any data is read.

D. Only when the query runs on Neo4j.

Answer

C. The Query checks each name against ddigraph's model and raises a ValueError with the nearest valid name. A is what would happen in a hand-written loop, which is the reason for the check.


Check yourself

  • I can load a DDI file into a MemoryLens and say what a lens is. (O1)
  • I can write a Query from node, edge and prop, and read its rows with evaluate or run. (O2)
  • I can narrow and sort the rows with compare, missing, asc, desc and limit. (O3)
  • I can count nodes or edges with count(), one type at a time. (O4)
  • I can find each code list's categories, whether they hang off the codes or off the code list. (O5)

Next: Module 6: Prove it is right: XSD and SHACL