Skip to content

Module 10: One query, many engines

Learning objectives

By the end of this module, you can:

  • O1. Write a typed query with ddigraph.query (Query, node, edge, prop, compare, asc), and read the error that a wrong name gives.
  • O2. Run the same query on MemoryLens (evaluate or run), on DuckDB through SQLLens(duckdb.connect()) and on OxigraphLens, and check that the rows are identical.
  • O3. Show the text each engine runs with to_sql, to_sparql and to_cypher, and find the query's parameters.
  • O4. Apply the rules every engine shares: rows are a multiset, a missing value is unknown, a limit needs an order; and say which lenses are not query targets.

Prerequisites: Module 9

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

Needs: No server for the Memory, DuckDB and Oxigraph tabs, which need the duckdb and oxigraph extras (pip install "ddigraph[duckdb,oxigraph]"). The Neo4j and PostgreSQL tabs of section 4 use the servers you started in Module 2.

New in this module: ddigraph.query, Query, node, edge, prop, compare, asc, count, missing, not_, or_, evaluate, run, to_sql, to_sparql, to_cypher, SQLLens, OxigraphLens, Neo4jLens


1. Why one query?

You now know three ways to ask a graph a question: Python over the stream (Module 5), Cypher in Neo4j (Module 7), and SPARQL over RDF (Modules 8 and 9). Each engine has its own language. Worse, two queries that look the same can give different answers. Cypher and SPARQL do not count rows the same way, and they do not treat a missing value the same way.

ddigraph.query solves this. You write a query once, in Python, as a plain data structure. ddigraph turns it into the language of each engine:

Engine Lens Language
In memory MemoryLens Python, the reference evaluator
DuckDB, PostgreSQL SQLLens SQL
Oxigraph, rdflib OxigraphLens, RDFLens SPARQL
Neo4j Neo4jLens, or a neo4j driver Cypher

A lens is a backend that stores the graph and reads it back. Module 12 looks at lenses in depth. Every engine in the table gives the same rows for the same query. ddigraph checks that on hundreds of generated queries with python -m ddigraph.conform query.

The query is small on purpose. It is a core part of GQL, the ISO standard for graph queries: node and edge patterns, filters, returns, order and limit. The queries page is the full reference.

2. A first query

A query has three main parts:

  • match: the patterns. node("v", "Variable") binds the variable v to each node of type Variable. edge("v", "USES_CONCEPT", "c") joins two bound variables by a relationship, in the direction the graph has it.
  • returns: what each row holds. prop("v", "name") is a property.
  • order_by: how to sort the rows. asc(...) sorts up, desc(...) down.

This query asks which concept each variable of the sample survey uses. It reads the survey's Codebook file, tests/fixtures/lfs_codebook.xml, and runs on a MemoryLens, the in-memory lens that needs no extra:

from ddigraph import ir
from ddigraph.lens.memory import MemoryLens
from ddigraph.query import Query, asc, edge, 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"), node("c", "Concept"), edge("v", "USES_CONCEPT", "c")],
    returns=[prop("v", "name"), prop("c", "label")],
    order_by=[asc(prop("v", "name"))],
)
for row in evaluate(query, lens):
    print(row)

Expected output:

(Text(value='AGE', lang=None), Text(value='Demographic characteristics', lang=None))
(Text(value='AGEGRP', lang=None), Text(value='Demographic characteristics', lang=None))
(Text(value='EDUC', lang=None), Text(value='Educational attainment', lang=None))
(Text(value='HOURS', lang=None), Text(value='Working time', lang=None))
(Text(value='ILOSTAT', lang=None), Text(value='Labour market status', lang=None))
(Text(value='REGION', lang=None), Text(value='Place of residence', lang=None))
(Text(value='SEX', lang=None), Text(value='Demographic characteristics', lang=None))

Each row is a tuple of plain values. name and label are text properties, so each comes back as a Text, which keeps its language (here, none: the Codebook file names no language). Read the string itself with .value. A missing value comes back as None.

Three variables have a concept labelled "Demographic characteristics". DDI-Codebook has no reuse: each variable states its own concept, so these are three Concept nodes with the same label, one for each row.

evaluate is the reference evaluator. It runs the query in Python, and works on a MemoryLens only. run(query, target) takes any engine of the table, as the next sections show.

3. Typed: mistakes fail early

A query is checked when you build it, before any engine sees it. A label must be a type of the model, a property one that the label owns, and a literal of the property's type. A wrong name raises ValueError, with the nearest valid name:

from ddigraph.query import Query, compare, count, edge, node, prop

