Skip to content

Cheat sheet

The commands and Python calls the curriculum teaches, on one page. Every block after the install step runs in the docs tests, from the root of a clone of the repository, as in Module 2. A block that needs a server says so. The CLI reference and the user guide have every option.

Install

pip install "ddigraph[rdf,shacl,networkx,pandas,duckdb,oxigraph]"
git clone https://github.com/pbisson44/ddigraph.git
cd ddigraph
Extra Gives you
rdf RDF export and reading back (rdflib)
shacl SHACL shapes and validation (pyshacl)
networkx to_networkx and the NetworkX lens
pandas to_dataframes, CSV and Excel
duckdb the SQL lens on DuckDB, and SQL/PGQ with duckpgq
postgres the SQL lens on PostgreSQL (psycopg)
oxigraph the Oxigraph lens
gremlin write_gremlin (gremlinpython)
api, arrow ddigraph serve, and Arrow and Arrow Flight

Look at a file

ddigraph detect tests/fixtures/lfs_codebook.xml
ddigraph preview tests/fixtures/lfs_codebook.xml --limit 2
ddigraph preview tests/fixtures/lfs_lifecycle.xml --format mermaid
ddigraph preview tests/fixtures/lfs_cdi.xml --format html -o preview.html
import ddigraph

print(ddigraph.detect("tests/fixtures/lfs_lifecycle.xml"))

Read the graph in Python

from ddigraph import ir

for chunk in ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id="survey"):
    for node in chunk.nodes:
        print(node.label, node.key)
    for edge in chunk.relationships:
        print(edge.type, edge.start, "->", edge.end)

One question on each backend

Pick your backend in the tabs. Each tab loads the survey's codebook, lfs_codebook.xml, and asks for its variables, each with its name and label: the start of a data dictionary. All eight print the same seven lines. The site remembers your pick: every tabbed box in the course then opens on that backend.

Runs in your Python process, with nothing to install.

from ddigraph import ir
from ddigraph import query as q
from ddigraph.lens.memory import MemoryLens

variables = q.Query(
    match=[q.node("v", "Variable")],
    returns=[q.prop("v", "name"), q.prop("v", "label")],
    order_by=[q.asc(q.prop("v", "name"))],
    dataset_id="cheat-sheet",
)

lens = MemoryLens()
chunks = ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="cheat-sheet")
lens.write(chunks, dataset_id="cheat-sheet")
for name, label in q.run(variables, lens):
    print(name, label.value)
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

Needs a Neo4j server and the variables from Module 2.

from neo4j import GraphDatabase

import ddigraph
from ddigraph import query as q
from ddigraph.config import Settings

variables = q.Query(
    match=[q.node("v", "Variable")],
    returns=[q.prop("v", "name"), q.prop("v", "label")],
    order_by=[q.asc(q.prop("v", "name"))],
    dataset_id="cheat-sheet",
)

ddigraph.bootstrap()
ddigraph.load("tests/fixtures/lfs_codebook.xml", dataset_id="cheat-sheet", replace=True)

settings = Settings()
auth = (settings.neo4j_user, settings.neo4j_password.get_secret_value())
with GraphDatabase.driver(settings.neo4j_uri, auth=auth) as driver:
    for name, label in q.run(variables, driver):
        print(name, label.value)
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

Needs a Gremlin server. ddigraph only writes to Gremlin, so you ask with a traversal. The vertex label is the node's type, and the node's own label is the property ddi_label.

from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.process.anonymous_traversal import traversal

from ddigraph.backends.gremlin import write_gremlin

connection = DriverRemoteConnection("ws://localhost:8182/gremlin", "g")
g = traversal().with_(connection)
g.V().has("Dataset", "dataset_id", "cheat-sheet").in_("IN_DATASET").drop().iterate()
write_gremlin(g, "tests/fixtures/lfs_codebook.xml", dataset_id="cheat-sheet")

members = g.V().has("Dataset", "dataset_id", "cheat-sheet").in_("IN_DATASET")
variables = members.has_label("Variable").order().by("name")
for row in variables.project("name", "label").by("name").by("ddi_label").to_list():
    print(row["name"], row["label"])
connection.close()
AGE Age in completed years
AGEGRP Age group
EDUC Highest level of education
HOURS Usual weekly hours in the main job
ILOSTAT Labour force status (ILO)
REGION Region of residence
SEX Sex of the person

Needs a PostgreSQL server. Put your own address in connect. The server keeps what earlier runs wrote, so purge empties the dataset first.

import psycopg

from ddigraph import ir
from ddigraph import query as q
from ddigraph.lens.sql import SQLLens

variables = q.Query(
    match=[q.node("v", "Variable")],
    returns=[q.prop("v", "name"), q.prop("v", "label")],
    order_by=[q.asc(q.prop("v", "name"))],
    dataset_id="cheat-sheet",
)

with psycopg.connect("postgresql://postgres:postgres@localhost:5432/postgres") as connection:
    lens = SQLLens(connection)
    lens.ddl()
    lens.purge("cheat-sheet")
    chunks = ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="cheat-sheet")
    lens.write(chunks, dataset_id="cheat-sheet")
    for name, label in q.run(variables, lens):
        print(name, label.value)
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

Runs in your Python process, with the duckdb extra.

import duckdb

from ddigraph import ir
from ddigraph import query as q
from ddigraph.lens.sql import SQLLens

variables = q.Query(
    match=[q.node("v", "Variable")],
    returns=[q.prop("v", "name"), q.prop("v", "label")],
    order_by=[q.asc(q.prop("v", "name"))],
    dataset_id="cheat-sheet",
)

