#!/usr/bin/env python3 """ Load the Eedi Misconceptions Graph (nodes.jsonl / relationships.jsonl, built by csv_to_jsonl.py from the Hugging Face release) into Neo4j (Aura or local). Source: https://huggingface.co/datasets/Eedi/Eedi-Misconceptions-Graph (CC BY 4.0) (:Subject)-[:SUBJECT_CONTAINS_TOPIC]->(:Topic)-[:TOPIC_CONTAINS_SUBTOPIC]->(:SubTopic) (:SubTopic)-[:SUBTOPIC_CONTAINS_CONSTRUCT]->(:Construct) (:Construct)-[:CONSTRUCT_HAS_MISCONCEPTION {percentage}]->(:Misconception) Every node also carries the label EediNode and a unique `uri` (e.g. eedi:construct:27). A small derived layer adds count properties (skip with --no-derived). Usage ----- pip install neo4j python-dotenv # Credentials come from the nearest .env above this script (or the current folder); either style works: # NEO4J_URI=bolt://localhost:7687 or NEO4J_URI_LOCAL=bolt://localhost:7687 # NEO4J_USERNAME=neo4j NEO4J_USERNAME_LOCAL=neo4j # NEO4J_PASSWORD=... NEO4J_PASSWORD_LOCAL=... # NEO4J_DATABASE=eedi-v1 (optional) NEO4J_DATABASE_LOCAL=eedi-v1 python load_eedi_graph.py --download # build the JSONL from the CSVs, then load python load_eedi_graph.py --download --target LOCAL # use the *_LOCAL variables (required if others exist) Safety: refuses to run against a database that already contains nodes unless --allow-nonempty (merge into it) or --wipe (delete everything first) is given. """ # How this works, in order (see main() at the bottom) # --------------------------------------------------- # 1. Read credentials from .env and work out which Neo4j instance + database to use. # 2. (--download) Build the JSONL from the Hugging Face CSVs via csv_to_jsonl.py. # 3. Connect; create the database if needed; refuse to touch a non-empty one. # 4. Create constraints/indexes BEFORE loading - they make the loading lookups fast. # 5. Load nodes, then relationships (relationships need their end nodes to exist). # 6. Add derived count properties, then re-count everything to verify the load. # # The core loading pattern (step 5) is "UNWIND + MERGE in batches": # - We send the database a *list* of rows as one query parameter ($rows), and # UNWIND turns that list back into one row per item inside Cypher. One round # trip per 5,000 rows is far faster than one query per node. # - MERGE = "find this, or create it if missing". Unlike CREATE it is idempotent, # so re-running the loader (with --allow-nonempty) updates rather than duplicates. # Lets us write type hints like `str | None` on older Pythons (3.8/3.9). from __future__ import annotations import argparse import json import os import re import sys import time from collections import defaultdict from pathlib import Path DEFAULT_TAG = "v1.0" # Hugging Face revision of the CSVs DEFAULT_DATABASE = "eedi-v1" # Neo4j database name, kept in step with the data version # Labels and relationship types can't be passed as Cypher parameters, so we have to # paste them into the query text. This pattern whitelists "plain identifier" names # so nothing odd from a data file can ever end up injected into a query. SAFE_NAME = re.compile(r"^[A-Za-z][A-Za-z0-9_]*$") # --------------------------------------------------------------------------- helpers def safe(name: str) -> str: """Return `name` unchanged if it's a safe label/type name, else raise.""" if not SAFE_NAME.match(name): raise ValueError(f"Unsafe label/type name: {name!r}") return name def batched(seq, n): """Yield successive slices of `seq` of length n (the last may be shorter).""" for i in range(0, len(seq), n): yield seq[i : i + n] # Folder this script lives in - default location for the JSONL files and the # starting point when searching for a .env. SCRIPT_DIR = Path(__file__).resolve().parent def read_env_file(env_file: Path | None) -> None: """Load NEO4J_* settings from a .env file into os.environ (via python-dotenv). With no --env-file, find the nearest .env walking upward - first from this script's folder, then from the directory you ran it in. e.g. from my-project/eedi/scripts/ it checks scripts/, then eedi/, then my-project/, so one .env at the top of a project covers everything below it.""" # Imported here, not at the top, so --help works before anything is installed. from dotenv import find_dotenv, load_dotenv if env_file is None: # find_dotenv() starts from the folder of the file that calls it (this # script); usecwd=True starts from the current directory instead. # Both return "" when nothing is found. found = find_dotenv() or find_dotenv(usecwd=True) env_file = Path(found) if found else None if env_file is None or not env_file.is_file(): print(f"No .env found ({env_file or 'searched upward from ' + str(SCRIPT_DIR) + ' and ' + os.getcwd()})" " - using environment variables only") return # override=False (the default): a variable already set in your shell wins # over the same name in the file. load_dotenv(env_file, override=False) print(f"Read settings from {env_file}") def neo4j_settings(target: str | None) -> tuple[str, str, str, str, list[str]]: """Resolve URI/user/password/database and report which variables were used. Targets are the URI variables present: NEO4J_URI -> 'DEFAULT', NEO4J_URI_LOCAL -> 'LOCAL', ... With several present you must choose one with --target, so an Aura instance and a local one can never be mixed up silently. Credentials never fall back across targets.""" # Build {target name: variable suffix}, e.g. {"DEFAULT": "", "LOCAL": "_LOCAL"}. targets = {} if "NEO4J_URI" in os.environ: targets["DEFAULT"] = "" for k in os.environ: m = re.fullmatch(r"NEO4J_URI_(\w+)", k) if m: targets[m.group(1).upper()] = f"_{m.group(1)}" if not targets: sys.exit("No NEO4J_URI / NEO4J_URI_ variable found (checked the .env and environment).") # No --target given: fine if there's only one choice, otherwise list the # options and stop rather than guess. if target is None: if len(targets) > 1: opts = ", ".join(f"--target {t} ({'NEO4J_URI' + sfx} = {os.environ['NEO4J_URI' + sfx]})" for t, sfx in sorted(targets.items())) sys.exit(f"Several Neo4j targets are configured - choose one:\n " + opts.replace(", --", "\n --")) target = next(iter(targets)) target = target.upper() if target not in targets: sys.exit(f"--target {target}: no NEO4J_URI{'_' + target if target != 'DEFAULT' else ''} set. " f"Available: {', '.join(sorted(targets))}") sfx = targets[target] used = [] # which variable names we actually read - printed so you can see the source def get(*names, default=None): # Try each candidate variable name in order; first one *present* wins # (an empty value like PASSWORD='' counts as set). for n in names: if n in os.environ: used.append(n) return os.environ[n] if default is not None: return default sys.exit(f"Missing {names[0]} for target {target}.") uri = get(f"NEO4J_URI{sfx}") user = get(f"NEO4J_USERNAME{sfx}", f"NEO4J_USER{sfx}", default="neo4j") password = get(f"NEO4J_PASSWORD{sfx}") # Database lookup order: # LOCAL target: NEO4J_DATABASE_LOCAL, then NEO4J_DATABASE_EEDI # DEFAULT target: NEO4J_DATABASE_EEDI, then NEO4J_DATABASE # ...then DEFAULT_DATABASE. NEO4J_DATABASE_EEDI sits above the generic # NEO4J_DATABASE so this graph doesn't land in a database meant for something else. db_vars = ([f"NEO4J_DATABASE{sfx}"] if sfx else []) + ["NEO4J_DATABASE_EEDI"] + ([] if sfx else ["NEO4J_DATABASE"]) database = get(*db_vars, default=DEFAULT_DATABASE) return uri, user, password, database, used def build_jsonl(tag: str, dest: Path) -> None: """Run csv_to_jsonl.py (shipped alongside this script): download CSVs, write JSONL.""" try: import csv_to_jsonl except ImportError: sys.exit(f"csv_to_jsonl.py not found next to {Path(__file__).name} - it is needed for --download") csv_to_jsonl.build(csv_to_jsonl.default_csv_dir(), dest, tag) def prepare_node(raw: dict) -> dict: """Turn a JSONL node into {labels, props}. Adds uri. The JSONL id ('eedi:construct:27') becomes the `uri` property - the single key we use to find any node, whatever its label.""" props = dict(raw["properties"]) # copy, so we don't mutate the parsed JSON props["uri"] = raw["id"] return {"labels": [safe(l) for l in raw["labels"]], "props": props} # --------------------------------------------------------------------------- loading def check_empty(session, allow_nonempty: bool, wipe: bool, where: str = ""): """Guard against loading on top of existing data by accident.""" count = session.run("MATCH (n) RETURN count(n) AS c").single()["c"] if count == 0: return if wipe: print(f"--wipe: deleting {count:,} existing nodes ...") # DETACH DELETE removes each node plus its relationships. Doing it # IN TRANSACTIONS OF 5000 ROWS commits in chunks, so deleting a large graph # doesn't need one enormous transaction held in memory. session.run( "MATCH (n) CALL { WITH n DETACH DELETE n } IN TRANSACTIONS OF 5000 ROWS" ).consume() return if not allow_nonempty: sys.exit( f"{where} already contains {count:,} nodes. Point at a fresh database, " "or pass --allow-nonempty (merge) / --wipe (delete everything first)." ) # Neo4j's rules for database names: start with a letter; letters, digits, '.', '-'; 3-63 chars. DB_NAME = re.compile(r"^[A-Za-z][A-Za-z0-9.\-]{2,62}$") def ensure_database(driver, db: str): """Create the target database if it doesn't exist (needs Enterprise, which Neo4j Desktop provides). Database admin commands (SHOW/CREATE DATABASE) must run against the special `system` database, hence database_="system" below.""" if db in ("neo4j", "system"): return # built-in databases always exist if not DB_NAME.match(db): sys.exit(f"Invalid database name {db!r} (letters, digits, '.', '-'; 3-63 chars)") names = {r["name"] for r in driver.execute_query("SHOW DATABASES YIELD name", database_="system").records} if db.lower() in names: # Neo4j stores database names in lower case return print(f"Database '{db}' not found - creating it ...") try: # Backticks are needed because names like `eedi-v1` contain a hyphen. # WAIT blocks until the new database is online and ready for queries. driver.execute_query(f"CREATE DATABASE `{db}` IF NOT EXISTS WAIT", database_="system") except Exception as e: # e.g. Community edition / Aura: single database only sys.exit(f"Could not create database '{db}': {e}\n" "Create it yourself (CREATE DATABASE ...) or set the database to 'neo4j'.") def create_schema(session): """Constraints and indexes. All IF NOT EXISTS, so safe to re-run. A uniqueness constraint does two jobs: it stops duplicates, and it creates an index behind the scenes. That index is what makes the MERGE / MATCH on `uri` during loading a fast lookup instead of a scan of every node.""" stmts = [ # The loading key: every node has the EediNode label and a unique uri. "CREATE CONSTRAINT eedi_uri IF NOT EXISTS FOR (n:EediNode) REQUIRE n.uri IS UNIQUE", # The human-facing keys: integer ids per label, for queries like # MATCH (c:Construct {constructId: 27}). "CREATE CONSTRAINT subject_id IF NOT EXISTS FOR (n:Subject) REQUIRE n.subjectSubjectId IS UNIQUE", "CREATE CONSTRAINT topic_id IF NOT EXISTS FOR (n:Topic) REQUIRE n.topicSubjectId IS UNIQUE", "CREATE CONSTRAINT subtopic_id IF NOT EXISTS FOR (n:SubTopic) REQUIRE n.subTopicSubjectId IS UNIQUE", "CREATE CONSTRAINT construct_id IF NOT EXISTS FOR (n:Construct) REQUIRE n.constructId IS UNIQUE", "CREATE CONSTRAINT misconception_id IF NOT EXISTS FOR (n:Misconception) REQUIRE n.misconceptionId IS UNIQUE", # Full-text (Lucene) index for word search across names, e.g. # CALL db.index.fulltext.queryNodes('eedi_text', 'place value') "CREATE FULLTEXT INDEX eedi_text IF NOT EXISTS " "FOR (n:Subject|Topic|SubTopic|Construct|Misconception) ON EACH [n.name]", ] for s in stmts: # .consume() runs the query to completion and discards the (empty) result. session.run(s).consume() # Indexes build in the background; wait (up to 300s) until they're ready to use. session.run("CALL db.awaitIndexes(300)").consume() def load_nodes(driver, db, path: Path, batch: int) -> dict[str, int]: """Load nodes.jsonl. Returns {label: count} for verify().""" # Group nodes by label set. A label can't be a query parameter, so we need # one query per label combination, with the label written into the query text. groups: dict[tuple, list] = defaultdict(list) with open(path, encoding="utf-8") as f: for line in f: # JSONL: each line is one node n = prepare_node(json.loads(line)) groups[tuple(sorted(n["labels"]))].append(n["props"]) counts = {} for labels, rows in groups.items(): label_str = "".join(f":{l}" for l in labels) # ["Construct"] -> ":Construct" # For each row: find-or-create the node by uri (using the shared EediNode # label, so the eedi_uri constraint's index is used), then copy every # property onto it (`+=` merges the row map in) and add its real label. q = ( "UNWIND $rows AS row " "MERGE (n:EediNode {uri: row.uri}) " f"SET n += row, n{label_str}" ) for chunk in batched(rows, batch): # execute_query runs each call in its own transaction, retrying on # transient errors (e.g. a brief Aura connection blip). driver.execute_query(q, rows=chunk, database_=db) counts["|".join(labels)] = len(rows) print(f" nodes {'|'.join(labels):28s} {len(rows):>8,}") return counts def load_rels(driver, db, path: Path, batch: int): """Load relationships.jsonl. Returns {type: count} for verify().""" # Same idea as load_nodes: a relationship type can't be a parameter, so group # by type and run one query per type. Each row is shrunk to just # s(tart uri), e(nd uri) and p(roperties) to keep the payload small. groups: dict[str, list] = defaultdict(list) with open(path, encoding="utf-8") as f: for line in f: r = json.loads(line) groups[r["type"]].append({"s": r["startNodeId"], "e": r["endNodeId"], "p": r.get("properties") or {}}) counts = {} # Biggest groups first, so any problem shows up early (purely cosmetic ordering). for rtype, rows in sorted(groups.items(), key=lambda kv: -len(kv[1])): t = safe(rtype) # Look up both end nodes by uri (index lookups thanks to eedi_uri), then # find-or-create the relationship between them and copy its properties # on (e.g. `percentage` on CONSTRUCT_HAS_MISCONCEPTION). # Note: MATCH, not MERGE, for the end nodes - if a uri were missing the row # would silently produce no relationship, which verify() would then catch. q = ( "UNWIND $rows AS row " "MATCH (s:EediNode {uri: row.s}) MATCH (e:EediNode {uri: row.e}) " f"MERGE (s)-[r:{t}]->(e) " "SET r += row.p" ) for chunk in batched(rows, batch): driver.execute_query(q, rows=chunk, database_=db) counts[t] = len(rows) print(f" rels {t:32s} {len(rows):>8,}") return counts # --------------------------------------------------------------------------- derived layer # Extra properties computed from the loaded graph (not present in the source CSVs). # Handy for filtering without writing the traversal every time, e.g. # MATCH (m:Misconception) WHERE m.subjectCount = 4 RETURN m.name # Each entry is (description printed while running, Cypher query). DERIVED = [ ( "Misconception.constructCount / subTopicCount / topicCount / subjectCount (how widely it spans)", # Walk from each misconception up the tree to its Subjects, then count the # DISTINCT nodes reached at each level. A misconception tagged in 5 constructs # that all sit in one subtopic gets constructCount=5, subTopicCount=1. """MATCH (m:Misconception)<-[:CONSTRUCT_HAS_MISCONCEPTION]-(c:Construct) <-[:SUBTOPIC_CONTAINS_CONSTRUCT]-(st:SubTopic) <-[:TOPIC_CONTAINS_SUBTOPIC]-(t:Topic) <-[:SUBJECT_CONTAINS_TOPIC]-(s:Subject) WITH m, count(DISTINCT c) AS cc, count(DISTINCT st) AS stc, count(DISTINCT t) AS tc, count(DISTINCT s) AS sc SET m.constructCount = cc, m.subTopicCount = stc, m.topicCount = tc, m.subjectCount = sc""", ), ( "Construct.misconceptionCount", # COUNT { pattern } is a Neo4j 5 "count subquery": the number of matches of # that pattern for this construct. """MATCH (c:Construct) SET c.misconceptionCount = COUNT { (c)-[:CONSTRUCT_HAS_MISCONCEPTION]->(:Misconception) }""", ), ] def build_derived(session): for desc, q in DERIVED: t0 = time.time() # .counters reports what the query changed (nodes/relationships/properties). s = session.run(q).consume().counters print(f" {desc}: {s.properties_set:,} props ({time.time()-t0:.1f}s)") # --------------------------------------------------------------------------- verify def verify(session, node_counts, rel_counts): """Re-count what's in the database and compare with what we sent. Nodes use >= (the database may legitimately hold more if --allow-nonempty merged into existing data); relationships must match exactly.""" ok = True for k, expected in node_counts.items(): label = k.split("|")[0] got = session.run(f"MATCH (n:{label}) RETURN count(n) AS c").single()["c"] if got < expected: ok = False print(f" MISMATCH {label}: expected >= {expected}, got {got}") for t, expected in rel_counts.items(): got = session.run(f"MATCH ()-[r:{t}]->() RETURN count(r) AS c").single()["c"] if got != expected: ok = False print(f" MISMATCH {t}: expected {expected}, got {got}") print(" verification", "PASSED" if ok else "FAILED") return ok def main(): # ---- command-line options (description=__doc__ reuses the docstring as --help text) ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--data-dir", type=Path, default=SCRIPT_DIR, help="where the JSONL files live / are built in (default: this script's folder)") ap.add_argument("--nodes", type=Path, help="override path to nodes.jsonl") ap.add_argument("--rels", type=Path, help="override path to relationships.jsonl") ap.add_argument("--env-file", type=Path, help="dotenv file to read (default: nearest .env above this script's folder, " "then above the current folder)") ap.add_argument("--database", help=f"database name (overrides the .env value; default '{DEFAULT_DATABASE}')") ap.add_argument("--target", help="which credentials: LOCAL -> NEO4J_*_LOCAL, DEFAULT -> plain NEO4J_*. " "Required when more than one is configured.") ap.add_argument("--download", action="store_true", help="(re)build the JSONL from the CSVs first - using ../data if present, " "else downloading them from Hugging Face") ap.add_argument("--tag", default=DEFAULT_TAG, help=f"Hugging Face revision (default {DEFAULT_TAG})") ap.add_argument("--no-derived", action="store_true", help="skip the derived count properties") ap.add_argument("--batch", type=int, default=5000) ap.add_argument("--allow-nonempty", action="store_true") ap.add_argument("--wipe", action="store_true", help="DELETE ALL existing data first") args = ap.parse_args() # ---- 1. credentials and target read_env_file(args.env_file) uri, user, password, db, used = neo4j_settings(args.target) db = args.database or db # --database on the command line beats the .env print(f"Target: {uri} database '{db}' (from {', '.join(used)}{', --database' if args.database else ''})") # ---- 2. input files if args.download: build_jsonl(args.tag, args.data_dir) args.nodes = args.nodes or args.data_dir / "nodes.jsonl" args.rels = args.rels or args.data_dir / "relationships.jsonl" for p in (args.nodes, args.rels): if not p.is_file(): sys.exit(f"{p} not found - run with --download (or csv_to_jsonl.py), or pass --data-dir / --nodes / --rels") from neo4j import GraphDatabase # imported late so --help works without the driver if password == "": print("Password is empty - connecting without authentication (fine only if auth is disabled).") auth = None else: auth = (user, password) t0 = time.time() # The driver manages a pool of connections; `with` closes them all at the end. with GraphDatabase.driver(uri, auth=auth) as driver: # ---- 3. connect, create database, safety check driver.verify_connectivity() # fail fast on a wrong URI/password print(f"Connected to {uri}") ensure_database(driver, db) print(f"Using database '{db}'") # A session is a short-lived "conversation" with one database; used here for # the one-off admin queries. Bulk loading uses driver.execute_query instead. with driver.session(database=db) as s: check_empty(s, args.allow_nonempty, args.wipe, f"Database '{db}' at {uri}") # ---- 4. schema first, so the loading lookups below are indexed print("Creating constraints & indexes ...") create_schema(s) # ---- 5. data: nodes before relationships print("Loading nodes ...") nc = load_nodes(driver, db, args.nodes, args.batch) print("Loading relationships ...") rc = load_rels(driver, db, args.rels, args.batch) # ---- 6. derived properties and verification with driver.session(database=db) as s: if not args.no_derived: print("Building derived properties ...") build_derived(s) print("Verifying ...") verify(s, nc, rc) print(f"Done in {time.time()-t0:.0f}s") if __name__ == "__main__": main()