attempts = [
    lambda: Query(match=[node("v", "Variabel")], returns=[prop("v", "name")]),
    lambda: Query(match=[node("v", "Variable")], returns=[prop("v", "nmae")]),
    lambda: Query(
        match=[node("v", "Variable"), edge("v", "USES_CONCEPT", "c")], returns=[prop("v", "name")]
    ),
    lambda: Query(match=[node("v", "Variable")], returns=[prop("v", "name"), count()]),
    lambda: Query(
        match=[node("s", "Sequence")],
        returns=[prop("s", "label")],
        where=compare(prop("s", "construct_count"), ">", "1"),
    ),
]
for attempt in attempts:
    try:
        attempt()
    except ValueError as error:
        print(error)

Expected output:

Unknown label 'Variabel'; did you mean 'Variable'?
v:Variable has no property 'nmae'; did you mean 'name'?
Variable 'c' is not bound: bind it with a node pattern first
count(*) is returned alone
s.construct_count is an int property: compare it with an int, not '1'

Read the third and fourth errors closely. Each variable must be bound by a node(...) pattern before an edge(...) uses it. And count() must be the only returned term. A Cypher or SPARQL typo would instead give an empty result, which looks like a real answer.

4. The same rows on every engine

Now run the same query on every engine. Pick a backend in the box below. Each tab is a complete program: it writes the Codebook file to its lens, then runs the query with run(query, lens). Every tab prints the same seven rows, because it is one graph.

The query sets dataset_id="m10-codebook", and each lens writes the file under that ID. A server such as Neo4j or PostgreSQL may hold other datasets, so dataset_id keeps only this one's nodes. The in-memory engines hold one dataset here, but the same query runs there unchanged.

The reference evaluator, in Python. On a MemoryLens, run calls evaluate:

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

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"))],
    dataset_id="m10-codebook",
)

lens = MemoryLens()
lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m10-codebook"),
    dataset_id="m10-codebook",
)
for row in run(query, lens):
    print(row)
(Text(value='AGE', lang=None), Text(value='Demographic characteristics', lang=None))
(Text(value='AGEGRP', lang=None), Text(value='Demographic characteristics', lang=None))
(Text(value='EDUC', lang=None), Text(value='Educational attainment', lang=None))
(Text(value='HOURS', lang=None), Text(value='Working time', lang=None))
(Text(value='ILOSTAT', lang=None), Text(value='Labour market status', lang=None))
(Text(value='REGION', lang=None), Text(value='Place of residence', lang=None))
(Text(value='SEX', lang=None), Text(value='Demographic characteristics', lang=None))

Needs the Neo4j server and the DDIGRAPH_NEO4J_* variables you set in Module 2. run writes Cypher 25 on Neo4j 2025 or later, and Cypher 5 before. The lens purges the dataset before it writes, so the tab can run twice, and after, to clean up:

import os

from neo4j import GraphDatabase

from ddigraph import ir
from ddigraph.lens.neo4j import Neo4jLens
from ddigraph.query import Query, asc, edge, node, prop, run

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"))],
    dataset_id="m10-codebook",
)

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("m10-codebook")
    lens.write(
        ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m10-codebook"),
        dataset_id="m10-codebook",
    )
    for row in run(query, lens):
        print(row)
    lens.purge("m10-codebook")
(Text(value='AGE', lang=None), Text(value='Demographic characteristics', lang=None))
(Text(value='AGEGRP', lang=None), Text(value='Demographic characteristics', lang=None))
(Text(value='EDUC', lang=None), Text(value='Educational attainment', lang=None))
(Text(value='HOURS', lang=None), Text(value='Working time', lang=None))
(Text(value='ILOSTAT', lang=None), Text(value='Labour market status', lang=None))
(Text(value='REGION', lang=None), Text(value='Place of residence', lang=None))
(Text(value='SEX', lang=None), Text(value='Demographic characteristics', lang=None))

Needs the PostgreSQL server of Module 2 and the postgres extra. The SQL lens makes its ddigraph_ tables if they are not there, and purges the dataset before and after:

import psycopg

from ddigraph import ir
from ddigraph.lens.sql import SQLLens
from ddigraph.query import Query, asc, edge, node, prop, run

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"))],
    dataset_id="m10-codebook",
)

with psycopg.connect(
    "postgresql://postgres:postgres@localhost:5432/postgres", autocommit=True
) as connection:
    lens = SQLLens(connection)
    lens.purge("m10-codebook")
    lens.write(
        ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m10-codebook"),
        dataset_id="m10-codebook",
    )
    for row in run(query, lens):
        print(row)
    lens.purge("m10-codebook")
(Text(value='AGE', lang=None), Text(value='Demographic characteristics', lang=None))
(Text(value='AGEGRP', lang=None), Text(value='Demographic characteristics', lang=None))
(Text(value='EDUC', lang=None), Text(value='Educational attainment', lang=None))
(Text(value='HOURS', lang=None), Text(value='Working time', lang=None))
(Text(value='ILOSTAT', lang=None), Text(value='Labour market status', lang=None))
(Text(value='REGION', lang=None), Text(value='Place of residence', lang=None))
(Text(value='SEX', lang=None), Text(value='Demographic characteristics', lang=None))

