Add graph JSONL converter and Neo4j loader

#2
by DigoryS - opened
README.md CHANGED
@@ -33,6 +33,7 @@ On the Eedi platform, students answer multiple-choice Diagnostic Questions with
33
  | `data/misconception-map.csv` | 19,294 | Misconception ↔ construct edges, weighted, with the full topic hierarchy on each row |
34
  | `data/construct-map.csv` | 2,258 | The construct catalogue and its subject → topic → sub-topic hierarchy |
35
  | `docs/data-dictionary.md` | — | Field definitions, per-field statistics and samples |
 
36
 
37
  Coverage: **8,117 misconceptions**, **2,258 constructs**, 236 sub-topics, 50 topics, 4 subjects (Number, Geometry and Measure, Algebra, Data and Statistics).
38
 
@@ -44,6 +45,17 @@ Join the two files on `ConstructId`. Every `ConstructId` in the misconception ma
44
 
45
  The Diagnostic Questions themselves, their distractors, question images, and any student-level response data are **not** part of this release. No personal data is included.
46
 
 
 
 
 
 
 
 
 
 
 
 
47
  ## Licence
48
 
49
  This work is licensed under a [Creative Commons Attribution 4.0 International Licence](https://creativecommons.org/licenses/by/4.0/) (CC BY 4.0).
@@ -56,6 +68,8 @@ The material is offered as-is, without warranties of any kind.
56
 
57
  The full licence text is in [`LICENSE`](LICENSE).
58
 
 
 
59
  ### Attribution
60
 
61
  Credit the work like this:
 
33
  | `data/misconception-map.csv` | 19,294 | Misconception ↔ construct edges, weighted, with the full topic hierarchy on each row |
34
  | `data/construct-map.csv` | 2,258 | The construct catalogue and its subject → topic → sub-topic hierarchy |
35
  | `docs/data-dictionary.md` | — | Field definitions, per-field statistics and samples |
36
+ | `scripts/` | — | Python scripts to convert the CSVs to graph JSONL and load them into Neo4j |
37
 
38
  Coverage: **8,117 misconceptions**, **2,258 constructs**, 236 sub-topics, 50 topics, 4 subjects (Number, Geometry and Measure, Algebra, Data and Statistics).
39
 
 
45
 
46
  The Diagnostic Questions themselves, their distractors, question images, and any student-level response data are **not** part of this release. No personal data is included.
47
 
48
+ ## Loading into a graph database
49
+
50
+ To explore the data as a graph, load it into [Neo4j](https://neo4j.com) with one command:
51
+
52
+ ```bash
53
+ pip install neo4j python-dotenv
54
+ python scripts/load_eedi_graph.py --download
55
+ ```
56
+
57
+ This builds a Subject → Topic → SubTopic → Construct → Misconception graph. Each construct–misconception link keeps its percentage weight. `scripts/csv_to_jsonl.py` produces the same graph as database-agnostic JSONL, and needs only the Python standard library. See [`scripts/README.md`](scripts/README.md) for connection settings, options, the graph model and example queries.
58
+
59
  ## Licence
60
 
61
  This work is licensed under a [Creative Commons Attribution 4.0 International Licence](https://creativecommons.org/licenses/by/4.0/) (CC BY 4.0).
 
68
 
69
  The full licence text is in [`LICENSE`](LICENSE).
70
 
71
+ The scripts in `scripts/` are software, so they are licensed separately under the [MIT Licence](scripts/LICENSE).
72
+
73
  ### Attribution
74
 
75
  Credit the work like this:
scripts/.env.example ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copy this file to .env (in this folder or any folder above it) and fill in your details.
2
+ # load_eedi_graph.py reads it automatically. Never commit your real .env.
3
+
4
+ # Local Neo4j (e.g. Neo4j Desktop)
5
+ NEO4J_URI=bolt://localhost:7687
6
+ NEO4J_USERNAME=neo4j
7
+ NEO4J_PASSWORD=your-password
8
+
9
+ # Optional: database to load into (default eedi-v1). On Aura or Community edition use neo4j.
10
+ # NEO4J_DATABASE_EEDI=eedi-v1
scripts/.gitignore ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Downloaded / generated data files
2
+ *.csv
3
+ *.jsonl
4
+
5
+ # Python
6
+ __pycache__/
7
+
8
+ # Environment variables
9
+ .env
10
+
11
+ # OS
12
+ .DS_Store
scripts/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Eedi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
scripts/README.md ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Scripts
2
+
3
+ Load the Eedi Misconceptions Graph into a graph database in one command.
4
+
5
+ | Script | What it does | Needs |
6
+ | --- | --- | --- |
7
+ | `csv_to_jsonl.py` | Converts the two CSVs into property-graph JSONL (`nodes.jsonl`, `relationships.jsonl`) | Python 3.8+ only |
8
+ | `load_eedi_graph.py` | Loads the JSONL into Neo4j (local or Aura); builds the JSONL first with `--download` | `pip install neo4j python-dotenv`, Neo4j 5+ |
9
+
10
+ ## Quick start
11
+
12
+ ```bash
13
+ pip install neo4j python-dotenv
14
+ python scripts/load_eedi_graph.py --download
15
+ ```
16
+
17
+ The CSVs are read from `data/` if you've cloned this repo. Otherwise they're downloaded from the `v1.0` release (pick a revision with `--tag`). You can also download just the two scripts and run them on their own.
18
+
19
+ ## Connecting to Neo4j
20
+
21
+ Copy `.env.example` to `.env` and fill in your details. Credentials are read from environment variables, or from the nearest `.env` file in the script's folder or any folder above it (failing that, the folder you run it from, or above):
22
+
23
+ ```bash
24
+ NEO4J_URI=bolt://localhost:7687 # or neo4j+s://xxxx.databases.neo4j.io for Aura
25
+ NEO4J_USERNAME=neo4j
26
+ NEO4J_PASSWORD=...
27
+ NEO4J_DATABASE_EEDI=eedi-v1 # optional; this is the default
28
+ ```
29
+
30
+ To keep several instances in one `.env`, add a suffix, e.g. `NEO4J_URI_LOCAL`, `NEO4J_PASSWORD_LOCAL`, and choose with `--target LOCAL`. When more than one is configured, the script refuses to guess.
31
+
32
+ The database is created if it doesn't exist. This needs Neo4j Enterprise, which Neo4j Desktop includes. Aura (including the free tier) and Community edition have a single database, so pass `--database neo4j` to load into it. The graph fits comfortably within Aura Free's limits.
33
+
34
+ ## Useful options
35
+
36
+ | Option | Effect |
37
+ | --- | --- |
38
+ | `--download` | (Re)build the JSONL from the CSVs before loading |
39
+ | `--target NAME` | Use the `NEO4J_*_NAME` variables |
40
+ | `--database NAME` | Load into this database (default `eedi-v1`) |
41
+ | `--wipe` | Delete everything in the database first |
42
+ | `--allow-nonempty` | Merge into a database that already has data |
43
+ | `--no-derived` | Skip the derived count properties |
44
+
45
+ By default the loader refuses to write to a database that already contains data.
46
+
47
+ ## Graph model
48
+
49
+ ```
50
+ (:Subject)-[:SUBJECT_CONTAINS_TOPIC]->(:Topic)-[:TOPIC_CONTAINS_SUBTOPIC]->(:SubTopic)
51
+ (:SubTopic)-[:SUBTOPIC_CONTAINS_CONSTRUCT]->(:Construct)
52
+ (:Construct)-[:CONSTRUCT_HAS_MISCONCEPTION {percentage}]->(:Misconception)
53
+ ```
54
+
55
+ | Label | Node id | Properties |
56
+ | --- | --- | --- |
57
+ | `Subject` | `eedi:subject:32` | `subjectSubjectId`, `name` |
58
+ | `Topic` | `eedi:topic:144` | `topicSubjectId`, `name` |
59
+ | `SubTopic` | `eedi:subtopic:202` | `subTopicSubjectId`, `name` |
60
+ | `Construct` | `eedi:construct:27` | `constructId`, `name`, `misconceptionCount`\* |
61
+ | `Misconception` | `eedi:misconception:13708` | `misconceptionId`, `name`, `constructCount`\*, `subTopicCount`\*, `topicCount`\*, `subjectCount`\* |
62
+
63
+ \* Computed by the loader, not present in the CSVs.
64
+
65
+ - **Field definitions:** properties are the CSV columns in camelCase (`ConstructId` → `constructId`, `ConstructName` → `name`). See [`docs/data-dictionary.md`](../docs/data-dictionary.md) for what each field means.
66
+ - **Node ids include the type.** Construct ids overlap with Subject/Topic/SubTopic ids, so the type prefix keeps every id unique. In Neo4j the id is stored as `uri`, and every node also has the label `EediNode`.
67
+ - **`percentage`** is `PercentageMisconceptionExistsInThisConstruct`: the share of a misconception's taggings that fall in that construct. It sums to 100 per misconception.
68
+ - **Full-text search** on names: `CALL db.index.fulltext.queryNodes('eedi_text', 'place value')`.
69
+
70
+ Version 1.0 loads 10,665 nodes and 21,838 relationships, and the loader checks these counts when it finishes.
71
+
72
+ ## Example queries
73
+
74
+ Misconceptions that appear in all four subjects:
75
+
76
+ ```cypher
77
+ MATCH (m:Misconception) WHERE m.subjectCount = 4
78
+ RETURN m.name, m.topicCount ORDER BY m.topicCount DESC
79
+ ```
80
+
81
+ Where a misconception shows up:
82
+
83
+ ```cypher
84
+ MATCH (m:Misconception {misconceptionId: 13708})<-[r:CONSTRUCT_HAS_MISCONCEPTION]-(c:Construct)
85
+ <-[:SUBTOPIC_CONTAINS_CONSTRUCT]-(st:SubTopic)
86
+ RETURN st.name, c.name, r.percentage ORDER BY r.percentage DESC
87
+ ```
88
+
89
+ ## Licence
90
+
91
+ The data is CC BY 4.0. See the [main README](../README.md#licence) for attribution. The JSONL is a format conversion of the CSVs, so the same licence and attribution apply.
92
+
93
+ The scripts themselves are licensed under the MIT Licence (see [`LICENSE`](LICENSE)).
scripts/csv_to_jsonl.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Convert the Eedi Misconceptions Graph CSV release (construct-map.csv /
4
+ misconception-map.csv) into property-graph JSONL (nodes.jsonl /
5
+ relationships.jsonl): one file of nodes, one file of relationships.
6
+
7
+ Source: https://huggingface.co/datasets/Eedi/Eedi-Misconceptions-Graph (CC BY 4.0)
8
+
9
+ Graph model
10
+ -----------
11
+ (:Subject)-[:SUBJECT_CONTAINS_TOPIC]->(:Topic)
12
+ (:Topic)-[:TOPIC_CONTAINS_SUBTOPIC]->(:SubTopic)
13
+ (:SubTopic)-[:SUBTOPIC_CONTAINS_CONSTRUCT]->(:Construct)
14
+ (:Construct)-[:CONSTRUCT_HAS_MISCONCEPTION {percentage}]->(:Misconception)
15
+
16
+ Node ids are type-prefixed (eedi:construct:27) because Construct ids overlap
17
+ with Subject/Topic/SubTopic ids.
18
+
19
+ Usage
20
+ -----
21
+ python csv_to_jsonl.py # write nodes.jsonl / relationships.jsonl next to this script
22
+ python csv_to_jsonl.py --csv-dir my/csvs # use CSVs from somewhere else
23
+
24
+ CSVs are read from ../data/ when this script sits in a clone of the Hugging Face
25
+ repo (scripts/ next to data/); otherwise they're downloaded next to this script.
26
+
27
+ Standard library only.
28
+ """
29
+ # How this works, in one paragraph
30
+ # --------------------------------
31
+ # The CSVs are "flat": every row repeats the whole Subject -> Topic -> SubTopic ->
32
+ # Construct chain. A graph wants each of those things stored ONCE as a node, with
33
+ # relationships joining them. So we walk every row, register each node/relationship
34
+ # in a dictionary keyed by its id (a repeat of something already seen is simply a
35
+ # no-op), and at the end write the de-duplicated contents out as JSONL.
36
+ #
37
+ # JSONL ("JSON Lines") = one complete JSON object per line. It streams well (no
38
+ # need to parse one giant JSON array), and it's database-agnostic - Neo4j is just
39
+ # one possible consumer.
40
+ #
41
+ # nodes.jsonl {"id": ..., "labels": [...], "properties": {...}}
42
+ # relationships.jsonl {"type": ..., "startNodeId": ..., "endNodeId": ..., "properties": {...}}
43
+
44
+ # Lets us write type hints like `dict | None` on older Pythons (3.8/3.9).
45
+ from __future__ import annotations
46
+
47
+ import argparse
48
+ import csv
49
+ import json
50
+ import sys
51
+ import urllib.request
52
+ from collections import Counter
53
+ from pathlib import Path
54
+
55
+ # `resolve/{tag}` is Hugging Face's "raw file at this revision" URL. Pinning a tag
56
+ # (rather than `main`) means the same command always gets the same data.
57
+ CSV_URL = "https://huggingface.co/datasets/Eedi/Eedi-Misconceptions-Graph/resolve/{tag}/data/{name}"
58
+ DEFAULT_TAG = "v1.0"
59
+ CSV_NAMES = ("construct-map.csv", "misconception-map.csv")
60
+
61
+ # Folder this script lives in - used as the default place to read/write files, so
62
+ # the script behaves the same whichever directory you run it from.
63
+ SCRIPT_DIR = Path(__file__).resolve().parent
64
+ # In a clone of the Hugging Face repo the CSVs already sit in data/, beside scripts/.
65
+ REPO_DATA_DIR = SCRIPT_DIR.parent / "data"
66
+
67
+ # The curriculum tree, top to bottom. Each tuple says how to build one level:
68
+ # (node label, CSV id column, id property name in the graph, CSV name column, parent label)
69
+ # Both CSVs contain these same columns, so one table drives the hierarchy for both.
70
+ # The graph property names are just the CSV column names in camelCase.
71
+ HIERARCHY = [
72
+ ("Subject", "SubjectSubjectId", "subjectSubjectId", "SubjectName", None),
73
+ ("Topic", "TopicSubjectId", "topicSubjectId", "TopicName", "Subject"),
74
+ ("SubTopic", "SubTopicSubjectId", "subTopicSubjectId", "SubTopicName", "Topic"),
75
+ ("Construct", "ConstructId", "constructId", "ConstructName", "SubTopic"),
76
+ ]
77
+ # Relationship type that points INTO each child level from its parent.
78
+ CONTAINS = {
79
+ "Topic": "SUBJECT_CONTAINS_TOPIC",
80
+ "SubTopic": "TOPIC_CONTAINS_SUBTOPIC",
81
+ "Construct": "SUBTOPIC_CONTAINS_CONSTRUCT",
82
+ }
83
+
84
+
85
+ def node_id(label: str, value: int) -> str:
86
+ """Construct, 27 -> eedi:construct:27
87
+
88
+ Why prefix? The raw integer ids aren't unique across types. Subject/Topic/
89
+ SubTopic ids come from one SQL table, so they never clash with each other,
90
+ but Construct ids are a separate sequence (e.g. 49 is both Subject
91
+ 'Algebra' and Construct 'Find 10 less than a given number').
92
+
93
+ Strictly only Constructs need separating, but every type gets its own prefix
94
+ anyway: one simple rule, ids that say what they are (eedi:topic:144), and no
95
+ reliance on the shared-table guarantee holding in future versions."""
96
+ return f"eedi:{label.lower()}:{value}"
97
+
98
+
99
+ def download(tag: str, dest: Path) -> None:
100
+ """Fetch any CSV not already in `dest`. Existing files are reused, so delete
101
+ them if you want a fresh copy (e.g. after changing --tag)."""
102
+ dest.mkdir(parents=True, exist_ok=True)
103
+ for name in CSV_NAMES:
104
+ p = dest / name
105
+ if not p.exists():
106
+ print(f"Downloading {name} ({tag}) ...")
107
+ urllib.request.urlretrieve(CSV_URL.format(tag=tag, name=name), p)
108
+
109
+
110
+ def default_csv_dir() -> Path:
111
+ """Use the repo's data/ folder if both CSVs are there, else this script's folder
112
+ (where download() will fetch them). Also used by load_eedi_graph.py."""
113
+ if all((REPO_DATA_DIR / name).is_file() for name in CSV_NAMES):
114
+ return REPO_DATA_DIR
115
+ return SCRIPT_DIR
116
+
117
+
118
+ def read_csv(path: Path) -> list[dict]:
119
+ """Read a CSV into a list of {column: value} dicts (all values are strings).
120
+
121
+ newline="" - required by the csv module so quoted fields containing
122
+ line breaks are handled correctly.
123
+ encoding=utf-8-sig - plain UTF-8, but silently drops a byte-order mark if the
124
+ file was saved by Excel (otherwise the first column name
125
+ would come out as '\\ufeffSubjectName')."""
126
+ with open(path, newline="", encoding="utf-8-sig") as f:
127
+ return list(csv.DictReader(f))
128
+
129
+
130
+ class Graph:
131
+ """Collects nodes/relationships, refusing conflicting duplicates.
132
+
133
+ Everything is stored in dicts keyed by identity, so adding the same node or
134
+ relationship twice is harmless - that's what de-duplicates the flat CSV rows.
135
+ But if the "same" thing arrives with DIFFERENT content (e.g. construct 27 with
136
+ two different names), we stop: that means the source data has changed shape
137
+ and silently picking one version would hide the problem."""
138
+
139
+ def __init__(self):
140
+ self.nodes: dict[str, dict] = {} # node id -> node record
141
+ self.rels: dict[tuple, dict] = {} # (type, start id, end id) -> relationship record
142
+ self.parent: dict[str, str] = {} # child node id -> parent node id (tree check)
143
+
144
+ def add_node(self, label: str, id_prop: str, raw_id: str, name: str) -> str:
145
+ """Register a node (if new) and return its id."""
146
+ value = int(raw_id.strip()) # CSV gives strings; store ids as integers in the graph
147
+ nid = node_id(label, value)
148
+ node = {"id": nid, "labels": [label], "properties": {id_prop: value, "name": name.strip()}}
149
+ # setdefault: "insert `node` if nid is new; either way, give me what's stored".
150
+ # So `existing` is either this node (first sighting) or the earlier one.
151
+ existing = self.nodes.setdefault(nid, node)
152
+ if existing != node:
153
+ sys.exit(f"Conflicting definitions for {nid}:\n {existing}\n {node}")
154
+ return nid
155
+
156
+ def add_rel(self, rtype: str, start: str, end: str, props: dict | None = None) -> None:
157
+ """Register a relationship (if new). Same setdefault trick as add_node.
158
+
159
+ The key is (type, start, end), so there is at most one relationship of a
160
+ given type between two nodes - matching MERGE semantics in the loader."""
161
+ key = (rtype, start, end)
162
+ rel = {"type": rtype, "startNodeId": start, "endNodeId": end, "properties": props or {}}
163
+ existing = self.rels.setdefault(key, rel)
164
+ if existing != rel:
165
+ sys.exit(f"Conflicting definitions for {key}:\n {existing}\n {rel}")
166
+
167
+ def add_hierarchy(self, row: dict) -> str:
168
+ """Add Subject -> Topic -> SubTopic -> Construct from one row; returns the Construct id."""
169
+ ids = {} # label -> node id for THIS row, so each level can find its parent
170
+ for label, id_col, id_prop, name_col, parent in HIERARCHY:
171
+ ids[label] = self.add_node(label, id_prop, row[id_col], row[name_col])
172
+ if parent: # everything except Subject hangs off the level above
173
+ # Each child has exactly one parent - catch a source change that breaks the tree.
174
+ # (add_rel alone wouldn't notice: a second parent is a *different* key,
175
+ # so it would just quietly add a second CONTAINS edge.)
176
+ known = self.parent.setdefault(ids[label], ids[parent])
177
+ if known != ids[parent]:
178
+ sys.exit(f"{ids[label]} has several parents: {known}, {ids[parent]}")
179
+ self.add_rel(CONTAINS[label], ids[parent], ids[label])
180
+ return ids["Construct"]
181
+
182
+
183
+ def build(csv_dir: Path, out_dir: Path, tag: str = DEFAULT_TAG, fetch: bool = True) -> tuple[Path, Path]:
184
+ """CSVs -> nodes.jsonl / relationships.jsonl. Returns the two output paths.
185
+
186
+ This is also what load_eedi_graph.py calls for its --download option."""
187
+ if fetch:
188
+ download(tag, csv_dir)
189
+ for name in CSV_NAMES:
190
+ if not (csv_dir / name).is_file():
191
+ sys.exit(f"{csv_dir / name} not found - drop --no-download, or pass --csv-dir")
192
+
193
+ g = Graph()
194
+
195
+ # 1) construct-map: one row per Construct -> builds the full curriculum tree.
196
+ for row in read_csv(csv_dir / "construct-map.csv"):
197
+ g.add_hierarchy(row)
198
+
199
+ # 2) misconception-map: one row per (Misconception, Construct) pair.
200
+ # It repeats the hierarchy columns too; re-adding them is a no-op, and it
201
+ # doubles as a check that both files agree on the tree.
202
+ for row in read_csv(csv_dir / "misconception-map.csv"):
203
+ construct = g.add_hierarchy(row)
204
+ misconception = g.add_node("Misconception", "misconceptionId", row["MisconceptionId"], row["MisconceptionName"])
205
+ # Share of this misconception's tags that fall in this construct (sums to ~100
206
+ # per misconception) - stored as a property on the relationship.
207
+ pct = float(row["PercentageMisconceptionExistsInThisConstruct"])
208
+ g.add_rel("CONSTRUCT_HAS_MISCONCEPTION", construct, misconception, {"percentage": pct})
209
+
210
+ # 3) Write one JSON object per line. ensure_ascii=False keeps characters like
211
+ # '÷' or '²' readable in the file instead of escaping them to \u00f7.
212
+ out_dir.mkdir(parents=True, exist_ok=True)
213
+ nodes_path, rels_path = out_dir / "nodes.jsonl", out_dir / "relationships.jsonl"
214
+ with open(nodes_path, "w", encoding="utf-8") as f:
215
+ for n in g.nodes.values():
216
+ f.write(json.dumps(n, ensure_ascii=False) + "\n")
217
+ with open(rels_path, "w", encoding="utf-8") as f:
218
+ for r in g.rels.values():
219
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
220
+
221
+ # 4) Summary. `:28s` pads to 28 chars, `:>8,` right-aligns with thousands separators.
222
+ for label, c in Counter(n["labels"][0] for n in g.nodes.values()).items():
223
+ print(f" nodes {label:28s} {c:>8,}")
224
+ for rtype, c in Counter(r["type"] for r in g.rels.values()).items():
225
+ print(f" rels {rtype:32s} {c:>8,}")
226
+ print(f"Wrote {len(g.nodes):,} nodes -> {nodes_path}")
227
+ print(f"Wrote {len(g.rels):,} relationships -> {rels_path}")
228
+ return nodes_path, rels_path
229
+
230
+
231
+ def main():
232
+ # description=__doc__ reuses the module docstring at the top as the --help text.
233
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
234
+ ap.add_argument("--csv-dir", type=Path,
235
+ help="where the CSVs live / are downloaded to "
236
+ "(default: ../data if it has them, else this script's folder)")
237
+ ap.add_argument("--out-dir", type=Path, default=SCRIPT_DIR,
238
+ help="where to write the JSONL (default: this script's folder)")
239
+ ap.add_argument("--tag", default=DEFAULT_TAG, help=f"Hugging Face revision (default {DEFAULT_TAG})")
240
+ ap.add_argument("--no-download", action="store_true", help="never download; CSVs must already be in --csv-dir")
241
+ args = ap.parse_args()
242
+ build(args.csv_dir or default_csv_dir(), args.out_dir, args.tag, fetch=not args.no_download)
243
+
244
+
245
+ # Only run main() when executed as a script - not when load_eedi_graph.py imports
246
+ # this file to reuse build().
247
+ if __name__ == "__main__":
248
+ main()
scripts/load_eedi_graph.py ADDED
@@ -0,0 +1,458 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Load the Eedi Misconceptions Graph (nodes.jsonl / relationships.jsonl, built by
4
+ csv_to_jsonl.py from the Hugging Face release) into Neo4j (Aura or local).
5
+
6
+ Source: https://huggingface.co/datasets/Eedi/Eedi-Misconceptions-Graph (CC BY 4.0)
7
+
8
+ (:Subject)-[:SUBJECT_CONTAINS_TOPIC]->(:Topic)-[:TOPIC_CONTAINS_SUBTOPIC]->(:SubTopic)
9
+ (:SubTopic)-[:SUBTOPIC_CONTAINS_CONSTRUCT]->(:Construct)
10
+ (:Construct)-[:CONSTRUCT_HAS_MISCONCEPTION {percentage}]->(:Misconception)
11
+
12
+ Every node also carries the label EediNode and a unique `uri` (e.g. eedi:construct:27).
13
+ A small derived layer adds count properties (skip with --no-derived).
14
+
15
+ Usage
16
+ -----
17
+ pip install neo4j python-dotenv
18
+ # Credentials come from the nearest .env above this script (or the current folder); either style works:
19
+ # NEO4J_URI=bolt://localhost:7687 or NEO4J_URI_LOCAL=bolt://localhost:7687
20
+ # NEO4J_USERNAME=neo4j NEO4J_USERNAME_LOCAL=neo4j
21
+ # NEO4J_PASSWORD=... NEO4J_PASSWORD_LOCAL=...
22
+ # NEO4J_DATABASE=eedi-v1 (optional) NEO4J_DATABASE_LOCAL=eedi-v1
23
+ python load_eedi_graph.py --download # build the JSONL from the CSVs, then load
24
+ python load_eedi_graph.py --download --target LOCAL # use the *_LOCAL variables (required if others exist)
25
+
26
+ Safety: refuses to run against a database that already contains nodes unless
27
+ --allow-nonempty (merge into it) or --wipe (delete everything first) is given.
28
+ """
29
+ # How this works, in order (see main() at the bottom)
30
+ # ---------------------------------------------------
31
+ # 1. Read credentials from .env and work out which Neo4j instance + database to use.
32
+ # 2. (--download) Build the JSONL from the Hugging Face CSVs via csv_to_jsonl.py.
33
+ # 3. Connect; create the database if needed; refuse to touch a non-empty one.
34
+ # 4. Create constraints/indexes BEFORE loading - they make the loading lookups fast.
35
+ # 5. Load nodes, then relationships (relationships need their end nodes to exist).
36
+ # 6. Add derived count properties, then re-count everything to verify the load.
37
+ #
38
+ # The core loading pattern (step 5) is "UNWIND + MERGE in batches":
39
+ # - We send the database a *list* of rows as one query parameter ($rows), and
40
+ # UNWIND turns that list back into one row per item inside Cypher. One round
41
+ # trip per 5,000 rows is far faster than one query per node.
42
+ # - MERGE = "find this, or create it if missing". Unlike CREATE it is idempotent,
43
+ # so re-running the loader (with --allow-nonempty) updates rather than duplicates.
44
+
45
+ # Lets us write type hints like `str | None` on older Pythons (3.8/3.9).
46
+ from __future__ import annotations
47
+
48
+ import argparse
49
+ import json
50
+ import os
51
+ import re
52
+ import sys
53
+ import time
54
+ from collections import defaultdict
55
+ from pathlib import Path
56
+
57
+ DEFAULT_TAG = "v1.0" # Hugging Face revision of the CSVs
58
+ DEFAULT_DATABASE = "eedi-v1" # Neo4j database name, kept in step with the data version
59
+
60
+ # Labels and relationship types can't be passed as Cypher parameters, so we have to
61
+ # paste them into the query text. This pattern whitelists "plain identifier" names
62
+ # so nothing odd from a data file can ever end up injected into a query.
63
+ SAFE_NAME = re.compile(r"^[A-Za-z][A-Za-z0-9_]*$")
64
+
65
+
66
+ # --------------------------------------------------------------------------- helpers
67
+ def safe(name: str) -> str:
68
+ """Return `name` unchanged if it's a safe label/type name, else raise."""
69
+ if not SAFE_NAME.match(name):
70
+ raise ValueError(f"Unsafe label/type name: {name!r}")
71
+ return name
72
+
73
+
74
+ def batched(seq, n):
75
+ """Yield successive slices of `seq` of length n (the last may be shorter)."""
76
+ for i in range(0, len(seq), n):
77
+ yield seq[i : i + n]
78
+
79
+
80
+ # Folder this script lives in - default location for the JSONL files and the
81
+ # starting point when searching for a .env.
82
+ SCRIPT_DIR = Path(__file__).resolve().parent
83
+
84
+
85
+ def read_env_file(env_file: Path | None) -> None:
86
+ """Load NEO4J_* settings from a .env file into os.environ (via python-dotenv).
87
+
88
+ With no --env-file, find the nearest .env walking upward - first from this
89
+ script's folder, then from the directory you ran it in. e.g. from
90
+ my-project/eedi/scripts/ it checks scripts/, then eedi/, then my-project/,
91
+ so one .env at the top of a project covers everything below it."""
92
+ # Imported here, not at the top, so --help works before anything is installed.
93
+ from dotenv import find_dotenv, load_dotenv
94
+
95
+ if env_file is None:
96
+ # find_dotenv() starts from the folder of the file that calls it (this
97
+ # script); usecwd=True starts from the current directory instead.
98
+ # Both return "" when nothing is found.
99
+ found = find_dotenv() or find_dotenv(usecwd=True)
100
+ env_file = Path(found) if found else None
101
+ if env_file is None or not env_file.is_file():
102
+ print(f"No .env found ({env_file or 'searched upward from ' + str(SCRIPT_DIR) + ' and ' + os.getcwd()})"
103
+ " - using environment variables only")
104
+ return
105
+ # override=False (the default): a variable already set in your shell wins
106
+ # over the same name in the file.
107
+ load_dotenv(env_file, override=False)
108
+ print(f"Read settings from {env_file}")
109
+
110
+
111
+ def neo4j_settings(target: str | None) -> tuple[str, str, str, str, list[str]]:
112
+ """Resolve URI/user/password/database and report which variables were used.
113
+
114
+ Targets are the URI variables present: NEO4J_URI -> 'DEFAULT', NEO4J_URI_LOCAL -> 'LOCAL', ...
115
+ With several present you must choose one with --target, so an Aura instance and a local
116
+ one can never be mixed up silently. Credentials never fall back across targets."""
117
+ # Build {target name: variable suffix}, e.g. {"DEFAULT": "", "LOCAL": "_LOCAL"}.
118
+ targets = {}
119
+ if "NEO4J_URI" in os.environ:
120
+ targets["DEFAULT"] = ""
121
+ for k in os.environ:
122
+ m = re.fullmatch(r"NEO4J_URI_(\w+)", k)
123
+ if m:
124
+ targets[m.group(1).upper()] = f"_{m.group(1)}"
125
+ if not targets:
126
+ sys.exit("No NEO4J_URI / NEO4J_URI_<TARGET> variable found (checked the .env and environment).")
127
+
128
+ # No --target given: fine if there's only one choice, otherwise list the
129
+ # options and stop rather than guess.
130
+ if target is None:
131
+ if len(targets) > 1:
132
+ opts = ", ".join(f"--target {t} ({'NEO4J_URI' + sfx} = {os.environ['NEO4J_URI' + sfx]})"
133
+ for t, sfx in sorted(targets.items()))
134
+ sys.exit(f"Several Neo4j targets are configured - choose one:\n " + opts.replace(", --", "\n --"))
135
+ target = next(iter(targets))
136
+ target = target.upper()
137
+ if target not in targets:
138
+ sys.exit(f"--target {target}: no NEO4J_URI{'_' + target if target != 'DEFAULT' else ''} set. "
139
+ f"Available: {', '.join(sorted(targets))}")
140
+ sfx = targets[target]
141
+ used = [] # which variable names we actually read - printed so you can see the source
142
+
143
+ def get(*names, default=None):
144
+ # Try each candidate variable name in order; first one *present* wins
145
+ # (an empty value like PASSWORD='' counts as set).
146
+ for n in names:
147
+ if n in os.environ:
148
+ used.append(n)
149
+ return os.environ[n]
150
+ if default is not None:
151
+ return default
152
+ sys.exit(f"Missing {names[0]} for target {target}.")
153
+
154
+ uri = get(f"NEO4J_URI{sfx}")
155
+ user = get(f"NEO4J_USERNAME{sfx}", f"NEO4J_USER{sfx}", default="neo4j")
156
+ password = get(f"NEO4J_PASSWORD{sfx}")
157
+ # Database lookup order:
158
+ # LOCAL target: NEO4J_DATABASE_LOCAL, then NEO4J_DATABASE_EEDI
159
+ # DEFAULT target: NEO4J_DATABASE_EEDI, then NEO4J_DATABASE
160
+ # ...then DEFAULT_DATABASE. NEO4J_DATABASE_EEDI sits above the generic
161
+ # NEO4J_DATABASE so this graph doesn't land in a database meant for something else.
162
+ db_vars = ([f"NEO4J_DATABASE{sfx}"] if sfx else []) + ["NEO4J_DATABASE_EEDI"] + ([] if sfx else ["NEO4J_DATABASE"])
163
+ database = get(*db_vars, default=DEFAULT_DATABASE)
164
+ return uri, user, password, database, used
165
+
166
+
167
+ def build_jsonl(tag: str, dest: Path) -> None:
168
+ """Run csv_to_jsonl.py (shipped alongside this script): download CSVs, write JSONL."""
169
+ try:
170
+ import csv_to_jsonl
171
+ except ImportError:
172
+ sys.exit(f"csv_to_jsonl.py not found next to {Path(__file__).name} - it is needed for --download")
173
+ csv_to_jsonl.build(csv_to_jsonl.default_csv_dir(), dest, tag)
174
+
175
+
176
+ def prepare_node(raw: dict) -> dict:
177
+ """Turn a JSONL node into {labels, props}. Adds uri.
178
+
179
+ The JSONL id ('eedi:construct:27') becomes the `uri` property - the single key
180
+ we use to find any node, whatever its label."""
181
+ props = dict(raw["properties"]) # copy, so we don't mutate the parsed JSON
182
+ props["uri"] = raw["id"]
183
+ return {"labels": [safe(l) for l in raw["labels"]], "props": props}
184
+
185
+
186
+ # --------------------------------------------------------------------------- loading
187
+ def check_empty(session, allow_nonempty: bool, wipe: bool, where: str = ""):
188
+ """Guard against loading on top of existing data by accident."""
189
+ count = session.run("MATCH (n) RETURN count(n) AS c").single()["c"]
190
+ if count == 0:
191
+ return
192
+ if wipe:
193
+ print(f"--wipe: deleting {count:,} existing nodes ...")
194
+ # DETACH DELETE removes each node plus its relationships. Doing it
195
+ # IN TRANSACTIONS OF 5000 ROWS commits in chunks, so deleting a large graph
196
+ # doesn't need one enormous transaction held in memory.
197
+ session.run(
198
+ "MATCH (n) CALL { WITH n DETACH DELETE n } IN TRANSACTIONS OF 5000 ROWS"
199
+ ).consume()
200
+ return
201
+ if not allow_nonempty:
202
+ sys.exit(
203
+ f"{where} already contains {count:,} nodes. Point at a fresh database, "
204
+ "or pass --allow-nonempty (merge) / --wipe (delete everything first)."
205
+ )
206
+
207
+
208
+ # Neo4j's rules for database names: start with a letter; letters, digits, '.', '-'; 3-63 chars.
209
+ DB_NAME = re.compile(r"^[A-Za-z][A-Za-z0-9.\-]{2,62}$")
210
+
211
+
212
+ def ensure_database(driver, db: str):
213
+ """Create the target database if it doesn't exist (needs Enterprise, which Neo4j Desktop provides).
214
+
215
+ Database admin commands (SHOW/CREATE DATABASE) must run against the special
216
+ `system` database, hence database_="system" below."""
217
+ if db in ("neo4j", "system"):
218
+ return # built-in databases always exist
219
+ if not DB_NAME.match(db):
220
+ sys.exit(f"Invalid database name {db!r} (letters, digits, '.', '-'; 3-63 chars)")
221
+ names = {r["name"] for r in driver.execute_query("SHOW DATABASES YIELD name", database_="system").records}
222
+ if db.lower() in names: # Neo4j stores database names in lower case
223
+ return
224
+ print(f"Database '{db}' not found - creating it ...")
225
+ try:
226
+ # Backticks are needed because names like `eedi-v1` contain a hyphen.
227
+ # WAIT blocks until the new database is online and ready for queries.
228
+ driver.execute_query(f"CREATE DATABASE `{db}` IF NOT EXISTS WAIT", database_="system")
229
+ except Exception as e: # e.g. Community edition / Aura: single database only
230
+ sys.exit(f"Could not create database '{db}': {e}\n"
231
+ "Create it yourself (CREATE DATABASE ...) or set the database to 'neo4j'.")
232
+
233
+
234
+ def create_schema(session):
235
+ """Constraints and indexes. All IF NOT EXISTS, so safe to re-run.
236
+
237
+ A uniqueness constraint does two jobs: it stops duplicates, and it creates an
238
+ index behind the scenes. That index is what makes the MERGE / MATCH on `uri`
239
+ during loading a fast lookup instead of a scan of every node."""
240
+ stmts = [
241
+ # The loading key: every node has the EediNode label and a unique uri.
242
+ "CREATE CONSTRAINT eedi_uri IF NOT EXISTS FOR (n:EediNode) REQUIRE n.uri IS UNIQUE",
243
+ # The human-facing keys: integer ids per label, for queries like
244
+ # MATCH (c:Construct {constructId: 27}).
245
+ "CREATE CONSTRAINT subject_id IF NOT EXISTS FOR (n:Subject) REQUIRE n.subjectSubjectId IS UNIQUE",
246
+ "CREATE CONSTRAINT topic_id IF NOT EXISTS FOR (n:Topic) REQUIRE n.topicSubjectId IS UNIQUE",
247
+ "CREATE CONSTRAINT subtopic_id IF NOT EXISTS FOR (n:SubTopic) REQUIRE n.subTopicSubjectId IS UNIQUE",
248
+ "CREATE CONSTRAINT construct_id IF NOT EXISTS FOR (n:Construct) REQUIRE n.constructId IS UNIQUE",
249
+ "CREATE CONSTRAINT misconception_id IF NOT EXISTS FOR (n:Misconception) REQUIRE n.misconceptionId IS UNIQUE",
250
+ # Full-text (Lucene) index for word search across names, e.g.
251
+ # CALL db.index.fulltext.queryNodes('eedi_text', 'place value')
252
+ "CREATE FULLTEXT INDEX eedi_text IF NOT EXISTS "
253
+ "FOR (n:Subject|Topic|SubTopic|Construct|Misconception) ON EACH [n.name]",
254
+ ]
255
+ for s in stmts:
256
+ # .consume() runs the query to completion and discards the (empty) result.
257
+ session.run(s).consume()
258
+ # Indexes build in the background; wait (up to 300s) until they're ready to use.
259
+ session.run("CALL db.awaitIndexes(300)").consume()
260
+
261
+
262
+ def load_nodes(driver, db, path: Path, batch: int) -> dict[str, int]:
263
+ """Load nodes.jsonl. Returns {label: count} for verify()."""
264
+ # Group nodes by label set. A label can't be a query parameter, so we need
265
+ # one query per label combination, with the label written into the query text.
266
+ groups: dict[tuple, list] = defaultdict(list)
267
+ with open(path, encoding="utf-8") as f:
268
+ for line in f: # JSONL: each line is one node
269
+ n = prepare_node(json.loads(line))
270
+ groups[tuple(sorted(n["labels"]))].append(n["props"])
271
+ counts = {}
272
+ for labels, rows in groups.items():
273
+ label_str = "".join(f":{l}" for l in labels) # ["Construct"] -> ":Construct"
274
+ # For each row: find-or-create the node by uri (using the shared EediNode
275
+ # label, so the eedi_uri constraint's index is used), then copy every
276
+ # property onto it (`+=` merges the row map in) and add its real label.
277
+ q = (
278
+ "UNWIND $rows AS row "
279
+ "MERGE (n:EediNode {uri: row.uri}) "
280
+ f"SET n += row, n{label_str}"
281
+ )
282
+ for chunk in batched(rows, batch):
283
+ # execute_query runs each call in its own transaction, retrying on
284
+ # transient errors (e.g. a brief Aura connection blip).
285
+ driver.execute_query(q, rows=chunk, database_=db)
286
+ counts["|".join(labels)] = len(rows)
287
+ print(f" nodes {'|'.join(labels):28s} {len(rows):>8,}")
288
+ return counts
289
+
290
+
291
+ def load_rels(driver, db, path: Path, batch: int):
292
+ """Load relationships.jsonl. Returns {type: count} for verify()."""
293
+ # Same idea as load_nodes: a relationship type can't be a parameter, so group
294
+ # by type and run one query per type. Each row is shrunk to just
295
+ # s(tart uri), e(nd uri) and p(roperties) to keep the payload small.
296
+ groups: dict[str, list] = defaultdict(list)
297
+ with open(path, encoding="utf-8") as f:
298
+ for line in f:
299
+ r = json.loads(line)
300
+ groups[r["type"]].append({"s": r["startNodeId"], "e": r["endNodeId"], "p": r.get("properties") or {}})
301
+ counts = {}
302
+ # Biggest groups first, so any problem shows up early (purely cosmetic ordering).
303
+ for rtype, rows in sorted(groups.items(), key=lambda kv: -len(kv[1])):
304
+ t = safe(rtype)
305
+ # Look up both end nodes by uri (index lookups thanks to eedi_uri), then
306
+ # find-or-create the relationship between them and copy its properties
307
+ # on (e.g. `percentage` on CONSTRUCT_HAS_MISCONCEPTION).
308
+ # Note: MATCH, not MERGE, for the end nodes - if a uri were missing the row
309
+ # would silently produce no relationship, which verify() would then catch.
310
+ q = (
311
+ "UNWIND $rows AS row "
312
+ "MATCH (s:EediNode {uri: row.s}) MATCH (e:EediNode {uri: row.e}) "
313
+ f"MERGE (s)-[r:{t}]->(e) "
314
+ "SET r += row.p"
315
+ )
316
+ for chunk in batched(rows, batch):
317
+ driver.execute_query(q, rows=chunk, database_=db)
318
+ counts[t] = len(rows)
319
+ print(f" rels {t:32s} {len(rows):>8,}")
320
+ return counts
321
+
322
+
323
+ # --------------------------------------------------------------------------- derived layer
324
+ # Extra properties computed from the loaded graph (not present in the source CSVs).
325
+ # Handy for filtering without writing the traversal every time, e.g.
326
+ # MATCH (m:Misconception) WHERE m.subjectCount = 4 RETURN m.name
327
+ # Each entry is (description printed while running, Cypher query).
328
+ DERIVED = [
329
+ (
330
+ "Misconception.constructCount / subTopicCount / topicCount / subjectCount (how widely it spans)",
331
+ # Walk from each misconception up the tree to its Subjects, then count the
332
+ # DISTINCT nodes reached at each level. A misconception tagged in 5 constructs
333
+ # that all sit in one subtopic gets constructCount=5, subTopicCount=1.
334
+ """MATCH (m:Misconception)<-[:CONSTRUCT_HAS_MISCONCEPTION]-(c:Construct)
335
+ <-[:SUBTOPIC_CONTAINS_CONSTRUCT]-(st:SubTopic)
336
+ <-[:TOPIC_CONTAINS_SUBTOPIC]-(t:Topic)
337
+ <-[:SUBJECT_CONTAINS_TOPIC]-(s:Subject)
338
+ WITH m, count(DISTINCT c) AS cc, count(DISTINCT st) AS stc, count(DISTINCT t) AS tc, count(DISTINCT s) AS sc
339
+ SET m.constructCount = cc, m.subTopicCount = stc, m.topicCount = tc, m.subjectCount = sc""",
340
+ ),
341
+ (
342
+ "Construct.misconceptionCount",
343
+ # COUNT { pattern } is a Neo4j 5 "count subquery": the number of matches of
344
+ # that pattern for this construct.
345
+ """MATCH (c:Construct)
346
+ SET c.misconceptionCount = COUNT { (c)-[:CONSTRUCT_HAS_MISCONCEPTION]->(:Misconception) }""",
347
+ ),
348
+ ]
349
+
350
+
351
+ def build_derived(session):
352
+ for desc, q in DERIVED:
353
+ t0 = time.time()
354
+ # .counters reports what the query changed (nodes/relationships/properties).
355
+ s = session.run(q).consume().counters
356
+ print(f" {desc}: {s.properties_set:,} props ({time.time()-t0:.1f}s)")
357
+
358
+
359
+ # --------------------------------------------------------------------------- verify
360
+ def verify(session, node_counts, rel_counts):
361
+ """Re-count what's in the database and compare with what we sent.
362
+
363
+ Nodes use >= (the database may legitimately hold more if --allow-nonempty
364
+ merged into existing data); relationships must match exactly."""
365
+ ok = True
366
+ for k, expected in node_counts.items():
367
+ label = k.split("|")[0]
368
+ got = session.run(f"MATCH (n:{label}) RETURN count(n) AS c").single()["c"]
369
+ if got < expected:
370
+ ok = False
371
+ print(f" MISMATCH {label}: expected >= {expected}, got {got}")
372
+ for t, expected in rel_counts.items():
373
+ got = session.run(f"MATCH ()-[r:{t}]->() RETURN count(r) AS c").single()["c"]
374
+ if got != expected:
375
+ ok = False
376
+ print(f" MISMATCH {t}: expected {expected}, got {got}")
377
+ print(" verification", "PASSED" if ok else "FAILED")
378
+ return ok
379
+
380
+
381
+ def main():
382
+ # ---- command-line options (description=__doc__ reuses the docstring as --help text)
383
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
384
+ ap.add_argument("--data-dir", type=Path, default=SCRIPT_DIR,
385
+ help="where the JSONL files live / are built in (default: this script's folder)")
386
+ ap.add_argument("--nodes", type=Path, help="override path to nodes.jsonl")
387
+ ap.add_argument("--rels", type=Path, help="override path to relationships.jsonl")
388
+ ap.add_argument("--env-file", type=Path,
389
+ help="dotenv file to read (default: nearest .env above this script's folder, "
390
+ "then above the current folder)")
391
+ ap.add_argument("--database", help=f"database name (overrides the .env value; default '{DEFAULT_DATABASE}')")
392
+ ap.add_argument("--target", help="which credentials: LOCAL -> NEO4J_*_LOCAL, DEFAULT -> plain NEO4J_*. "
393
+ "Required when more than one is configured.")
394
+ ap.add_argument("--download", action="store_true",
395
+ help="(re)build the JSONL from the CSVs first - using ../data if present, "
396
+ "else downloading them from Hugging Face")
397
+ ap.add_argument("--tag", default=DEFAULT_TAG, help=f"Hugging Face revision (default {DEFAULT_TAG})")
398
+ ap.add_argument("--no-derived", action="store_true", help="skip the derived count properties")
399
+ ap.add_argument("--batch", type=int, default=5000)
400
+ ap.add_argument("--allow-nonempty", action="store_true")
401
+ ap.add_argument("--wipe", action="store_true", help="DELETE ALL existing data first")
402
+ args = ap.parse_args()
403
+
404
+ # ---- 1. credentials and target
405
+ read_env_file(args.env_file)
406
+ uri, user, password, db, used = neo4j_settings(args.target)
407
+ db = args.database or db # --database on the command line beats the .env
408
+ print(f"Target: {uri} database '{db}' (from {', '.join(used)}{', --database' if args.database else ''})")
409
+
410
+ # ---- 2. input files
411
+ if args.download:
412
+ build_jsonl(args.tag, args.data_dir)
413
+ args.nodes = args.nodes or args.data_dir / "nodes.jsonl"
414
+ args.rels = args.rels or args.data_dir / "relationships.jsonl"
415
+ for p in (args.nodes, args.rels):
416
+ if not p.is_file():
417
+ sys.exit(f"{p} not found - run with --download (or csv_to_jsonl.py), or pass --data-dir / --nodes / --rels")
418
+
419
+ from neo4j import GraphDatabase # imported late so --help works without the driver
420
+
421
+ if password == "":
422
+ print("Password is empty - connecting without authentication (fine only if auth is disabled).")
423
+ auth = None
424
+ else:
425
+ auth = (user, password)
426
+
427
+ t0 = time.time()
428
+ # The driver manages a pool of connections; `with` closes them all at the end.
429
+ with GraphDatabase.driver(uri, auth=auth) as driver:
430
+ # ---- 3. connect, create database, safety check
431
+ driver.verify_connectivity() # fail fast on a wrong URI/password
432
+ print(f"Connected to {uri}")
433
+ ensure_database(driver, db)
434
+ print(f"Using database '{db}'")
435
+ # A session is a short-lived "conversation" with one database; used here for
436
+ # the one-off admin queries. Bulk loading uses driver.execute_query instead.
437
+ with driver.session(database=db) as s:
438
+ check_empty(s, args.allow_nonempty, args.wipe, f"Database '{db}' at {uri}")
439
+ # ---- 4. schema first, so the loading lookups below are indexed
440
+ print("Creating constraints & indexes ...")
441
+ create_schema(s)
442
+ # ---- 5. data: nodes before relationships
443
+ print("Loading nodes ...")
444
+ nc = load_nodes(driver, db, args.nodes, args.batch)
445
+ print("Loading relationships ...")
446
+ rc = load_rels(driver, db, args.rels, args.batch)
447
+ # ---- 6. derived properties and verification
448
+ with driver.session(database=db) as s:
449
+ if not args.no_derived:
450
+ print("Building derived properties ...")
451
+ build_derived(s)
452
+ print("Verifying ...")
453
+ verify(s, nc, rc)
454
+ print(f"Done in {time.time()-t0:.0f}s")
455
+
456
+
457
+ if __name__ == "__main__":
458
+ main()