Relate: A SQLite-Style Graph Database
Query a graph from your Python notebook with Relate, Neo4j’s SQLite-style embedded graph database: one file, one pip install, Cypher, and pandas.
If you've ever reached for SQLite to answer a question about a CSV, you already know the appeal: no server, one file, connect() and go. Relate (formerly CypherLite), a Neo4j project, brings that experience to graph data. It's an embedded graph database written in Rust, queried in Cypher, and runs inside your Python process.
This article uses it in a notebook on a dataset that is naturally a graph, the London Underground. We'll load stations and connections, ask questions that would need self-joins in SQL, such as:
- What's within three stops?
- Which stations are interchanges?
- How do I get from A to B?
and hand the results to pandas.
The SQLite parallels are close. The database is a single .cl file or lives in memory. The Python API is connect() and execute() with named parameters, and rows come back keyed by column name. There is no daemon to start and no connection string.
The full source code is available on GitHub.
Install And Run A First Query
The package is called relate-db on PyPI and imported as relate. Relate ships prebuilt wheels for Windows, Linux, and macOS, so there's nothing to compile. It needs Python 3.9 or later; the pinned package versions in the accompanying notebook need Python 3.11 or later.
If you've used sqlite3, the first query will look familiar:
db = relate.connect(":memory:") # or a path such as "tube.cl"
db.execute("CREATE (:Station {name: $name})", {"name": "Kennington"})
for row in db.execute("MATCH (s:Station) RETURN s.name AS name"):
print(row["name"])
execute() takes the query and a dictionary of parameters, and each row is addressable by column name. Use parameters rather than string formatting, for the same reason you would in SQL.
Load The London Underground Data
The dataset is three CSV files:
- Stations with coordinates
- Connections between neighboring stations with the line that serves them
- A list of lines
The connections file also holds other London rail lines, so the code keeps only the lines in the lines file. We'll read the files with pandas and pass the rows as a parameter. UNWIND turns the list into one row per record, similar to executemany in SQLite.
stations = pd.read_csv("data/london_stations.csv")
links = pd.read_csv("data/london_connections.csv")
lines = pd.read_csv("data/london_lines.csv")
for frame in (stations, links, lines):
frame.columns = frame.columns.str.strip()
# Keep the lines in the lines file, and only the stations those lines touch.
links = links[links["Tube Line"].str.strip().isin(set(lines["Tube Line"].str.strip()))]
used = set(links["From Station"].str.strip()) | set(links["To Station"].str.strip())
stations = stations[stations["Station"].str.strip().isin(used)]
db = relate.connect("tube.cl")
db.execute(
"UNWIND $rows AS r "
"MERGE (s:Station {name: r.name}) "
"SET s.lat = r.lat, s.lon = r.lon",
{"rows": [
{"name": str(r["Station"]).strip(), "lat": float(r["Latitude"]), "lon": float(r["Longitude"])}
for r in stations.to_dict("records")
]},
)
db.execute(
"UNWIND $rows AS r "
"MATCH (a:Station {name: r.a}), (b:Station {name: r.b}) "
"CREATE (a)-[:CONNECTS_TO {line: r.line}]->(b)",
{"rows": [
{"a": str(r["From Station"]).strip(), "b": str(r["To Station"]).strip(), "line": str(r["Tube Line"]).strip()}
for r in links.to_dict("records")
]},
)
Each connection is stored once. The queries below match it in either direction, so a trip works both ways without storing every link twice. Cypher also has LOAD CSV, which skips pandas. Relate denies local file reads unless we allow a directory explicitly, so the parameter route is the simpler approach in a notebook.
We'll check the load with a count:
print(db.execute("MATCH (s:Station) RETURN count(s) AS stations").data())
print(db.execute("MATCH ()-[r:CONNECTS_TO]->() RETURN count(r) AS links").data())
On the Underground data, this outputs 349 stations and 458 connections.
Ask Graph Questions
Three questions that need self-joins in SQL read as one pattern in Cypher.
1. What's Within Three Stops Of Kennington?
A variable-length pattern follows connections up to a limit, in either direction:
nearby = db.execute(
"MATCH p = (a:Station {name: $name})-[:CONNECTS_TO*1..3]-(b:Station) "
"WHERE a <> b "
"RETURN b.name AS station, min(length(p)) AS stops "
"ORDER BY stops, station",
{"name": "Kennington"},
).data()
Kennington has 4 neighbors, 8 more stations two stops away and 12 more at three stops, 24 in all.
2. Which Stations Are Interchanges?
Group each station's connections by line and keep the ones served by more than one:
hubs = db.execute(
"MATCH (s:Station)-[r:CONNECTS_TO]-() "
"WITH s, collect(DISTINCT r.line) AS lines "
"WHERE size(lines) > 1 "
"RETURN s.name AS station, size(lines) AS lines, lines AS served_by "
"ORDER BY lines DESC, station LIMIT 10"
).data()
Kings Cross St. Pancras comes first with 6 lines, followed by Baker Street with 5.
3. How Do I Get From Kennington To Euston?
Cypher 25 path selectors ask for the shortest paths directly. Two details matter:
- Bound the search with a hop limit, because an open-ended pattern makes the engine consider every path through a network full of loops.
- Name the line if you want one, as below.
ORIGIN, DEST, LINE = "Kennington", "Euston", "Northern"
MAX_HOPS = 10 # the shortest route is 8 hops; the bound keeps the search small
found = db.execute(
f"MATCH p = SHORTEST 3 (a:Station {{name: $origin}})-[:CONNECTS_TO {{line: $line}}]-{{1,{MAX_HOPS}}}(b:Station {{name: $dest}}) "
"RETURN [n IN nodes(p) | n.name] AS stations, length(p) AS stops ORDER BY stops",
{"origin": ORIGIN, "dest": DEST, "line": LINE},
).data()
# Keep each station sequence once.
routes = list({tuple(r["stations"]): r for r in found}.values())
On the Northern Line, the query returns the two branches in a few milliseconds:
- Charing Cross (8 stops, via Waterloo and Embankment)
- Bank (9 stops, via Elephant and Castle and Angel)
Where several lines serve the same stations, the graph holds parallel connections, and each counts as a separate path, so the same station sequence can come back more than once. We'll keep each sequence once.
Drop the line filter and the same question runs across the whole network. We ask for more paths than we need, keep the distinct station sequences, and return the line on each hop, so we can see where the route changes:
whole = db.execute(
f"MATCH p = SHORTEST 20 (a:Station {{name: $origin}})-[:CONNECTS_TO]-{{1,{MAX_HOPS}}}(b:Station {{name: $dest}}) "
"RETURN [n IN nodes(p) | n.name] AS stations, [r IN relationships(p) | r.line] AS lines, length(p) AS stops "
"ORDER BY stops",
{"origin": ORIGIN, "dest": DEST},
).data()
distinct = list({tuple(r["stations"]): r for r in whole}.values())
This takes under a second and returns 20 paths, but only two distinct routes, because most paths differ only in which parallel connection they use. The shortest has 6 stops: Northern Line to Waterloo, Jubilee Line to Green Park, then the Victoria Line through Oxford Circus and Warren Street to Euston, with two interchanges. The other has 7 stops through Bank, Moorgate and Farringdon, using the Northern, Waterloo and City, and Circle or Metropolitan Lines. Fewer stops does not mean a better trip, which is why a route's interchanges belong in the comparison.
In SQL, the same three questions require recursive CTEs or repeated self-joins.
Move Results Into Pandas
Every query above returns a list of dictionaries through .data(), which pandas takes directly:
hubs_df = pd.DataFrame(hubs)
hubs_df.plot.barh(x="station", y="lines", legend=False).invert_yaxis()
For larger results, the native Database class can return Arrow IPC bytes, which avoids building Python objects row by row. It needs the file to be free, so we'll close the earlier connection first:
db.close() # the file must be free for the native class
adb = Database("tube.cl")
buf = adb.execute_arrow("MATCH (s:Station) RETURN s.name AS name, s.lat AS lat, s.lon AS lon")
stations_df = pa.ipc.open_stream(buf).read_all().to_pandas()
adb.close()
From here, the data is an ordinary DataFrame. We can plot it, merge it with other tables, or feed it to a model, and write findings back with a parameterized UNWIND when we want them in the graph.
Keep It In One File
A path ending in .cl stores the write-ahead log, the snapshots and the catalog in a single file, so the whole graph can be copied, emailed or committed alongside the notebook. A plain directory path works too, and ":memory:" gives us a throwaway database that disappears when the process ends.
db.close()
db = relate.connect("tube.cl") # the graph is still there
print(db.execute("MATCH (s:Station) RETURN count(s) AS stations").data())
Close a connection before another one opens the same file. Relate allows one writer, and a second opener of a locked database gets an error (an OperationalError, "storage locked"), as it would in SQLite. By default, a write is acknowledged after it reaches the log, so a crash does not lose it.
Summary
Relate fits analysis on a graph that lives on a local machine: a notebook, a script, a unit test for a Cypher query, or a prototype before being moved to a server. Because the dialect is Cypher, the queries carry over to Neo4j.
Know the limits before you build on it:
- The working set must fit in RAM
- It's an engine, not a platform: it has no equivalent of Neo4j's plugin ecosystem, such as Graph Data Science, and it does not let you register your own Cypher functions
- It's a subset of what Neo4j runs, so check each feature you depend on against the documentation, and test your queries on both engines before choosing
For many applications, these trade-offs will be fine. We get a graph, a query language, and a DataFrame in one pip install, with nothing to run in the background.
In the next article, we'll see how to use Relate with TypeSafe AI's Jev, LLMs and MCP. We'll build an AI agent that navigates the London Underground while recording its decisions, alternatives, model judgments, and human interventions in a persistent, queryable graph ledger. Stay tuned!
The full source code is available on GitHub.
Opinions expressed by DZone contributors are their own.