SQLLens(duckdb.connect()) makes an in-memory DuckDB database and its tables:

import duckdb

from ddigraph import ir
from ddigraph.lens.sql import SQLLens
from ddigraph.query import Query, asc, edge, node, prop, run

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"))],
    dataset_id="m10-codebook",
)

lens = SQLLens(duckdb.connect())
lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m10-codebook"),
    dataset_id="m10-codebook",
)
for row in run(query, lens):
    print(row)
(Text(value='AGE', lang=None), Text(value='Demographic characteristics', lang=None))
(Text(value='AGEGRP', lang=None), Text(value='Demographic characteristics', lang=None))
(Text(value='EDUC', lang=None), Text(value='Educational attainment', lang=None))
(Text(value='HOURS', lang=None), Text(value='Working time', lang=None))
(Text(value='ILOSTAT', lang=None), Text(value='Labour market status', lang=None))
(Text(value='REGION', lang=None), Text(value='Place of residence', lang=None))
(Text(value='SEX', lang=None), Text(value='Demographic characteristics', lang=None))

OxigraphLens() makes an in-memory Oxigraph store, an RDF database:

from ddigraph import ir
from ddigraph.lens.oxigraph import OxigraphLens
from ddigraph.query import Query, asc, edge, node, prop, run

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"))],
    dataset_id="m10-codebook",
)

lens = OxigraphLens()
lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m10-codebook"),
    dataset_id="m10-codebook",
)
for row in run(query, lens):
    print(row)
(Text(value='AGE', lang=None), Text(value='Demographic characteristics', lang=None))
(Text(value='AGEGRP', lang=None), Text(value='Demographic characteristics', lang=None))
(Text(value='EDUC', lang=None), Text(value='Educational attainment', lang=None))
(Text(value='HOURS', lang=None), Text(value='Working time', lang=None))
(Text(value='ILOSTAT', lang=None), Text(value='Labour market status', lang=None))
(Text(value='REGION', lang=None), Text(value='Place of residence', lang=None))
(Text(value='SEX', lang=None), Text(value='Demographic characteristics', lang=None))

Five stores, four languages, one answer. run sees which lens it was given and picks the language. The lens's constructor is the only line that changes from one tab to the next.

5. What each engine runs

You may want to see, or reuse, the text an engine runs. Three functions give it, with no server: to_cypher, to_sql and to_sparql. Here is the query of section 4, as each engine receives it:

to_cypher gives the text and its parameters. Pass "25" for Cypher 25:

from ddigraph.query import Query, asc, edge, node, prop, to_cypher

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"))],
    dataset_id="m10-codebook",
)

text, parameters = to_cypher(query, "5")
print(text)
print(parameters)
CYPHER 5
MATCH (v:DDINode:Variable)
WHERE (v.key = $dataset OR EXISTS { (v)-[:IN_DATASET]->(:DDINode {key: $dataset}) })
MATCH (c:DDINode:Concept)
WHERE (c.key = $dataset OR EXISTS { (c)-[:IN_DATASET]->(:DDINode {key: $dataset}) })
MATCH (v)-[:USES_CONCEPT]->(c)
RETURN v.name AS `v.name`, v.name_lang AS `v.name lang`, c.label AS `c.label`, c.label_lang AS `c.label lang`
ORDER BY `v.name`, coalesce(toLower(`v.name lang`), ''), coalesce(`v.name lang`, '')
{'dataset': '28abecfcd0f23d302bc97f27c1f9f01a'}

to_sql(query, "postgres") gives the text and its parameters, $1 first:

from ddigraph.query import Query, asc, edge, node, prop, to_sql

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"))],
    dataset_id="m10-codebook",
)

