Module 22: Gremlin¶
Learning objectives
By the end of this module, you can:
- O1. Connect to Gremlin Server with gremlinpython, write a DDI file with
write_gremlin, and read itsGremlinResult. - O2. Explain why ddigraph only writes to Gremlin, and what that means for
ddigraph.queryand for reading the graph back. - O3. Predict what a write puts in the graph: vertices upserted by
key,IN_DATASETedges,ddi_labelforlabel, and lists joined with|. - O4. Write your own traversals: count one dataset's vertices by label, find a question's variables, and list a code list's categories through its codes.
- O5. Remove one dataset from the graph without touching the vertices another dataset shares.
Prerequisites: Module 7
Time: 40 min self-paced / 55 min instructor-led.
Needs: Gremlin Server 3.8, in Docker (tinkerpop/gremlin-server:3.8.2; Module 2 starts it), and the gremlin extra. The Neo4j tabs, which are optional, need Neo4j 5 as in Module 7.
New in this module: ddigraph.backends.gremlin.write_gremlin, GremlinResult, DriverRemoteConnection, traversal().with_(), the steps V, has, in_, out, out_e, in_v, where, order, group_count, project, union, not_ and drop
1. Gremlin and the TinkerPop family¶
Apache TinkerPop is a common layer for
graph databases. Its query language is Gremlin. A Gremlin query is a
traversal: a chain of steps that walks the graph. g.V() starts at
every vertex, .has(...) keeps some of them, .out(...) follows edges
forward, and so on.
The graph is a property graph, as in Neo4j (Module 7). A vertex is a node, an edge joins two vertices, and each has a label and properties. Many databases speak Gremlin:
- TinkerGraph, an in-memory graph inside Gremlin Server, for tests and for this module;
- JanusGraph, an open-source graph for large, spread-out data;
- Amazon Neptune, a managed graph on AWS;
- Azure Cosmos DB, through its Gremlin API.
ddigraph writes to any of them in the same way. The connection details differ: the Gremlin backend page shows them for JanusGraph, Neptune and Cosmos DB.
Start Gremlin Server, if Module 2 did not already, and install the
extra. The server listens at ws://localhost:8182/gremlin:
docker run -d --name ddigraph-gremlin -p 8182:8182 tinkerpop/gremlin-server:3.8.2
pip install "ddigraph[gremlin]"
2. Connect, and write a file¶
gremlinpython is the Python client for Gremlin. DriverRemoteConnection
opens a WebSocket to the server, and traversal().with_(connection) gives
you g, the start of every traversal. write_gremlin(g, path) then reads
a DDI file and writes it. The file here is the course's sample survey, a
Labour Force Survey in DDI-Lifecycle 3.3: its questionnaire, questions,
code lists and variables.
Each script in this module starts by removing what an earlier run wrote,
so you can run it again. The drop_dataset function does that. Section 6
explains why it is written this way.
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.process.anonymous_traversal import traversal
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.traversal import P
from ddigraph.backends.gremlin import write_gremlin
def drop_dataset(g, dataset_id):
"""Drop a dataset's vertices, but keep those another dataset also holds."""
shared = __.out("IN_DATASET").has("dataset_id", P.neq(dataset_id))
g.V().has("Dataset", "dataset_id", dataset_id).in_("IN_DATASET").not_(shared).drop().iterate()
g.V().has("Dataset", "dataset_id", dataset_id).drop().iterate()
connection = DriverRemoteConnection("ws://localhost:8182/gremlin", "g")
g = traversal().with_(connection)
drop_dataset(g, "m22-survey")
for attempt in ("first", "second"):
result = write_gremlin(g, "tests/fixtures/lfs_lifecycle.xml", dataset_id="m22-survey")
members = g.V().has("Dataset", "dataset_id", "m22-survey").in_("IN_DATASET").count().next()
print(attempt, "write:", result, "->", members, "members")
connection.close()
Expected output:
first write: GremlinResult(nodes=87, relationships=108, memberships=86, skipped=0) -> 86 members
second write: GremlinResult(nodes=87, relationships=108, memberships=86, skipped=0) -> 86 members
The GremlinResult counts what the write sent:
nodes: vertices, the Dataset vertex included;relationships: the file's edges;memberships: theIN_DATASETedges, one from each node to the Dataset vertex;skipped: edges not written because an end vertex was missing. It should be 0.
The 87 vertices are the survey's 86 nodes and the Dataset vertex. The second write gives the same counts, and the dataset still has 86 members. Each write is an upsert: it finds a vertex or edge first, and creates it only if it is missing. So loading a file twice changes nothing.
Read the traversal that counts the members from left to right: start at
the vertices with label Dataset and dataset_id m22-survey, step back
along incoming IN_DATASET edges, count. Python spells the step in_,
because in is a Python keyword. .next() runs the traversal and gives
its one result. .to_list() gives all of them, and .iterate() runs a
traversal for its effect alone, as drop does.
Each step you add changes the traversal object itself, and a traversal
runs only once. So start a new one from g for each question, as the
loop above does, rather than reuse a variable that already ran.
3. A one-way street¶
ddigraph writes to Gremlin. It has no reader for it. The module
ddigraph.backends.gremlin holds write_gremlin and GremlinResult, and
nothing that reads a vertex back into ddigraph's graph.
So Gremlin is not a target for ddigraph.query. That module turns one
query into Cypher, SPARQL or SQL (Module 10),
but it has no Gremlin translation. Give run a traversal source and it
says so:
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.process.anonymous_traversal import traversal
from ddigraph import ir
from ddigraph.lens.memory import MemoryLens
from ddigraph.query import Query, count, node, run
query = Query(match=[node("v", "Variable")], returns=[count()])
connection = DriverRemoteConnection("ws://localhost:8182/gremlin", "g")
g = traversal().with_(connection)
try:
run(query, g)
except TypeError as error:
print("TypeError:", error)
connection.close()
lens = MemoryLens()
lens.write(
ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m22-codebook"),
dataset_id="m22-codebook",
)
print("in memory:", run(query, lens))
Expected output:
TypeError: Cannot run a query on a GraphTraversalSource
in memory: [(7,)]
The same query, run on the survey's Codebook file in memory, counts its 7 variables.
This shapes how you work with Gremlin:
- The DDI file stays the source. To rebuild the graph, write the file
again. To check what ddigraph wrote, read the file with
ir.parseor a lens that has a reader. - Questions to the Gremlin graph are your own traversals. Sections 5 and 6 write some.
ddigraph.queryruns elsewhere. Run it on the same file in memory, as above, or on Neo4j, SQL or an RDF store.
4. What the write puts in the graph¶
The write follows a few rules, so that the graph works the same on every Gremlin database:
- Every vertex has a
key. It is the node's key: 32 hex characters, the same as in Neo4j and in every other backend. The writer finds a vertex by it, withg.V().has("key", ...). The vertex label is the node's type, andidentityholds the node's identity as text. - Each node joins its dataset. An
IN_DATASETedge goes from each node to the Dataset vertex. It carries thesourcefile, itsflavorand thelinethe node came from. labelbecomesddi_label. Some databases read a property calledlabelas the vertex's own label, and Cosmos DB refuses it. A text propertypalso getsp_langwhen it has a language.- A list becomes one string, its items joined with
|. Databases store lists in too many different ways to rely on.
The scripts below write the survey's Codebook file. First they give the
variable REGION two external references, which ddigraph reads as a
list: the URNs of its concept and its universe in the survey's DDI-L
file. Then they print that node and its IN_DATASET edge. The Neo4j tab
loads the same file into Neo4j, as in Module 7, so you can compare:
from pathlib import Path
from neo4j import GraphDatabase
import ddigraph
from ddigraph.config import Settings
# Give the variable REGION two references: a list property
xml = Path("tests/fixtures/lfs_codebook.xml").read_text(encoding="utf-8")
label = "<labl>Region of residence</labl>"
references = (
"<ConceptReference><URN>urn:ddi:example.nso:concept-geography:1</URN></ConceptReference>"
"<UniverseReference><URN>urn:ddi:example.nso:universe-persons15:1</URN></UniverseReference>"
)
Path("codebook.xml").write_text(xml.replace(label, label + references))
ddigraph.bootstrap()
ddigraph.load("codebook.xml", dataset_id="m22-codebook", replace=True)
settings = Settings()
auth = (settings.neo4j_user, settings.neo4j_password.get_secret_value())
with GraphDatabase.driver(settings.neo4j_uri, auth=auth) as driver:
records, _, _ = driver.execute_query(
"""
MATCH (v:Variable {name: 'REGION'})-[m:IN_DATASET]->(:Dataset {dataset_id: $dataset})
RETURN v.key AS key, v.identity AS identity, v.label AS label,
v.external_references AS external_references, properties(m) AS membership
""",
dataset="m22-codebook",
)
node = records[0]
for name in ("key", "identity", "label", "external_references"):
print(name, "=", node[name])
print("IN_DATASET:", sorted(node["membership"].items()))
key = c44d23708f187318f27abda064fa0aa2
identity = urn:ddigraph:scoped:m22-codebook:V4
label = Region of residence
external_references = ['urn:ddi:example.nso:concept-geography:1', 'urn:ddi:example.nso:universe-persons15:1']
IN_DATASET: [('flavor', 'codebook'), ('line', 73), ('source', 'codebook.xml')]
Neo4j keeps the property name label, and stores the references as a
real list.
from pathlib import Path
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.process.anonymous_traversal import traversal
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.traversal import P
from ddigraph.backends.gremlin import write_gremlin
def drop_dataset(g, dataset_id):
"""Drop a dataset's vertices, but keep those another dataset also holds."""
shared = __.out("IN_DATASET").has("dataset_id", P.neq(dataset_id))
g.V().has("Dataset", "dataset_id", dataset_id).in_("IN_DATASET").not_(shared).drop().iterate()
g.V().has("Dataset", "dataset_id", dataset_id).drop().iterate()
# Give the variable REGION two references: a list property
xml = Path("tests/fixtures/lfs_codebook.xml").read_text(encoding="utf-8")
label = "<labl>Region of residence</labl>"
references = (
"<ConceptReference><URN>urn:ddi:example.nso:concept-geography:1</URN></ConceptReference>"
"<UniverseReference><URN>urn:ddi:example.nso:universe-persons15:1</URN></UniverseReference>"
)
Path("codebook.xml").write_text(xml.replace(label, label + references))
connection = DriverRemoteConnection("ws://localhost:8182/gremlin", "g")
g = traversal().with_(connection)
drop_dataset(g, "m22-codebook")
write_gremlin(g, "codebook.xml", dataset_id="m22-codebook")
region = g.V().has("Variable", "name", "REGION").has("dataset_id", "m22-codebook")
vertex = region.value_map().by(__.unfold()).next()
for name in ("key", "identity", "ddi_label", "external_references"):
print(name, "=", vertex[name])
membership = (
g.V().has("Variable", "name", "REGION").has("dataset_id", "m22-codebook").out_e("IN_DATASET")
)
print("IN_DATASET:", sorted(membership.value_map().next().items()))
connection.close()
key = c44d23708f187318f27abda064fa0aa2
identity = urn:ddigraph:scoped:m22-codebook:V4
ddi_label = Region of residence
external_references = urn:ddi:example.nso:concept-geography:1|urn:ddi:example.nso:universe-persons15:1
IN_DATASET: [('flavor', 'codebook'), ('line', 73), ('source', 'codebook.xml')]
Two differences from Neo4j: the label is in ddi_label, and the two
references are one string, joined with |. To get the list back,
split it: value.split("|").
The key, the identity and the membership are the same on both: it is one
graph. In the Gremlin tab, value_map() gives each property as a list,
since a Gremlin property can hold several values. .by(__.unfold())
takes each value out of its list. __ starts an anonymous traversal: a
piece of traversal used inside a step, here inside by. The key depends
on the dataset ID, because a Codebook ID is only unique inside its file.
5. Your own traversals¶
Here are three questions you will often ask. Each starts at one dataset's members, so it never mixes in another module's data. Each tab asks the same question of another backend, and prints the same answer.
Count the vertices by label. In Gremlin, group_count().by(T.label)
groups the vertices by label and counts each group:
from neo4j import GraphDatabase
import ddigraph
from ddigraph.config import Settings
ddigraph.bootstrap()
ddigraph.load("tests/fixtures/lfs_codebook.xml", dataset_id="m22-codebook", replace=True)
settings = Settings()
auth = (settings.neo4j_user, settings.neo4j_password.get_secret_value())
with GraphDatabase.driver(settings.neo4j_uri, auth=auth) as driver:
records, _, _ = driver.execute_query(
"""
MATCH (n)-[:IN_DATASET]->(:Dataset {dataset_id: $dataset})
UNWIND [label IN labels(n) WHERE label <> 'DDINode'] AS label
RETURN label, count(*) AS n
ORDER BY n DESC, label
LIMIT 5
""",
dataset="m22-codebook",
)
for record in records:
print(record["label"], record["n"])
DDIGenericIdentifiable 26
Category 21
Concept 7
Variable 7
Question 5
Every node in Neo4j also has the label DDINode, so the query leaves
it out.
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.process.anonymous_traversal import traversal
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.traversal import P, T
from ddigraph.backends.gremlin import write_gremlin
def drop_dataset(g, dataset_id):
"""Drop a dataset's vertices, but keep those another dataset also holds."""
shared = __.out("IN_DATASET").has("dataset_id", P.neq(dataset_id))
g.V().has("Dataset", "dataset_id", dataset_id).in_("IN_DATASET").not_(shared).drop().iterate()
g.V().has("Dataset", "dataset_id", dataset_id).drop().iterate()
connection = DriverRemoteConnection("ws://localhost:8182/gremlin", "g")
g = traversal().with_(connection)
drop_dataset(g, "m22-codebook")
write_gremlin(g, "tests/fixtures/lfs_codebook.xml", dataset_id="m22-codebook")
members = g.V().has("Dataset", "dataset_id", "m22-codebook").in_("IN_DATASET")
counts = members.group_count().by(T.label).next()
for label, n in sorted(counts.items(), key=lambda item: (-item[1], item[0]))[:5]:
print(label, n)
connection.close()
DDIGenericIdentifiable 26
Category 21
Concept 7
Variable 7
Question 5
A vertex has one label, its type, so there is nothing to leave out. The sorting happens in Python, on the map Gremlin returns.
import duckdb
from ddigraph import ir
from ddigraph.lens.sql import SQLLens
lens = SQLLens(duckdb.connect()) # a DuckDB database in memory
stream = ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m22-codebook")
lens.write(stream, dataset_id="m22-codebook")
rows = lens.fetch("""
SELECT l.type_label, count(*) AS n
FROM ddigraph_memberships AS m
JOIN ddigraph_labels AS l ON l.key = m.key AND l.flavor = m.flavor
WHERE m.dataset = 'm22-codebook' AND l.type_label <> 'Dataset'
GROUP BY l.type_label
ORDER BY n DESC, l.type_label
LIMIT 5
""")
for label, n in rows:
print(label, n)
DDIGenericIdentifiable 26
Category 21
Concept 7
Variable 7
Question 5
The SQL lens keeps the graph in plain tables: one row per membership and one per type label. Module 20 shows them all.
The counts show how DDI-Codebook works. Each of the 7 variables has its
own concept, so there are 7 Concept vertices for 5 concepts:
"Demographic characteristics" appears three times, for SEX, AGE and
AGEGRP. A Codebook repeats text, where DDI-L stores a concept once and
points at it. Only 5 variables have a Question: AGEGRP and ILOSTAT are
derived from other answers, so no one is asked them.
Find a question's variables. In DDI-L, a variable
REFERENCES_QUESTION each question it comes from, so the variables sit
at the start of the edge. In Gremlin, in_("REFERENCES_QUESTION") walks
back to them. A question construct, the question's place in the
questionnaire, uses the same edge type, so has_label("Variable") keeps
the variables alone. A question's vertex can also be shared with another
dataset (Section 6), which may add variables of its own. So where keeps
only the variables of this dataset. project builds one result per
question, with a value for each name you give it, in order:
from neo4j import GraphDatabase
import ddigraph
from ddigraph.config import Settings
ddigraph.bootstrap()
ddigraph.load("tests/fixtures/lfs_lifecycle.xml", dataset_id="m22-survey", replace=True)
settings = Settings()
auth = (settings.neo4j_user, settings.neo4j_password.get_secret_value())
with GraphDatabase.driver(settings.neo4j_uri, auth=auth) as driver:
records, _, _ = driver.execute_query(
"""
MATCH (q:QuestionItem)-[:IN_DATASET]->(survey:Dataset {dataset_id: $dataset})
RETURN q.name AS question,
[(v:Variable)-[:REFERENCES_QUESTION]->(q)
WHERE (v)-[:IN_DATASET]->(survey) | v.name] AS variables
ORDER BY question
""",
dataset="m22-survey",
)
for record in records:
print(record["question"], "->", sorted(record["variables"]))
AGE -> ['AGE', 'AGEGRP']
AVAIL -> ['ILOSTAT']
EDUC -> ['EDUC']
HOURS -> ['HOURS']
LOOK -> ['ILOSTAT']
REGION -> ['REGION']
SEX -> ['SEX']
WORK -> ['ILOSTAT']
The pattern in square brackets gathers the variables into a list, one
row per question. Its WHERE keeps the variables of this dataset.
Cypher gives the list in no set order, so Python sorts it.
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.process.anonymous_traversal import traversal
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.traversal import P
from ddigraph.backends.gremlin import write_gremlin
def drop_dataset(g, dataset_id):
"""Drop a dataset's vertices, but keep those another dataset also holds."""
shared = __.out("IN_DATASET").has("dataset_id", P.neq(dataset_id))
g.V().has("Dataset", "dataset_id", dataset_id).in_("IN_DATASET").not_(shared).drop().iterate()
g.V().has("Dataset", "dataset_id", dataset_id).drop().iterate()
connection = DriverRemoteConnection("ws://localhost:8182/gremlin", "g")
g = traversal().with_(connection)
drop_dataset(g, "m22-survey")
write_gremlin(g, "tests/fixtures/lfs_lifecycle.xml", dataset_id="m22-survey")
questions = (
g.V()
.has("Dataset", "dataset_id", "m22-survey")
.in_("IN_DATASET")
.has_label("QuestionItem")
.order()
.by("name")
.project("question", "variables")
.by("name")
.by(
__.in_("REFERENCES_QUESTION")
.has_label("Variable")
.where(__.out("IN_DATASET").has("dataset_id", "m22-survey"))
.values("name")
.order()
.fold()
)
)
for row in questions.to_list():
print(row["question"], "->", row["variables"])
connection.close()
AGE -> ['AGE', 'AGEGRP']
AVAIL -> ['ILOSTAT']
EDUC -> ['EDUC']
HOURS -> ['HOURS']
LOOK -> ['ILOSTAT']
REGION -> ['REGION']
SEX -> ['SEX']
WORK -> ['ILOSTAT']
where keeps a vertex only if the traversal inside it finds
something: here, an IN_DATASET edge to this dataset. order() sorts
what reaches it, and .by("name") says by which property. fold()
gathers the names into one list, so a question with two variables
still gives one row.
The answer shows how the survey derives its variables. The question AGE feeds two variables: AGE itself, and AGEGRP, the age group made from it. Three questions, WORK, LOOK and AVAIL, feed one variable: ILOSTAT, the labour force status.
List a code list's categories through its codes. In DDI 3.2 and 3.3,
each code has an ID of its own, so it is a node: the code list CONTAINS
the code, and the code has the HAS_CATEGORY edge. In DDI 3.1, a code has
no ID. It is part of its code list, and the HAS_CATEGORY edge starts at
the code list. The survey is DDI 3.3, so only the first path finds
categories here, but a query that works on any DDI-L file follows both.
Order matters too. A code list keeps its categories in a set order, such
as the age groups from youngest to oldest. Each of these edges holds its
place in that order in its ordinal:
from neo4j import GraphDatabase
import ddigraph
from ddigraph.config import Settings
ddigraph.bootstrap()
ddigraph.load("tests/fixtures/lfs_lifecycle.xml", dataset_id="m22-survey", replace=True)
settings = Settings()
auth = (settings.neo4j_user, settings.neo4j_password.get_secret_value())
with GraphDatabase.driver(settings.neo4j_uri, auth=auth) as driver:
records, _, _ = driver.execute_query(
"""
MATCH (cl:CodeList)-[:IN_DATASET]->(:Dataset {dataset_id: $dataset})
MATCH (cl)-[step:CONTAINS|HAS_CATEGORY]->()-[:HAS_CATEGORY*0..1]->(cat:Category)
WITH cl, cat
ORDER BY step.ordinal
RETURN cl.label AS code_list, collect(cat.label) AS categories
ORDER BY code_list
""",
dataset="m22-survey",
)
for record in records:
print(record["code_list"], "->", record["categories"])
Age group -> ['15-24', '25-34', '35-44', '45-54', '55-64', '65 and over']
Highest level of education -> ['Primary or less (ISCED 0-1)', 'Lower secondary (ISCED 2)', 'Upper secondary (ISCED 3)', 'Post-secondary non-tertiary (ISCED 4)', 'Tertiary (ISCED 5-8)']
Labour force status (ILO) -> ['Employed', 'Unemployed', 'Not in the labour force']
Region -> ['Capital region', 'North', 'South', 'East', 'West']
Sex -> ['Male', 'Female']
Yes or no -> ['Yes', 'No']
The first step, step, is either CONTAINS, to a code, or
HAS_CATEGORY, straight to a category. [:HAS_CATEGORY*0..1] then
takes one more step from a code, or none from a category. Sorting the
rows by step.ordinal before collect keeps each list in its order.
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.process.anonymous_traversal import traversal
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.traversal import P
from ddigraph.backends.gremlin import write_gremlin
def drop_dataset(g, dataset_id):
"""Drop a dataset's vertices, but keep those another dataset also holds."""
shared = __.out("IN_DATASET").has("dataset_id", P.neq(dataset_id))
g.V().has("Dataset", "dataset_id", dataset_id).in_("IN_DATASET").not_(shared).drop().iterate()
g.V().has("Dataset", "dataset_id", dataset_id).drop().iterate()
connection = DriverRemoteConnection("ws://localhost:8182/gremlin", "g")
g = traversal().with_(connection)
drop_dataset(g, "m22-survey")
write_gremlin(g, "tests/fixtures/lfs_lifecycle.xml", dataset_id="m22-survey")
code_lists = (
g.V()
.has("Dataset", "dataset_id", "m22-survey")
.in_("IN_DATASET")
.has_label("CodeList")
.order()
.by("ddi_label")
.project("code_list", "categories")
.by("ddi_label")
.by(
__.union(
__.out_e("HAS_CATEGORY").order().by("ordinal").in_v(),
__.out_e("CONTAINS").order().by("ordinal").in_v().out("HAS_CATEGORY"),
)
.values("ddi_label")
.fold()
)
)
for row in code_lists.to_list():
print(row["code_list"], "->", row["categories"])
connection.close()
Age group -> ['15-24', '25-34', '35-44', '45-54', '55-64', '65 and over']
Highest level of education -> ['Primary or less (ISCED 0-1)', 'Lower secondary (ISCED 2)', 'Upper secondary (ISCED 3)', 'Post-secondary non-tertiary (ISCED 4)', 'Tertiary (ISCED 5-8)']
Labour force status (ILO) -> ['Employed', 'Unemployed', 'Not in the labour force']
Region -> ['Capital region', 'North', 'South', 'East', 'West']
Sex -> ['Male', 'Female']
Yes or no -> ['Yes', 'No']
union follows both paths: the categories one HAS_CATEGORY step
away, plus those one CONTAINS step and one HAS_CATEGORY step away.
In each path, out_e stops on the edges instead of walking past them,
so order().by("ordinal") can sort them. in_v then steps to the
vertex each edge points at. Without the sort, Gremlin gives edges in no
set order, and Region could come out as South, East, West, Capital
region, North. The labels are in ddi_label here, where Neo4j has
label.
The code list Yes or no appears once, though three questions use it:
WORK, LOOK and AVAIL. DDI-L stores it once, and each question points at
it. The Gremlin backend page has more traversals, such as the path from a
questionnaire to its questions.
6. Remove a dataset, and keep what others share¶
A vertex's key comes from its identity. A DDI-L or DDI-CDI object has a
URN, which is the same in every file that holds it. So when two datasets
hold the same object, they share one vertex, with an IN_DATASET
edge to each Dataset vertex. A Codebook ID has no URN, so its key
includes the dataset ID, and two datasets never share it.
That is why drop_dataset does not drop every member. It drops the
members with no IN_DATASET edge to another dataset, then the Dataset
vertex. A shared vertex loses only its edge to the dropped dataset. Watch
it happen:
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.process.anonymous_traversal import traversal
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.traversal import P
from ddigraph.backends.gremlin import write_gremlin
def drop_dataset(g, dataset_id):
"""Drop a dataset's vertices, but keep those another dataset also holds."""
shared = __.out("IN_DATASET").has("dataset_id", P.neq(dataset_id))
g.V().has("Dataset", "dataset_id", dataset_id).in_("IN_DATASET").not_(shared).drop().iterate()
g.V().has("Dataset", "dataset_id", dataset_id).drop().iterate()
connection = DriverRemoteConnection("ws://localhost:8182/gremlin", "g")
g = traversal().with_(connection)
for dataset_id in ("m22-survey", "m22-copy"):
drop_dataset(g, dataset_id)
write_gremlin(g, "tests/fixtures/lfs_lifecycle.xml", dataset_id=dataset_id)
question = "urn:ddi:example.nso:q-work:1"
print("question vertices:", g.V().has("QuestionItem", "urn", question).count().next())
holders = g.V().has("QuestionItem", "urn", question).out("IN_DATASET").values("dataset_id")
# Keep this module's datasets: other people may load the same file
print("its datasets:", sorted(d for d in holders.to_list() if d.startswith("m22-")))
drop_dataset(g, "m22-copy")
holders = g.V().has("QuestionItem", "urn", question).out("IN_DATASET").values("dataset_id")
print("after the drop:", sorted(d for d in holders.to_list() if d.startswith("m22-")))
members = g.V().has("Dataset", "dataset_id", "m22-survey").in_("IN_DATASET").count().next()
print("m22-survey members:", members)
connection.close()
Expected output:
question vertices: 1
its datasets: ['m22-copy', 'm22-survey']
after the drop: ['m22-survey']
m22-survey members: 86
The script follows the question WORK by its URN. A plain
in_("IN_DATASET").drop() would have deleted it, and m22-survey would
have lost it too. The same care applies to any graph
other people write to. Never wipe the whole graph with g.V().drop() on a
shared server.
Exercises¶
Scenario
Your agency runs JanusGraph for its other metadata. You try the DDI side on a local Gremlin Server first, with the Labour Force Survey, before you ask for space on the real one.
Exercise 1 (O1, O3). Write the survey in DDI-CDI,
tests/fixtures/lfs_cdi.xml, as dataset m22-cdi. Print the
GremlinResult. Then count the CDICategory vertices that have a
ddi_label property, and those that have a label property.
Expected output:
GremlinResult(nodes=91, relationships=92, memberships=90, skipped=0)
with ddi_label: 21
with label: 0
Answer
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.process.anonymous_traversal import traversal
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.traversal import P
from ddigraph.backends.gremlin import write_gremlin
def drop_dataset(g, dataset_id):
"""Drop a dataset's vertices, but keep those another dataset also holds."""
shared = __.out("IN_DATASET").has("dataset_id", P.neq(dataset_id))
g.V().has("Dataset", "dataset_id", dataset_id).in_("IN_DATASET").not_(shared).drop().iterate()
g.V().has("Dataset", "dataset_id", dataset_id).drop().iterate()
connection = DriverRemoteConnection("ws://localhost:8182/gremlin", "g")
g = traversal().with_(connection)
drop_dataset(g, "m22-cdi")
print(write_gremlin(g, "tests/fixtures/lfs_cdi.xml", dataset_id="m22-cdi"))
members = g.V().has("Dataset", "dataset_id", "m22-cdi").in_("IN_DATASET")
print("with ddi_label:", members.has_label("CDICategory").has("ddi_label").count().next())
members = g.V().has("Dataset", "dataset_id", "m22-cdi").in_("IN_DATASET")
print("with label:", members.has_label("CDICategory").has("label").count().next())
connection.close()
GremlinResult(nodes=91, relationships=92, memberships=90, skipped=0)
with ddi_label: 21
with label: 0
Ninety-one vertices, the Dataset vertex among them, and 90
memberships, one for every other vertex. has with a name alone keeps
the vertices that have that property. All 21 categories, from Male to
Not in the labour force, have a ddi_label, and none has a label:
the writer renamed it. A traversal runs only once, so the script builds
it again for the second question.
Exercise 2 (O4). In the same file, a DDI-CDI code list HAS_CODE
codes. Each code USES a notation, which holds its value, and DENOTES
a category. List the codes of the code list Labour force status (ILO),
in order, each with its value and the name of its category.
Expected output:
Labour force status (ILO): 1 -> Employed
Labour force status (ILO): 2 -> Unemployed
Labour force status (ILO): 3 -> Not in the labour force
Answer
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.process.anonymous_traversal import traversal
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.traversal import P
from ddigraph.backends.gremlin import write_gremlin
def drop_dataset(g, dataset_id):
"""Drop a dataset's vertices, but keep those another dataset also holds."""
shared = __.out("IN_DATASET").has("dataset_id", P.neq(dataset_id))
g.V().has("Dataset", "dataset_id", dataset_id).in_("IN_DATASET").not_(shared).drop().iterate()
g.V().has("Dataset", "dataset_id", dataset_id).drop().iterate()
connection = DriverRemoteConnection("ws://localhost:8182/gremlin", "g")
g = traversal().with_(connection)
drop_dataset(g, "m22-cdi")
write_gremlin(g, "tests/fixtures/lfs_cdi.xml", dataset_id="m22-cdi")
codes = (
g.V()
.has("Dataset", "dataset_id", "m22-cdi")
.in_("IN_DATASET")
.has("CDICodeList", "name", "Labour force status (ILO)")
.as_("list")
.out("HAS_CODE")
.as_("code")
.out("DENOTES")
.as_("category")
.select("list", "code", "category")
.by("name")
.by(__.out("USES").values("value"))
.by("name")
)
for row in sorted(codes.to_list(), key=lambda row: row["code"]):
print(f"{row['list']}: {row['code']} -> {row['category']}")
connection.close()
Labour force status (ILO): 1 -> Employed
Labour force status (ILO): 2 -> Unemployed
Labour force status (ILO): 3 -> Not in the labour force
as_ names a step, and select gathers the named steps into one
result. Each by says what to show for each name, in order: a
property, or a traversal, such as the step to the notation for the
code's value. These HAS_CODE edges carry no ordinal, so Python
sorts the rows by code. In DDI-CDI the codes are always vertices, so
there is one path only.
Exercise 3 (O4). The Codebook variable AGEGRP uses six
categories, the age groups from youngest to oldest. Its USES_CATEGORY
edges carry an ordinal. List the categories in that order, with their
ordinal.
Expected output:
0 15-24
1 25-34
2 35-44
3 45-54
4 55-64
5 65 and over
Answer
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.process.anonymous_traversal import traversal
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.traversal import P
from ddigraph.backends.gremlin import write_gremlin
def drop_dataset(g, dataset_id):
"""Drop a dataset's vertices, but keep those another dataset also holds."""
shared = __.out("IN_DATASET").has("dataset_id", P.neq(dataset_id))
g.V().has("Dataset", "dataset_id", dataset_id).in_("IN_DATASET").not_(shared).drop().iterate()
g.V().has("Dataset", "dataset_id", dataset_id).drop().iterate()
connection = DriverRemoteConnection("ws://localhost:8182/gremlin", "g")
g = traversal().with_(connection)
drop_dataset(g, "m22-codebook")
write_gremlin(g, "tests/fixtures/lfs_codebook.xml", dataset_id="m22-codebook")
categories = (
g.V()
.has("Variable", "name", "AGEGRP")
.has("dataset_id", "m22-codebook")
.out_e("USES_CATEGORY")
.order()
.by("ordinal")
.project("ordinal", "category")
.by("ordinal")
.by(__.in_v().values("ddi_label"))
)
for row in categories.to_list():
print(row["ordinal"], row["category"])
connection.close()
0 15-24
1 25-34
2 35-44
3 45-54
4 55-64
5 65 and over
As in Section 5, out_e stops on the edges instead of walking past
them, so you can sort by an edge property. in_v then steps to the
vertex each edge points at. Here project reads one value from the
edge and one from the category it points at.
Exercise 4 (O2, O4). A colleague asks you to prove that Gremlin holds
the same Codebook variables as the file. Count the Variable nodes twice:
with ddigraph.query on the file in memory, and with a traversal on
Gremlin.
Expected output:
file, ddigraph.query: 7
Gremlin, traversal: 7
Answer
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.process.anonymous_traversal import traversal
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.traversal import P
from ddigraph import ir
from ddigraph.backends.gremlin import write_gremlin
from ddigraph.lens.memory import MemoryLens
from ddigraph.query import Query, count, node, run
def drop_dataset(g, dataset_id):
"""Drop a dataset's vertices, but keep those another dataset also holds."""
shared = __.out("IN_DATASET").has("dataset_id", P.neq(dataset_id))
g.V().has("Dataset", "dataset_id", dataset_id).in_("IN_DATASET").not_(shared).drop().iterate()
g.V().has("Dataset", "dataset_id", dataset_id).drop().iterate()
path = "tests/fixtures/lfs_codebook.xml"
lens = MemoryLens()
lens.write(ir.parse(path, dataset_id="m22-codebook"), dataset_id="m22-codebook")
[(variables,)] = run(Query(match=[node("v", "Variable")], returns=[count()]), lens)
print("file, ddigraph.query:", variables)
connection = DriverRemoteConnection("ws://localhost:8182/gremlin", "g")
g = traversal().with_(connection)
drop_dataset(g, "m22-codebook")
write_gremlin(g, path, dataset_id="m22-codebook")
members = g.V().has("Dataset", "dataset_id", "m22-codebook").in_("IN_DATASET")
print("Gremlin, traversal:", members.has_label("Variable").count().next())
connection.close()
file, ddigraph.query: 7
Gremlin, traversal: 7
ddigraph.query cannot run on Gremlin, so it runs on the file, which
stays the source. The traversal asks Gremlin the same question in its
own language. When the two agree, the write is complete.
Exercise 5 (O5). Write tests/fixtures/lfs_cdi.xml twice, as
m22-cdi-a and m22-cdi-b. Count how many vertices the two datasets
share. Then drop m22-cdi-b with drop_dataset and count the members of
m22-cdi-a before and after.
Expected output:
members of m22-cdi-a: 90
shared by both: 90
members of m22-cdi-a after the drop: 90
Answer
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.process.anonymous_traversal import traversal
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.traversal import P
from ddigraph.backends.gremlin import write_gremlin
def drop_dataset(g, dataset_id):
"""Drop a dataset's vertices, but keep those another dataset also holds."""
shared = __.out("IN_DATASET").has("dataset_id", P.neq(dataset_id))
g.V().has("Dataset", "dataset_id", dataset_id).in_("IN_DATASET").not_(shared).drop().iterate()
g.V().has("Dataset", "dataset_id", dataset_id).drop().iterate()
connection = DriverRemoteConnection("ws://localhost:8182/gremlin", "g")
g = traversal().with_(connection)
for dataset_id in ("m22-cdi-a", "m22-cdi-b"):
drop_dataset(g, dataset_id)
write_gremlin(g, "tests/fixtures/lfs_cdi.xml", dataset_id=dataset_id)
members = g.V().has("Dataset", "dataset_id", "m22-cdi-a").in_("IN_DATASET")
print("members of m22-cdi-a:", members.count().next())
members = g.V().has("Dataset", "dataset_id", "m22-cdi-a").in_("IN_DATASET")
shared = members.where(__.out("IN_DATASET").has("dataset_id", "m22-cdi-b")).count().next()
print("shared by both:", shared)
drop_dataset(g, "m22-cdi-b")
members = g.V().has("Dataset", "dataset_id", "m22-cdi-a").in_("IN_DATASET")
print("members of m22-cdi-a after the drop:", members.count().next())
connection.close()
members of m22-cdi-a: 90
shared by both: 90
members of m22-cdi-a after the drop: 90
Every node of this file has a URN, made of its agency, ID and version.
So each one is a single vertex that both datasets hold. Dropping
m22-cdi-b removes only its Dataset vertex, with its edges, and leaves
m22-cdi-a whole. The survey's Codebook file would share nothing,
since a Codebook ID is scoped to its dataset.
Quiz¶
Question 1 (O2): You pass a Gremlin traversal source to ddigraph.query.run. What happens?
A. ddigraph writes the query as Gremlin and runs it.
B. run raises TypeError: ddigraph has no Gremlin translation and no Gremlin reader.
C. run reads the whole graph back into memory, then runs the query there.
D. It works only on JanusGraph, not on TinkerGraph.
Answer
B. ddigraph only writes to Gremlin. A is tempting, since run
writes Cypher, SPARQL and SQL, but Gremlin is not among them. C
would need a reader, which does not exist. Run the query on the
file in memory, or on another lens, and write your own traversal
for Gremlin.
Question 2 (O3): You load the same DDI-L file into the same dataset twice. What is in the graph after the second load?
A. Every vertex twice, one per load.
B. The same vertices and edges as after the first load.
C. The vertices once, and every edge twice.
D. Only the vertices of the second load: the first are replaced.
Answer
B. Each vertex is found by its key, and each edge by its two
ends, type and ordinal. The write creates one only when it is
missing. C is the usual trap of a write that upserts vertices but
always adds edges; write_gremlin upserts both.
Question 3 (O3): Why does a DDI node's label property arrive in Gremlin as ddi_label?
A. To keep it apart from the vertex label, which some databases also read from a label property, and which Cosmos DB refuses as a property name.
B. Because Gremlin properties cannot hold text.
C. To mark it as a DDI property, as every property gets a ddi_ prefix.
D. Because the label holds a language, and Gremlin needs a prefix for that.
Answer
A. In TinkerPop, every vertex already has a label: its type,
such as Variable. A property with the same name confuses some
databases. C is wrong: only label is renamed, while name and
question_text keep their names. The language goes in
ddi_label_lang, so D is wrong too.
Question 4 (O3): A Codebook variable's external_references holds two URNs. What does its vertex hold?
A. Two values of the property, one per URN.
B. Nothing: lists are left out.
C. One string, the two URNs joined with |.
D. Two vertices, one per URN, joined by edges.
Answer
C. Gremlin databases store lists, or several values in one property, in different ways. Some do not allow them at all. One string works everywhere. A is what a multi-property would give, and that is exactly what ddigraph avoids.
Question 5 (O4): Why does the code-list traversal use union, with one path through HAS_CATEGORY alone and one through CONTAINS, then HAS_CATEGORY?
A. To list each category twice, once per path.
B. Because a code with an ID is a vertex between the code list and its category, and a code with no ID is not.
C. Because HAS_CATEGORY edges point from the category to the code list.
D. To include the categories of other code lists.
Answer
B. DDI 3.2 and 3.3 give each code an ID, so the path is code list, code, category. DDI 3.1 codes have none, so the edge starts at the code list. One code list takes one path or the other, so A does not happen. C reverses the edge.
Question 6 (O5): You drop every vertex with an IN_DATASET edge to your Dataset vertex, without the not_ filter. Another team loaded the same DDI-L file as their own dataset. What breaks?
A. Nothing: their vertices are copies of yours.
B. Their dataset loses every vertex with a URN, because those vertices were shared with yours.
C. Only their Dataset vertex is lost.
D. The drop fails, because the vertices have other edges.
Answer
B. A URN gives the same key in every dataset, so both datasets hold one shared vertex. A is the tempting mistake: it would be true for Codebook IDs, which are scoped to their dataset, but not for URNs. Gremlin drops a vertex with all its edges, so D does not happen either.
Check yourself¶
- I can connect to Gremlin Server with gremlinpython, write a DDI file with
write_gremlin, and read itsGremlinResult. (O1) - I can explain why ddigraph only writes to Gremlin, and what that means for
ddigraph.queryand for reading the graph back. (O2) - I can predict what a write puts in the graph: vertices upserted by
key,IN_DATASETedges,ddi_labelforlabel, and lists joined with|. (O3) - I can write my own traversals: count one dataset's vertices by label, find a question's variables, and list a code list's categories through its codes. (O4)
- I can remove one dataset from the graph without touching the vertices another dataset shares. (O5)