post-graph: PostgreSQL-Backed Graph Database Library

PostgreSQL is already a graph database. A property graph is two kinds of table — vertices with a JSONB payload, and edges with a from, a to and a type — and PostgreSQL already has the rest: recursive CTEs to walk it, triggers to audit it, schemas to isolate tenants, pgvector for embeddings. post-graph is the Python API over that.
import asyncio
from post_graph import AsyncPostGraph
async def main():
client = AsyncPostGraph(dsn="postgresql://localhost:5432/postgres")
await client.connect()
await client.create_vertex_table("people", realm="acme")
await client.create_edge_table("knows", from_vertex_table="people",
to_vertex_table="people", realm="acme")
ada = await client.add_vertex("people", realm="acme", payload={"name": "Ada"})
bob = await client.add_vertex("people", realm="acme", payload={"name": "Bob"})
cy = await client.add_vertex("people", realm="acme", payload={"name": "Cy"})
await client.add_edge("knows", realm="acme", from_id=ada.id, to_id=bob.id, relation_type="knows")
await client.add_edge("knows", realm="acme", from_id=bob.id, to_id=cy.id, relation_type="knows")
# Everyone Ada can reach, walked inside PostgreSQL by a recursive CTE.
for step in await client.traverse("acme", "people", ada.id, edge_tables=["knows"], max_depth=3):
print(step["depth"], step["path"])
await client.close()
asyncio.run(main())
Because the graph is ordinary tables, an edge and the application row it describes commit in the same transaction, one backup covers both, and row-level security applies to the graph like everything else.
What you get: multi-tenant realms (shared tables or a schema per tenant), sub-grouping with space, trigger-written audit logs and append-only history, pgvector search on vertices and edges, filtered and temporal traversal, a measured subset of openCypher, and asyncpg and SQLAlchemy clients with the same public API.
What it is not: a graph engine. It makes no claim to out-run one on deep traversals over very large graphs, and the Cypher support is a subset — 179 of the openCypher TCK's 1,615 scenarios pass (details). If graph querying is your product, use a graph database.
|
Neo4j |
Apache AGE |
post-graph |
| Runs inside your PostgreSQL |
❌ |
✅ |
✅ |
| Needs no extension of its own |
n/a |
❌ |
✅ (pgvector only for embeddings) |
| Graph and application rows in one transaction |
❌ |
✅ |
✅ |
| Tables you may index, constrain and add triggers to |
n/a |
discouraged |
✅ |
| openCypher |
✅ |
✅ |
subset |
| Audit log and history built in |
enterprise |
❌ |
✅ |
The longer comparison, with sources, is in the write-up.
Using with Claude, Gemini CLI, Cursor & MCP
Looking for persistent Graph RAG memory for AI coding assistants backed by post-graph? post-graph-rag and its MCP server post-graph-rag-mcp run directly on post-graph with zero sidecar LLM API keys:
# Claude Code (zero-config local Postgres + local ONNX embeddings)
claude mcp add post-graph-rag -- uvx --python 3.12 --from "post-graph-rag-mcp[embedded,local-embed]" post-graph-rag-mcp
# Gemini CLI
gemini mcp add post-graph-rag uvx -- --python 3.12 --from "post-graph-rag-mcp[embedded,local-embed]" post-graph-rag-mcp
See the full MCP & AI Client Guide for Claude Desktop, Cursor, Windsurf, VS Code, Codex CLI, existing PostgreSQL / Neon / Supabase, and a tool walkthrough.
🧪 Runnable Examples
Ten scripts in examples/, each one capability. They need
PostgreSQL and nothing else — no LLM, no API keys:
export POSTGRES_URI=postgresql://localhost:5432/postgres
cd examples && python 01_quickstart.py
|
shows |
01_quickstart.py |
Vertices, edges, traversal, shortest path |
02_vector_search.py |
pgvector search across main and history tables |
03_realms_and_spaces.py |
Tenant isolation and sub-grouping |
04_schema_per_realm.py |
A PostgreSQL schema per tenant |
05_range_queries.py |
Range filters, ordering, counting, bulk delete on JSONB |
06_history_and_audit.py |
Append-only history and the trigger-written audit log |
07_opencypher.py |
openCypher queries |
08_transactions.py |
Graph and application tables in one transaction |
09_uuid_keys.py |
UUID keys alongside generated ids |
10_full_tour.py |
All of it, end to end |
Every one was executed against a live database before being committed.
🌟 Key Features
- Table-Per-Vertex & Table-Per-Edge Architecture: Maps graph elements directly to relational tables, taking advantage of PostgreSQL's foreign keys, indexes, and constraints.
- Hierarchical Multi-Tenancy & Space Sub-grouping:
- Macro-Isolation (
realm): Primary tenant partitioning at database or schema level.
- Micro-Isolation (
space): Optional application-level sub-grouping (space VARCHAR(255) DEFAULT 'default') within tables to segregate environments (e.g. production, staging, sandbox, or workspace spaces).
- Dual Tenant Topologies:
- Single-Schema Multi-Tenancy: Logical isolation using
realm & space column partitions.
- Schema-Per-Realm: Physical isolation creating dedicated PostgreSQL schema namespaces per tenant (
CREATE SCHEMA IF NOT EXISTS "realm_name").
- pgvector Similarity Search (
vector_search):
- Native HNSW vector indexing (
vector(dim)) for vertex embeddings.
- Cosine distance (
<=>), Euclidean L2 (<->), and Inner Product (<#>).
- Multi-scope searching across main tables, associated data history tables, or both combined (
search_scope="both").
- Autogenerated
BIGSERIAL Primary Keys & Computed fqid:
- Vertex FQID:
{realm}/{table_name}/{id}
- Edge FQID:
{realm}/{table_name}/{id} — the edge table's own name, the same shape as a vertex's.
(Before 1.14.0 it was the endpoint pair, {from_table}-{to_table}. fqid is a stored generated
column, so an edge table created by an earlier release keeps the old form.)
- Automatically populated at PostgreSQL level via
GENERATED ALWAYS AS ... STORED NOT NULL.
- Append-Only History Tables (
{table_name}_data):
- Automatically created alongside vertex and edge tables.
- Stores timestamped JSONB payload updates (
data_id, realm, space, id, payload, timestamp, embedding).
- Supports vector embeddings on data records for historical semantic matching.
- Cascades deletion when main vertex/edge is deleted (
ON DELETE CASCADE).
- Shadow Audit Logging (
{table_name}_audit):
- Operates via PostgreSQL triggers to capture all
INSERT, UPDATE, and DELETE events.
- Logs old/new row state and the initiating
user_id passed via session parameters (app.current_user_id).
- Advanced Graph Traversals & Cycle Detection:
- Recursive CTE queries for neighbor exploration, path discovery, and cycle-free shortest path calculation.
- Optional
check_cycle=True raising CyclicReferenceError during edge creation.
- Direct object-oriented traversal APIs (
vertex.to(), vertex.from_(), step.vertex(), step.add_edge_to()).
- Promoted Payload Columns:
- Hot JSONB keys become generated, indexed columns maintained by PostgreSQL, so the planner can use an index where it previously scanned.
valid_from and valid_to are promoted by default as pt_valid_from / pt_valid_to, holding the date normalised to YYYY-MM-DD; any other key can be promoted via promoted_keys as p_{key}.
- The write path is unchanged — callers keep writing plain JSON — and a table without the columns falls back to
payload->>, returning the same rows.
- openCypher Queries (
CypherSession):
- A documented Cypher subset over the same tables: a label is a vertex table, a relationship type is a
relation_type value, a property is a payload key.
- Reads compile to a single SQL statement; writes run through the client's own methods, in one transaction, so audit tables and triggers behave and a failed query leaves nothing behind.
- Conformance is measured against the openCypher TCK rather than asserted. See docs/cypher.md.
- Multiple Async Client Drivers:
- High-speed
asyncpg client (AsyncPostGraph).
SQLAlchemy v2.0 async client (SQLAlchemyPostGraph).
📦 Installation
Needs Python 3.11+ and PostgreSQL 16 or 18 with pgvector. CI runs 3.11
on 16, and 3.13 on both 16 and 18: this library's behaviour lives in the
database, so each PostgreSQL version is exercised rather than assumed.
PostgreSQL 18 gets its own job because it changed what
GENERATED ALWAYS AS (expr) means when no storage keyword is given — an error
before 18, and VIRTUAL from 18 on, which cannot be indexed. Every generated
column here says STORED, and a test asserts it against the catalogue.
Install post-graph from PyPI:
# Basic installation (includes asyncpg)
pip install post-graph
# Installation with SQLAlchemy support
pip install "post-graph[sqlalchemy]"
# Installation with all optional dependencies
pip install "post-graph[all]"
Using uv:
uv add post-graph
# or with SQLAlchemy support:
uv add "post-graph[sqlalchemy]"
PostgreSQL Setup
To enable pgvector similarity search, ensure the pgvector extension is enabled in PostgreSQL:
CREATE EXTENSION IF NOT EXISTS vector;
🏗️ Database Architecture & Multi-Tenancy Hierarchy
erDiagram
REALM ||--o{ SPACE : contains
SPACE ||--o{ VERTICES : contains
SPACE ||--o{ EDGES : contains
agent_registry {
text realm PK
bigserial id PK
varchar_255 space "Indexed optional sub-grouping (e.g. production, sandbox)"
text fqid "Generated: realm/table/id"
uuid uuid "Unique UUID identifier"
jsonb payload "JSON metadata"
vector embedding "HNSW Cosine Vector"
timestamptz created_at
timestamptz updated_at
}
agent_registry_data {
bigserial data_id PK
text realm FK
bigint id FK
varchar_255 space
jsonb payload
vector embedding
timestamptz timestamp
}
spawns {
text realm PK, FK
bigserial id PK
varchar_255 space
bigint from_id FK
bigint to_id FK
text relation_type
jsonb payload
timestamptz created_at
}
agent_registry ||--o{ agent_registry_data : "appends history"
agent_registry ||--o{ spawns : "from_id / to_id"
🚀 Quick Start Guide
import asyncio
from post_graph import AsyncPostGraph
async def main():
# 1. Initialize client
client = AsyncPostGraph(dsn="postgresql://user:password@localhost:5432/mydb")
await client.connect()
realm = "proj_alpha"
# 2. Declare Vertex & Edge tables
await client.create_vertex_table("agents", realm=realm, vector_dim=1536)
await client.create_edge_table("spawns", from_vertex_table="agents", to_vertex_table="agents", realm=realm)
# 3. Upsert Vertices with Space Sub-grouping
v_parent = await client.upsert_vertex(
table_name="agents",
realm=realm,
vertex_id=1,
space="production",
payload={"name": "The Prime Orchestrator", "caste": "genesis"},
embedding=[0.01] * 1536
)
v_progeny = await client.upsert_vertex(
table_name="agents",
realm=realm,
vertex_id=2,
space="production",
payload={"name": "Specialized Worker", "caste": "progeny"},
embedding=[0.02] * 1536
)
# 4. Create Directed Edge
edge = await client.add_edge(
table_name="spawns",
realm=realm,
from_id=v_parent.id,
to_id=v_progeny.id,
space="production",
relation_type="spawned_progeny",
payload={"reason": "Task Delegation"}
)
# 5. Query Vertices by Realm & Space
prod_agents = await client.get_vertices("agents", realm=realm, space="production")
print(f"Production agents: {[a.payload['name'] for a in prod_agents]}")
# 6. Object-Oriented Neighbor Traversal
neighbors = await v_parent.outgoing("spawns")
for step in neighbors:
print(f"Parent -> {step.vertex().payload['name']} (Edge: {step.edge.relation_type})")
await client.close()
if __name__ == "__main__":
asyncio.run(main())
⏱️ Range Queries, Ordering and Bulk Deletion
Polling a growing table must not mean fetching it. where pushes range
predicates into SQL over the JSONB payload (parameter-bound, key-validated),
order_by/limit shape the result server-side, and count_vertices /
delete_vertices complete the poll–work–purge loop without transferring rows.
# An event scheduler's tick: the few due, undone events — not the whole table.
due = await pg.find_vertices("events", realm=world,
where=[("done_at", "is_null", None), ("due_at", "<=", now_str)],
order_by="due_at", limit=200)
# A work queue's pending slice.
pending = await pg.find_vertices("decision_queue", realm="agents",
where=[("done_at", "is_null", None)], limit=500)
# Periodic purge of completed history, returning rows deleted.
purged = await pg.delete_vertices("events", realm=world,
where=[("done_at", "not_null", None), ("done_at", "<", cutoff_str)])
# Queue depth without row transfer; index the hot predicate once at startup.
depth = await pg.count_vertices("decision_queue", realm="agents",
where=[("done_at", "is_null", None)])
await pg.create_payload_index("events", realm=world, key="due_at")