sql, parameters = to_sql(query, "postgres")
print(sql)
print(parameters)
WITH RECURSIVE v0 (key) AS MATERIALIZED (
  SELECT key FROM ddigraph_nodes
  WHERE key IN (SELECT key FROM ddigraph_labels WHERE type_label = 'Variable')
    AND key IN (SELECT key FROM ddigraph_memberships WHERE dataset = $2
      UNION ALL SELECT CAST($1 AS TEXT))
),
v1 (key) AS MATERIALIZED (
  SELECT key FROM ddigraph_nodes
  WHERE key IN (SELECT key FROM ddigraph_labels WHERE type_label = 'Concept')
    AND key IN (SELECT key FROM ddigraph_memberships WHERE dataset = $2
      UNION ALL SELECT CAST($1 AS TEXT))
)
SELECT c0, c1, c2, c3
FROM (
SELECT p0.string_value AS c0, p0.language AS c1, p1.string_value AS c2, p1.language AS c3
FROM (
  SELECT n0.key AS n0, n1.key AS n1
  FROM v0 AS n0, v1 AS n1, ddigraph_relationships AS e0
  WHERE e0.start_key = n0.key AND e0.type = 'USES_CONCEPT' AND e0.end_key = n1.key
) AS m
LEFT JOIN ddigraph_properties AS p0
  ON p0.key = m.n0 AND p0.name = 'name'
LEFT JOIN ddigraph_properties AS p1
  ON p1.key = m.n1 AND p1.name = 'label'
) AS r
ORDER BY c0 COLLATE "C" ASC NULLS LAST, coalesce(lower(c1), '') COLLATE "C" ASC, coalesce(c1, '') COLLATE "C" ASC
['28abecfcd0f23d302bc97f27c1f9f01a', 'm10-codebook']

The same SQL for DuckDB. Only the string comparisons differ: DuckDB compares bytes, so it needs no COLLATE "C":

from ddigraph.query import Query, asc, edge, node, prop, to_sql

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"))],
    dataset_id="m10-codebook",
)

sql, parameters = to_sql(query, "duckdb")
print(sql)
print(parameters)
WITH RECURSIVE v0 (key) AS MATERIALIZED (
  SELECT key FROM ddigraph_nodes
  WHERE key IN (SELECT key FROM ddigraph_labels WHERE type_label = 'Variable')
    AND key IN (SELECT key FROM ddigraph_memberships WHERE dataset = $2
      UNION ALL SELECT CAST($1 AS TEXT))
),
v1 (key) AS MATERIALIZED (
  SELECT key FROM ddigraph_nodes
  WHERE key IN (SELECT key FROM ddigraph_labels WHERE type_label = 'Concept')
    AND key IN (SELECT key FROM ddigraph_memberships WHERE dataset = $2
      UNION ALL SELECT CAST($1 AS TEXT))
)
SELECT c0, c1, c2, c3
FROM (
SELECT p0.string_value AS c0, p0.language AS c1, p1.string_value AS c2, p1.language AS c3
FROM (
  SELECT n0.key AS n0, n1.key AS n1
  FROM v0 AS n0, v1 AS n1, ddigraph_relationships AS e0
  WHERE e0.start_key = n0.key AND e0.type = 'USES_CONCEPT' AND e0.end_key = n1.key
) AS m
LEFT JOIN ddigraph_properties AS p0
  ON p0.key = m.n0 AND p0.name = 'name'
LEFT JOIN ddigraph_properties AS p1
  ON p1.key = m.n1 AND p1.name = 'label'
) AS r
ORDER BY c0 ASC NULLS LAST, coalesce(lower(c1), '') ASC, coalesce(c1, '') ASC
['28abecfcd0f23d302bc97f27c1f9f01a', 'm10-codebook']

to_sparql gives the text only. The values are written into it, escaped:

from ddigraph.query import Query, asc, edge, node, prop, to_sparql

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"))],
    dataset_id="m10-codebook",
)

