Queries Across Engines¶
ddigraph writes one graph to many backends: Neo4j, RDF, Oxigraph, PostgreSQL, DuckDB and an in-memory lens. Each backend has its own query language. Cypher and SPARQL look alike, but they do not count rows the same way, and they do not treat a missing value the same way either. So two queries that look the same can give different answers.
ddigraph.query solves this. You write a query once, in Python. ddigraph
turns it into Cypher for Neo4j, into SPARQL for RDF and Oxigraph, and into
SQL for PostgreSQL and DuckDB. A reference evaluator runs it in Python, over the in-memory lens. Every engine
gives the same rows. python -m ddigraph.conform query checks that, on
hundreds of generated queries.
The query is small on purpose. It is a core subset of GQL pattern matching: node and edge patterns, filters, returns, order and limit. It needs no optional extra, except the one of the backend you run it on.
A First Query¶
The example below reads survey.xml, a DDI-L file, into the in-memory lens.
It then asks which categories each question's code list holds.
from ddigraph import ir
from ddigraph.ir.model import Text
from ddigraph.lens.memory import MemoryLens
from ddigraph.query import Query, asc, edge, evaluate, node, prop
lens = MemoryLens()
lens.write(ir.parse("survey.xml", dataset_id="survey"), dataset_id="survey")
query = Query(
match=[
node("q", "QuestionItem"),
node("l", "CodeList"),
node("c", "Category"),
edge("q", "USES_CODELIST", "l"),
edge("l", "HAS_CATEGORY", "c"),
],
returns=[prop("q", "name"), prop("c", "label")],
order_by=[asc(prop("q", "name")), asc(prop("c", "label"))],
)
rows = evaluate(query, lens)
print(rows)
assert rows == [(Text("Q1"), Text("Under 18"))]
[(Text(value='Q1', lang=None), Text(value='Under 18', lang=None))]
Each row is a tuple of plain values: a key, a string, an integer, or a
Text for a text property, which keeps its language. A missing value is
None.
The Same Query in Cypher and SPARQL¶
to_cypher(query) gives the Cypher text and its parameters. Every literal
is a parameter. This query has none:
CYPHER 5
MATCH (q:DDINode:QuestionItem)
MATCH (l:DDINode:CodeList)
MATCH (c:DDINode:Category)
MATCH (q)-[:USES_CODELIST]->(l)
MATCH (l)-[:HAS_CATEGORY]->(c)
RETURN q.name AS `q.name`, c.label AS `c.label`, c.label_lang AS `c.label lang`
ORDER BY `q.name`, `c.label`, coalesce(toLower(`c.label lang`), ''), coalesce(`c.label lang`, '')
Each pattern is its own MATCH clause. A text property comes back as two
columns: its value and its language.
to_sparql(query) gives the SPARQL text, for the graph the RDF and
Oxigraph lenses write:
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 ?_p0 (STR(?_p1) AS ?_t1) (LANG(?_p1) AS ?_l1) (1 AS ?_row)
WHERE {
?q ddigraph:key ?_k_q .
?q a ddigraph:QuestionItem .
?l ddigraph:key ?_k_l .
?l a ddigraph:CodeList .
?c ddigraph:key ?_k_c .
?c a ddigraph:Category .
?_e0 rdf:subject ?q ; rdf:predicate ddigraph:usesCodelist ; rdf:object ?l .
FILTER(STRSTARTS(STR(?_e0), "urn:ddigraph:relationship:"))
?_e1 rdf:subject ?l ; rdf:predicate ddigraph:hasCategory ; rdf:object ?c .
FILTER(STRSTARTS(STR(?_e1), "urn:ddigraph:relationship:"))
OPTIONAL { ?q ddigraph:name ?_p0 }
OPTIONAL { ?c rdfs:label|skos:prefLabel ?_p1 }
}
ORDER BY ASC(!BOUND(?_p0)) ASC(?_p0) ASC(!BOUND(?_t1)) ASC(?_t1) ASC(LCASE(COALESCE(?_l1, ""))) ASC(COALESCE(?_l1, ""))
An edge matches the lens's statement for each relationship, not the plain
triple. So two relationships between the same nodes give two rows, as in
Neo4j. The last column, (1 AS ?_row), is there because rdflib drops a
row whose every column is empty.
to_sql(query, dialect) and to_pgq(query) give the SQL text, for the
tables the SQL lens writes. See
PostgreSQL and DuckDB.
run(query, target) runs the query where your graph is, and gives the
same rows:
from ddigraph.query import run
run(query, memory_lens) # the reference evaluator
run(query, neo4j_lens) # Cypher 25 on Neo4j 2025 or later, Cypher 5 before
run(query, rdf_lens) # SPARQL, with rdflib
run(query, oxigraph_lens) # SPARQL, with Oxigraph
run(query, sql_lens) # SQL; SQL/PGQ on DuckDB with duckpgq loaded
run also takes a neo4j driver. Pass cypher="5" or cypher="25" to
choose the Cypher version yourself.
What a Query Can Say¶
| Part | Helpers | Meaning |
|---|---|---|
| Node | node("v", "Variable") |
A node with that type label; with no label, any :DDINode |
| Edge | edge("v", "USES_CONCEPT", "c") |
One relationship from v to c, as the IR directs it |
| Reach | edge("a", "BASED_ON", "b", hops=(1, 3)) |
b can be reached from a in 1 to 3 steps |
| Filter | compare, is_in, exists, missing |
A property compared with a literal, or tested |
| Logic | and_, or_, not_ |
Filters combined |
| Return | key("v"), prop("v", "name"), count() |
Keys and properties, or count(*) alone |
| Order | asc(term), desc(term) |
Sort by returned terms |
| Language | lang("v", "label") |
The language of a text property, in a filter |
A Query also takes distinct=True, limit=n and dataset_id="...". A
dataset ID keeps only the members of that dataset, and its Dataset node, for
each variable. The steps of a reach may pass through any node.
A filter compares with ==, !=, <, <=, > or >=:
from ddigraph.query import and_, compare, exists, lang, not_, prop
where = and_(
compare(prop("v", "name"), "==", "age"),
not_(compare(lang("v", "label"), "==", "fr")),
exists(prop("v", "label")),
)
The Rules Every Engine Follows¶
Rows Are a Multiset¶
An edge pattern gives one row for each relationship it matches. Two
relationships between the same two nodes give two rows. distinct=True
drops the repeats.
Matching is a homomorphism, as with SQL joins and SPARQL. Two edge patterns
may match the same relationship, and two variables may match the same node.
Cypher would forbid a relationship twice in one pattern, so ddigraph writes
each edge pattern as its own MATCH.
A Missing Value Is Unknown¶
A filter on a missing property is unknown, as in SQL. A row is kept only when its filter is true.
Filter, for a node with no name |
Result | Row kept? |
|---|---|---|
name == "age" |
unknown | no |
not (name == "age") |
unknown | no |
name == "age" or label exists (it does) |
true | yes |
name == "age" and label missing (it is not) |
false | no |
name missing |
true | yes |
exists and missing are never unknown.
Text and Languages¶
A text property compares by its string. Its language is a term of its own,
lang(var, name), which compares without regard to case: "EN" matches
en. Language tags ignore case in BCP 47, and Oxigraph stores them in
lower case. A text with no language has an unknown language.
A DDI-L text can hold several languages. A query reads the main one, the
one in name or label. The others are in name_translations and
name_translation_langs, which are lists.
A list property, such as external_references, takes exists and
missing only.
Order and Limit¶
order_by sorts by returned terms. Missing values come last, both
ascending and descending. A text sorts by its string, then by its language
in lower case, then by its language as written. So in ascending order, a
text with no language comes first, and EN comes before en. desc
reverses both.
limit needs an order over every returned term. Otherwise two engines
could keep different rows.
A Reach Must Be Distinct¶
A reach asks whether a walk of min to max relationships of a type joins
two nodes (1 <= min <= max <= 8). A walk may take one relationship more
than once, as SQL and SPARQL allow. Engines count the paths of a reach
differently, so a query with a reach must set distinct=True, and cannot
return count().
This query finds every construct an instrument reaches in one to three steps. In Cypher 5, a reach that starts at one step is a variable-length pattern:
CYPHER 5
MATCH (i:DDINode:Instrument)
MATCH (x:DDINode)
MATCH (i)-[:HAS_CONSTRUCT*1..3]->(x)
RETURN DISTINCT x.ddi_id AS `x.ddi_id`
ORDER BY `x.ddi_id`
A Cypher 5 variable-length pattern never takes a relationship twice. So a
reach that starts at two steps or more is written as one test per length,
each step its own MATCH. Cypher 25 can take a relationship twice with
REPEATABLE ELEMENTS, so it writes every reach as a quantified path. A
Neo4j 5 server cannot plan this one:
CYPHER 25
MATCH (i:DDINode:Instrument)
MATCH (x:DDINode)
MATCH REPEATABLE ELEMENTS (i)-[:HAS_CONSTRUCT]->{1,3}(x)
RETURN DISTINCT x.ddi_id AS `x.ddi_id`
ORDER BY `x.ddi_id`
SPARQL writes a reach as a union of fixed lengths: p, p/p, p/p/p.
SPARQL (rdflib and Oxigraph), and Cypher 5 when min is 2 or more, list
every walk of a reach. On data with cycles, the time grows fast with max:
each extra step can multiply it. So keep reaches short, and do not run long
ones over files you do not trust.
Labels After a Purge¶
A purge keeps a node that another dataset also holds, with all its type
labels and properties. Say a DDI-L file and a CDI file both hold one
category, and you purge the CDI dataset. A query for CDICategory still
finds the node, with its CDI properties, on every engine.
Where Engines Differ¶
Two cases give other rows on one engine:
- Oxigraph and language case. Oxigraph stores a language in lower case.
So
"x"@ENand"x"@enare one value there. Each comes back in the case BCP 47 recommends, such asenoren-GB. - Neo4j and characters above U+FFFF. Neo4j compares two strings by their
UTF-16 code units in
<,<=,>and>=. So a character above U+FFFF, such as a rare CJK character, comes before one from U+E000 to U+FFFF, such as a full-width letter. The other engines put it after. This holds for str and text properties, in Cypher 5 and in Cypher 25.order_byis not affected.
Typing Errors¶
A query is checked when you build it. A label must be one of the model's
labels, and a relationship type one of its types. A property must be one
the variable's label owns. With no label, some label must own it. A literal
must have the property's type. A wrong name raises ValueError, which
names it and the nearest valid name:
Unknown label 'QuestionItm'; did you mean 'QuestionItem'?
q:QuestionItem has no property 'questin_text'; did you mean 'question_text'?
l.code_count is an int property: compare it with an int, not '3'
A variable must be bound by a node pattern before an edge, a filter or a
return uses it. IN_DATASET is refused: use dataset_id instead.
Checking Every Engine: conform query¶
conform query writes each file of a corpus to each engine. It then draws
queries over the file's graph and runs each one on every engine. It
compares each engine's rows with the reference evaluator's:
python -m ddigraph.conform query --corpus tests/fixtures --generated 200 \
--lens memory neo4j rdf oxigraph
codebook_sample.xml -> memory: 0 differences in 200 queries
codebook_sample.xml -> neo4j (Cypher 5): 0 differences in 200 queries
codebook_sample.xml -> rdf: 0 differences in 200 queries
codebook_sample.xml -> oxigraph: 0 differences in 200 queries
...
Total: 0 differences in 8800 queries over 44 checks
This output comes from a Neo4j 5 server. On Neo4j 2025 or later, each file
also gets a neo4j (Cypher 25) line.
| Option | Default | What it sets |
|---|---|---|
--corpus DIR |
(required) | The folder of DDI files, read as conform run reads it |
--generated N |
100 |
The number of queries drawn over each file's graph |
--documents N |
0 |
Generated DDI documents to add, as conform run --generated adds |
--lens NAME ... |
every installed engine but neo4j and postgres |
The engines: memory, neo4j, rdf, oxigraph, postgres, duckdb |
--neo4j-uri URI |
DDIGRAPH_NEO4J_URI |
The Neo4j server |
--postgres-uri URI |
DDIGRAPH_POSTGRES_URI |
The PostgreSQL server |
--duckdb-extension-directory DIR |
DuckDB's own | Where DuckDB finds duckpgq, to run each query as SQL/PGQ too |
--json |
off | Print the counts as JSON |
The queries cover every form: one to three edges, reaches, filters with literals drawn from the graph, every return, order and limit. The same file gives the same queries every run. For each difference, the command prints the query as Cypher and both results. It exits with 1 when there is any difference.
The neo4j engine empties its database
Like conform run --lens neo4j, it deletes every node in the database
before it writes each file. Point it only at a server you can empty. On
Neo4j 2025 or later, it runs each query in Cypher 5 and in Cypher 25.