lens = SQLLens(duckdb.connect())
lens.ddl()
chunks = ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="cheat-sheet")
lens.write(chunks, dataset_id="cheat-sheet")
for name, label in q.run(variables, lens):
    print(name, label.value)
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

Runs in your Python process, with the oxigraph extra. q.run sends SPARQL.

from ddigraph import ir
from ddigraph import query as q
from ddigraph.lens.oxigraph import OxigraphLens

variables = q.Query(
    match=[q.node("v", "Variable")],
    returns=[q.prop("v", "name"), q.prop("v", "label")],
    order_by=[q.asc(q.prop("v", "name"))],
    dataset_id="cheat-sheet",
)

lens = OxigraphLens()
chunks = ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="cheat-sheet")
lens.write(chunks, dataset_id="cheat-sheet")
for name, label in q.run(variables, lens):
    print(name, label.value)
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

Runs in your Python process. ddigraph.query does not run on NetworkX, so you ask in Python.

from ddigraph.backends.networkx import to_networkx

graph = to_networkx("tests/fixtures/lfs_codebook.xml")
variables = [data for _, data in graph.nodes(data=True) if "Variable" in data["node_labels"]]
for data in sorted(variables, key=lambda data: data["name"]):
    print(data["name"], data["label"])
AGE Age in completed years
AGEGRP Age group
EDUC Highest level of education
HOURS Usual weekly hours in the main job
ILOSTAT Labour force status (ILO)
REGION Region of residence
SEX Sex of the person

Runs in your Python process. ddigraph.query does not run on pandas, so you ask in Python.

from ddigraph.backends.pandas import to_dataframes

frames = to_dataframes("tests/fixtures/lfs_codebook.xml")
variables = frames.of("Variable").sort_values("name")
for name, label in zip(variables["name"], variables["label"]):
    print(name, label)
AGE Age in completed years
AGEGRP Age group
EDUC Highest level of education
HOURS Usual weekly hours in the main job
ILOSTAT Labour force status (ILO)
REGION Region of residence
SEX Sex of the person

q.run takes a MemoryLens, a Neo4jLens or driver, an RDFLens, an OxigraphLens or an SQLLens. It gives a label back as a Text, which also holds its language, so the code prints its .value. Bind each node with q.node before an q.edge uses it, and return q.count() on its own. To see the text an engine runs, compile the query yourself (Module 10):

from ddigraph import query as q

variables = q.Query(
    match=[q.node("v", "Variable")],
    returns=[q.prop("v", "name"), q.prop("v", "label")],
    order_by=[q.asc(q.prop("v", "name"))],
    dataset_id="cheat-sheet",
)
text, parameters = q.to_cypher(variables, "5")
print(text)
sql, parameters = q.to_sql(variables, "duckdb")
sparql = q.to_sparql(variables)

Validate

ddigraph validate tests/fixtures/lfs_cdi.xml
ddigraph validate tests/fixtures/lfs_lifecycle.xml --shapes
ddigraph shapes -o shapes.ttl
ddigraph export tests/fixtures/lfs_lifecycle.xml -o survey.ttl --format turtle
ddigraph validate survey.ttl

ddigraph validate checks XML against the official XSD, and RDF against the SHACL shapes. With --shapes, it checks an XML file's graph against the shapes too, in one step. The survey's files pass both checks. Module 6 shows files that fail, and why.

Neo4j (needs a server)

Set DDIGRAPH_NEO4J_URI, DDIGRAPH_NEO4J_USER and DDIGRAPH_NEO4J_PASSWORD first (Module 2). This loads the survey twice: as a codebook, and as DDI-L.

ddigraph bootstrap
ddigraph load tests/fixtures/lfs_codebook.xml --dataset-id cheat-codebook --replace
ddigraph load tests/fixtures/lfs_lifecycle.xml --dataset-id cheat-survey --replace
MATCH (:Dataset {dataset_id: 'cheat-codebook'})<-[:IN_DATASET]-(v:Variable)
OPTIONAL MATCH (v)-[:ASKED_AS]->(question:Question)
RETURN v.name, v.label, question.question_text
ORDER BY v.name

The first query lists the codebook's variables, each with the text of its question. AGEGRP and ILOSTAT are derived, so they have none. In DDI-L, a code list reaches its categories through its codes. This query lists each code list of the survey with its categories, in the order of their codes:

MATCH (:Dataset {dataset_id: 'cheat-survey'})<-[:IN_DATASET]-(cl:CodeList)
MATCH (cl)-[step:CONTAINS]->(:Code)-[:HAS_CATEGORY]->(cat:Category)
WITH cl, cat ORDER BY step.ordinal
RETURN cl.label, collect(cat.label)
ORDER BY cl.label

Export without a database

ddigraph export tests/fixtures/lfs_lifecycle.xml -o survey.ttl --format turtle
ddigraph export tests/fixtures/lfs_cdi.xml -o survey.jsonld --format jsonld
ddigraph export tests/fixtures/lfs_codebook.xml -o codebook-csv --format csv

History

ddigraph store add tests/fixtures/lfs_codebook.xml --store history --dataset-id lfs
ddigraph store list --store history
ddigraph store show lfs --store history

Where each topic is taught

Topic Module
DDI flavors, and why a graph 1
detect and preview 3
Nodes, keys, identity, stubs 4
ddigraph.query 5, 10
XSD and SHACL 6
Neo4j 7, 17
RDF, SKOS and XKOS 8, 9, 21
The store, history and diffs 11
Lenses and your own pipeline 12
Big, broken and untrusted files 13
Language models 14, 15
NetworkX, pandas, SQL, Gremlin 18, 19, 20, 22
The HTTP API and Arrow Flight 23