print(to_sparql(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 (STR(?_p0) AS ?_t0) (LANG(?_p0) AS ?_l0) (STR(?_p1) AS ?_t1) (LANG(?_p1) AS ?_l1) (1 AS ?_row)
WHERE {
  ?v ddigraph:key ?_k_v .
  ?v a ddigraph:Variable .
  FILTER(?_k_v = "28abecfcd0f23d302bc97f27c1f9f01a" || EXISTS { ?_m_v ddigraph:member ?v ; ddigraph:dataset "m10-codebook" })
  ?c ddigraph:key ?_k_c .
  ?c a ddigraph:Concept .
  FILTER(?_k_c = "28abecfcd0f23d302bc97f27c1f9f01a" || EXISTS { ?_m_c ddigraph:member ?c ; ddigraph:dataset "m10-codebook" })
  ?_e0 rdf:subject ?v ; rdf:predicate ddigraph:usesConcept ; rdf:object ?c .
  FILTER(STRSTARTS(STR(?_e0), "urn:ddigraph:relationship:"))
  OPTIONAL { ?v ddigraph:name ?_p0 . FILTER NOT EXISTS { ?v ddigraph:name ?_o0 . FILTER(LANG(?_p0) != "" && (LANG(?_o0) = "" || LCASE(LANG(?_o0)) < LCASE(LANG(?_p0)))) } }
  OPTIONAL { ?c rdfs:label|skos:prefLabel ?_p1 . FILTER NOT EXISTS { ?c rdfs:label|skos:prefLabel ?_o1 . FILTER(LANG(?_p1) != "" && (LANG(?_o1) = "" || LCASE(LANG(?_o1)) < LCASE(LANG(?_p1)))) } }
}
ORDER BY ASC(!BOUND(?_t0)) ASC(?_t0) ASC(LCASE(COALESCE(?_l0, ""))) ASC(COALESCE(?_l0, ""))

What to notice:

  • Parameters. Cypher and SQL keep values out of the text. The dataset is the parameter $dataset in Cypher, and $1 and $2 in SQL. A literal of a filter would be a parameter too. SPARQL writes the values into the text, escaped.
  • The dataset. Each language reaches the dataset the way its store keeps it: the IN_DATASET edges in Neo4j (Module 7), the ddigraph_memberships table in SQL, and the ddigraph:Membership resources in RDF (Module 8).
  • Patterns. Cypher writes each pattern as its own MATCH. SQL joins ddigraph_relationships to the two nodes. SPARQL matches each edge's rdf:Statement, so two relationships between the same nodes give two rows, as in Neo4j.
  • Text and missing values. A text property comes back as two columns, its value and its language. A property is a LEFT JOIN in SQL and OPTIONAL in SPARQL, so a missing one is NULL or unbound, never a lost row.

The PostgreSQL and DuckDB page describes the SQL lens's tables.

6. The rules every engine follows

The engines agree because ddigraph fixes the rules, and writes each language to follow them. Three rules matter most.

Rows are a multiset. An edge pattern gives one row for each relationship it matches. So the same row can come twice. distinct=True drops the repeats. count() counts the rows.

A missing value is unknown. A filter on a property a node does not have is neither true nor false, as in SQL. not_ of unknown is still unknown, and a row is kept only when its filter is true. missing(...) and exists(...) are never unknown.

A limit needs an order. limit=n needs an order_by over every returned term. Otherwise two engines could keep different rows.

This example shows the first two on all three engines. In the Codebook file, the variable SEX uses two categories, Male and Female. Five variables have a question text. The two derived variables, AGEGRP and ILOSTAT, have none: they are computed from other answers, not asked.

import duckdb

from ddigraph import ir
from ddigraph.lens.memory import MemoryLens
from ddigraph.lens.oxigraph import OxigraphLens
from ddigraph.lens.sql import SQLLens
from ddigraph.query import Query, asc, compare, count, edge, missing, node, not_, or_, prop, run

lenses = [MemoryLens(), SQLLens(duckdb.connect()), OxigraphLens()]
for lens in lenses:
    lens.write(
        ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="codebook"), dataset_id="codebook"
    )

uses = [node("v", "Variable"), node("c", "Category"), edge("v", "USES_CATEGORY", "c")]
name = prop("v", "name")
text = prop("v", "question_text")
is_sex = compare(name, "==", "SEX")
sex_question = compare(text, "==", "What is your sex?")
queries = {
    "rows": Query(match=uses, returns=[name], where=is_sex),
    "distinct": Query(match=uses, returns=[name], where=is_sex, distinct=True),
    "count": Query(match=uses, returns=[count()], where=is_sex),
    "not sex": Query(
        match=[node("v", "Variable")],
        returns=[name],
        where=not_(sex_question),
        order_by=[asc(name)],
    ),
    "missing or not sex": Query(
        match=[node("v", "Variable")],
        returns=[name],
        where=or_(missing(text), not_(sex_question)),
        order_by=[asc(name)],
    ),
}
for title, query in queries.items():
    answers = [run(query, lens) for lens in lenses]
    print(f"{title}: {answers[0]}  same on every engine: {answers[0] == answers[1] == answers[2]}")

Expected output:

rows: [(Text(value='SEX', lang=None),), (Text(value='SEX', lang=None),)]  same on every engine: True
distinct: [(Text(value='SEX', lang=None),)]  same on every engine: True
count: [(2,)]  same on every engine: True
not sex: [(Text(value='AGE', lang=None),), (Text(value='EDUC', lang=None),), (Text(value='HOURS', lang=None),), (Text(value='REGION', lang=None),)]  same on every engine: True
missing or not sex: [(Text(value='AGE', lang=None),), (Text(value='AGEGRP', lang=None),), (Text(value='EDUC', lang=None),), (Text(value='HOURS', lang=None),), (Text(value='ILOSTAT', lang=None),), (Text(value='REGION', lang=None),)]  same on every engine: True

Look at not sex. It returns four variables, not six. AGEGRP and ILOSTAT have no question text, so "the question text is What is your sex?" is unknown for them, and "not unknown" is unknown too. To keep them, say so with missing(text). Without shared rules, one engine would keep them and another would drop them.

7. What is not a query target

run takes a MemoryLens, an SQLLens, an OxigraphLens, an RDFLens, a Neo4jLens or a neo4j driver. NetworkX and pandas are not query targets. Their lenses store the graph for analysis in those libraries, and run refuses them with TypeError. To query such a graph, copy it into a MemoryLens first: every lens reads back the same stream.

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

query = Query(
    match=[node("q", "QuestionItem"), node("l", "CodeList"), edge("q", "USES_CODELIST", "l")],
    returns=[prop("q", "name"), prop("l", "label")],
    order_by=[asc(prop("q", "name"))],
)

nx_lens = NetworkXLens()
nx_lens.write(
    ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id="survey"), dataset_id="survey"
)
try:
    run(query, nx_lens)
except TypeError as error:
    print("TypeError:", error)

memory = MemoryLens()
memory.write(nx_lens.read(dataset_id="survey"), dataset_id="survey")
for row in run(query, memory):
    print(row)

Expected output:

TypeError: Cannot run a query on a NetworkXLens
(Text(value='AVAIL', lang='en'), Text(value='Yes or no', lang='en'))
(Text(value='EDUC', lang='en'), Text(value='Highest level of education', lang='en'))
(Text(value='LOOK', lang='en'), Text(value='Yes or no', lang='en'))
(Text(value='REGION', lang='en'), Text(value='Region', lang='en'))
(Text(value='SEX', lang='en'), Text(value='Sex', lang='en'))
(Text(value='WORK', lang='en'), Text(value='Yes or no', lang='en'))

The copy holds the whole DDI-L survey, tests/fixtures/lfs_lifecycle.xml. Six of its eight questions use a code list. AGE and HOURS ask for a number, so they have none. Three questions share the Yes or no list, as in Module 9.

In NetworkX, you query with NetworkX itself: paths, neighbours, graph algorithms. The NetworkX page shows how.


Exercises

Scenario

Your team keeps survey metadata in DuckDB for reports and in Oxigraph for the linked-data site. A colleague asks whether a question checker can be written once and trusted on both.

Exercise 1 (O1, O2). Write a query that returns the name of each QuestionItem that uses (USES_CODELIST) the CodeList whose label is "Yes or no", sorted by name. Write tests/fixtures/lfs_lifecycle.xml to a MemoryLens, an SQLLens on DuckDB and an OxigraphLens. Print each lens's class name and rows, then whether all three agree.

Expected output:

MemoryLens [(Text(value='AVAIL', lang='en'),), (Text(value='LOOK', lang='en'),), (Text(value='WORK', lang='en'),)]
SQLLens [(Text(value='AVAIL', lang='en'),), (Text(value='LOOK', lang='en'),), (Text(value='WORK', lang='en'),)]
OxigraphLens [(Text(value='AVAIL', lang='en'),), (Text(value='LOOK', lang='en'),), (Text(value='WORK', lang='en'),)]
same: True
Answer
import duckdb

from ddigraph import ir
from ddigraph.lens.memory import MemoryLens
from ddigraph.lens.oxigraph import OxigraphLens
from ddigraph.lens.sql import SQLLens
from ddigraph.query import Query, asc, compare, edge, node, prop, run

query = Query(
    match=[node("q", "QuestionItem"), node("l", "CodeList"), edge("q", "USES_CODELIST", "l")],
    returns=[prop("q", "name")],
    where=compare(prop("l", "label"), "==", "Yes or no"),
    order_by=[asc(prop("q", "name"))],
)

results = []
for lens in (MemoryLens(), SQLLens(duckdb.connect()), OxigraphLens()):
    lens.write(
        ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id="survey"), dataset_id="survey"
    )
    rows = run(query, lens)
    print(type(lens).__name__, rows)
    results.append(rows)
print("same:", all(rows == results[0] for rows in results))
MemoryLens [(Text(value='AVAIL', lang='en'),), (Text(value='LOOK', lang='en'),), (Text(value='WORK', lang='en'),)]
SQLLens [(Text(value='AVAIL', lang='en'),), (Text(value='LOOK', lang='en'),), (Text(value='WORK', lang='en'),)]
OxigraphLens [(Text(value='AVAIL', lang='en'),), (Text(value='LOOK', lang='en'),), (Text(value='WORK', lang='en'),)]
same: True

The code that writes and queries does not change from one lens to the next. Only the lens's constructor does. A text property such as label compares with a plain string: the filter reads its value, not its language. The three questions share one code list, so a change to that list reaches all three.

Exercise 2 (O3). Build a query for each QuestionItem whose name is "WORK", returning its name. Print the parameters of its PostgreSQL SQL, the parameters of its Cypher, and whether "WORK" (with its quotes) appears in its SPARQL text. Then print the PostgreSQL SQL itself.

Expected output:

['WORK'] {'p0': 'WORK'} True
WITH RECURSIVE v0 (key) AS MATERIALIZED (
  SELECT key FROM ddigraph_nodes
  WHERE key IN (SELECT key FROM ddigraph_labels WHERE type_label = 'QuestionItem')
)
SELECT p0.string_value AS c0, p0.language AS c1
FROM (
  SELECT n0.key AS n0
  FROM v0 AS n0
) AS m
LEFT JOIN ddigraph_properties AS p0
  ON p0.key = m.n0 AND p0.name = 'name'
WHERE (p0.string_value COLLATE "C" = $1)
Answer
from ddigraph.query import Query, compare, node, prop, to_cypher, to_sparql, to_sql

query = Query(
    match=[node("q", "QuestionItem")],
    returns=[prop("q", "name")],
    where=compare(prop("q", "name"), "==", "WORK"),
)
sql, sql_parameters = to_sql(query, "postgres")
_cypher, cypher_parameters = to_cypher(query)
print(sql_parameters, cypher_parameters, '"WORK"' in to_sparql(query))
print(sql)
['WORK'] {'p0': 'WORK'} True
WITH RECURSIVE v0 (key) AS MATERIALIZED (
  SELECT key FROM ddigraph_nodes
  WHERE key IN (SELECT key FROM ddigraph_labels WHERE type_label = 'QuestionItem')
)
SELECT p0.string_value AS c0, p0.language AS c1
FROM (
  SELECT n0.key AS n0
  FROM v0 AS n0
) AS m
LEFT JOIN ddigraph_properties AS p0
  ON p0.key = m.n0 AND p0.name = 'name'
WHERE (p0.string_value COLLATE "C" = $1)

SQL and Cypher keep every literal out of the text, as a parameter. So a value from a user can never change the query itself. SPARQL writes the literal in, escaped. On PostgreSQL, COLLATE "C" makes the comparison go by code point, as on the other engines.

Exercise 3 (O4). In the survey, HOURS is the only variable with a narrower universe: it is asked of employed persons only. In the Codebook file, list each Variable whose question_text is not the HOURS question, "How many hours a week do you usually work in your main job?". Include the derived variables, which have no question text at all. Return the name, sorted. Run it on the three engines and print the rows of each.

Expected output:

[(Text(value='AGE', lang=None),), (Text(value='AGEGRP', lang=None),), (Text(value='EDUC', lang=None),), (Text(value='ILOSTAT', lang=None),), (Text(value='REGION', lang=None),), (Text(value='SEX', lang=None),)]
[(Text(value='AGE', lang=None),), (Text(value='AGEGRP', lang=None),), (Text(value='EDUC', lang=None),), (Text(value='ILOSTAT', lang=None),), (Text(value='REGION', lang=None),), (Text(value='SEX', lang=None),)]
[(Text(value='AGE', lang=None),), (Text(value='AGEGRP', lang=None),), (Text(value='EDUC', lang=None),), (Text(value='ILOSTAT', lang=None),), (Text(value='REGION', lang=None),), (Text(value='SEX', lang=None),)]
Answer
import duckdb

from ddigraph import ir
from ddigraph.lens.memory import MemoryLens
from ddigraph.lens.oxigraph import OxigraphLens
from ddigraph.lens.sql import SQLLens
from ddigraph.query import Query, asc, compare, missing, node, or_, prop, run

text = prop("v", "question_text")
hours_question = "How many hours a week do you usually work in your main job?"
query = Query(
    match=[node("v", "Variable")],
    returns=[prop("v", "name")],
    where=or_(missing(text), compare(text, "!=", hours_question)),
    order_by=[asc(prop("v", "name"))],
)
for lens in (MemoryLens(), SQLLens(duckdb.connect()), OxigraphLens()):
    lens.write(
        ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="codebook"), dataset_id="codebook"
    )
    print(run(query, lens))
[(Text(value='AGE', lang=None),), (Text(value='AGEGRP', lang=None),), (Text(value='EDUC', lang=None),), (Text(value='ILOSTAT', lang=None),), (Text(value='REGION', lang=None),), (Text(value='SEX', lang=None),)]
[(Text(value='AGE', lang=None),), (Text(value='AGEGRP', lang=None),), (Text(value='EDUC', lang=None),), (Text(value='ILOSTAT', lang=None),), (Text(value='REGION', lang=None),), (Text(value='SEX', lang=None),)]
[(Text(value='AGE', lang=None),), (Text(value='AGEGRP', lang=None),), (Text(value='EDUC', lang=None),), (Text(value='ILOSTAT', lang=None),), (Text(value='REGION', lang=None),), (Text(value='SEX', lang=None),)]

compare(text, "!=", ...) alone would drop AGEGRP and ILOSTAT, whose question text is missing: the filter is unknown there. missing(text) is never unknown, so or_ keeps them.

Exercise 4 (O4). Write tests/fixtures/lfs_codebook.xml to a NetworkXLens as the dataset codebook. Count its Variable nodes with a count() query: first try run on the NetworkX lens and print the error, then copy the dataset into a MemoryLens and run the query there.

Expected output:

TypeError: Cannot run a query on a NetworkXLens
[(7,)]
Answer
from ddigraph import ir
from ddigraph.lens.memory import MemoryLens
from ddigraph.lens.networkx import NetworkXLens
from ddigraph.query import Query, count, node, run

query = Query(match=[node("v", "Variable")], returns=[count()])

nx_lens = NetworkXLens()
nx_lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="codebook"), dataset_id="codebook"
)
try:
    run(query, nx_lens)
except TypeError as error:
    print("TypeError:", error)

memory = MemoryLens()
memory.write(nx_lens.read(dataset_id="codebook"), dataset_id="codebook")
print(run(query, memory))
TypeError: Cannot run a query on a NetworkXLens
[(7,)]

NetworkX and pandas are stores for analysis, not query engines. Every lens reads back the same stream, so moving a dataset from one lens to another is one write of the other's read. The count is the survey's seven variables.


Quiz

Question 1 (O1): You misspell a property, prop('v', 'lable'). When do you find out?

A. When run sends the query to DuckDB, which reports an unknown column.

B. Never: the query returns None in that column.

C. When you build the Query: it raises ValueError and suggests label.

D. Only on Neo4j, which warns about unknown properties.

Answer

C. A query is checked against the model as it is built. B is what a Cypher typo would do in Neo4j, which is why it is tempting: an unknown property there is quietly null. That is the mistake the typed query prevents.

Question 2 (O2): Which call runs a query on an in-memory DuckDB database?

A. run(query, duckdb.connect())

B. run(query, SQLLens(duckdb.connect())), after the lens has written the graph.

C. evaluate(query, SQLLens(duckdb.connect()))

D. to_sql(query, "duckdb") alone.

Answer

B. run needs a lens, which knows its tables. A is tempting, but a bare connection has no ddigraph_ tables until a lens makes them, and run does not take one. evaluate works on a MemoryLens only. to_sql gives the text and runs nothing.

Question 3 (O3): to_cypher(query) returns a pair. What is the second item?

A. The Cypher version, "5" or "25".

B. The parameters: each literal of the query, such as {'p0': 'SEX'}.

C. The column names of the result.

D. The query's rows, run on the default server.

Answer

B. Every literal is a parameter, so a value can never change the query's text. A is tempting because the text starts with CYPHER 5, but the version is the function's second argument, not part of what it returns.

Question 4 (O4): A query filters with not_(compare(prop('v', 'question_text'), '==', 'What is your sex?')). The derived variable ILOSTAT has no question_text. Is it in the result?

A. Yes: its question text is not "What is your sex?".

B. No: the comparison is unknown, not of unknown is unknown, and only true rows are kept.

C. It depends on the engine.

D. The query raises ValueError, because question_text can be missing.

Answer

B. A missing value is unknown, as in SQL. A is the everyday reading, which is why it is tempting. C would be true without ddigraph.query: the shared rule is what makes every engine agree. Add missing(...) with or_ to keep such rows.

Question 5 (O4): Why does Query(..., limit=10) need an order_by over every returned term?

A. Because SQL cannot run LIMIT without ORDER BY.

B. Without a full order, two engines could keep two different sets of 10 rows.

C. To make the query faster.

D. Because rows are returned as tuples.

Answer

B. Each engine may return rows in any order before the limit. Only a full order makes "the first 10" mean the same rows everywhere. A is false: SQL accepts a bare LIMIT, and that is exactly the problem.

Question 6 (O4): You keep a graph in a PandasLens and want to run a ddigraph.query on it. What do you do?

A. Call run(query, pandas_lens).

B. Use to_sql and run the SQL on the DataFrames.

C. Write pandas_lens.read() into a MemoryLens, or another query target, and run the query there.

D. It cannot be done: pandas graphs have a different model.

Answer

C. pandas, like NetworkX, is not a query target, so run raises TypeError. But every lens reads back the same stream, so a copy is one write. B is tempting, but the SQL reads the SQL lens's tables, not your DataFrames.


Check yourself

  • I can write a typed query with ddigraph.query, and read the error that a wrong name gives. (O1)
  • I can run the same query on MemoryLens, on DuckDB through SQLLens and on OxigraphLens, and check that the rows are identical. (O2)
  • I can show the text each engine runs with to_sql, to_sparql and to_cypher, and find the query's parameters. (O3)
  • I can apply the rules every engine shares, and say which lenses are not query targets. (O4)

Next: Module 11: Reload, history and differences