Skip to content

What is TypeGraph?

TypeGraph is a TypeScript-first, embedded knowledge graph library that brings property graph semantics and ontological reasoning to applications using standard relational databases. Rather than introducing a separate graph database, TypeGraph lives inside your application as a library, storing graph data in your existing SQLite or PostgreSQL database.

TypeGraph Architecture: Your application imports TypeGraph as a library dependency. TypeGraph uses Drizzle ORM to store graph data (nodes, edges, schema, ontology) in your existing SQLite or PostgreSQL database. No separate graph database required.

Zod schemas are the single source of truth. From one schema definition, TypeGraph derives:

  • Runtime validation rules
  • TypeScript types (inferred, not duplicated)
  • Database storage requirements
  • Query builder type constraints
const Person = defineNode("Person", {
schema: z.object({
fullName: z.string().min(1),
email: z.string().email().optional(),
dateOfBirth: z.date().optional(),
}),
});

2. Semantic Layer with Ontological Reasoning

Section titled “2. Semantic Layer with Ontological Reasoning”

Type-level relationships enable sophisticated inference:

Relationship Meaning Use Case
subClassOf Instance inheritance (Podcast IS-A Media) Query expansion
broader Hierarchical concept (ML broader than DL) Topic navigation
equivalentTo Same concept, different name Cross-system mapping
disjointWith Cannot be both (Person ≠ Organization) Constraint validation
implies Edge entailment (marriedTo implies knows) Relationship inference
inverseOf Edge pairs (manages/managedBy) Bidirectional queries

The schema and ontology are stored in the database as data, enabling:

  • Runtime schema introspection
  • Versioned schema history
  • Self-describing exports and backups
  • Migration tooling

Queries compile to an AST before targeting SQL:

  • Consistent semantics across SQLite and PostgreSQL
  • Type-checked at compile time
  • Query results have inferred types

Every node and edge has a valid-time window (validFrom / validTo), so you can ask what was true at a domain instant with .temporal("asOf", T) or store.asOf(T). Stores created with { history: true } also capture recorded time for TypeGraph-managed writes, the system-time axis that remembers when the graph wrote each fact down. store.asOfRecorded(T) reconstructs what the graph captured at a recorded instant, and store.asOf(validT).asOfRecorded(recordedT) pins both axes independently.

Use it for audit trails, agent decision replay, effective-dated policies, and breach forensics. See Temporal queries and the Bitemporal Time Travel example.

TypeGraph is a library dependency, not a networked service. TypeGraph initializes with your application, uses your database connection, and requires no separate deployment.

Define your schemas once with Zod, and TypeGraph handles validation, type inference, and storage. No duplicate type definitions or manual synchronization.

TypeGraph favors explicit declarations:

  • Relationships are declared, not inferred from foreign keys
  • Semantic relationships are explicit in the ontology
  • Cascade behavior is configured, not assumed

The query builder generates portable ASTs that can target different SQL dialects. The same query code works with SQLite and PostgreSQL.

TypeGraph deliberately excludes:

  • Advanced graph analytics: No PageRank, community detection, weighted shortest path, or centrality measures beyond degree
  • Distributed storage: Single-database deployment only

These exclusions keep TypeGraph focused and maintainable.

Note: TypeGraph does support semantic search via native database vector engines: pgvector for PostgreSQL, sqlite-vec for the local (better-sqlite3) SQLite backend, and libSQL’s built-in vectors for the libSQL / Turso backend. See Semantic Search for details.

Note: TypeGraph does support fulltext search — native BM25 on SQLite (FTS5) and tsvector + GIN on PostgreSQL, with a query-builder n.$fulltext.matches() predicate that composes with any other predicate. Combine with semantic search for hybrid RAG retrieval. See Fulltext Search for details.

Note: TypeGraph does support variable-length paths via .recursive() with configurable depth limits, optional path/depth projection, and explicit cycle policy. Cycle prevention is the default. See Recursive Traversals for details.

Note: TypeGraph ships Tier 1 graph algorithms (shortest path, reachability, neighborhoods, and degree) on store.algorithms.*. Each call compiles to a single recursive CTE. See Graph Algorithms for details.

Note: TypeGraph supports runtime schema induction via graph extensions. An LLM or ingestion agent can propose a typed schema as a JSON-serializable document, an operator approves it, and store.evolve() atomically commits a new schema version — no redeploy, full Zod validation, restart parity. See Graph Extensions for the agent-driven workflow.

Note: TypeGraph ships graph merge — fork a store into isolated working copies, let many writers (parallel agents, importers, reviewers) edit independently, then reconcile them into one canonical graph with deterministic entity resolution (exact / blocking / fulltext / vector / hybrid), edge repointing, conflict reporting, and provenance. mergeIncremental() folds new sources into a live graph without creating duplicates — the primitive for multi-agent knowledge-graph construction and continuous ingestion. See Graph Merge for the full guide.

Note: TypeGraph supports bitemporal graph reads. Valid time answers “when was this fact true in the domain?” Recorded time answers “when did the graph record it?” Together they reconstruct prior captured state after corrections, replay agent decisions against the graph they actually saw, and traverse access graphs at a breach instant for TypeGraph-managed writes. See Temporal queries and the Agent Decision Replay example.

Compared to Graph Databases (Neo4j, Amazon Neptune)

Section titled “Compared to Graph Databases (Neo4j, Amazon Neptune)”

Graph databases are powerful but come with operational overhead:

Aspect Graph Database TypeGraph
Deployment Separate service to manage, scale, and monitor Library in your app, uses existing database
Network Additional latency for every query In-process, no network hop
Transactions Separate transaction scope from your SQL data Same ACID transaction as your other data
Learning curve New query language (Cypher, Gremlin) TypeScript you already know
Graph algorithms Built-in (PageRank, shortest path, community detection) Tier 1 only (shortest path, reachability, neighborhoods, degree)
Scale Optimized for billions of nodes Best for thousands to millions

Choose TypeGraph when your graph is part of your application domain (knowledge bases, org charts, content relationships) rather than a standalone analytical system.

Compared to ORMs (Prisma, Drizzle, TypeORM)

Section titled “Compared to ORMs (Prisma, Drizzle, TypeORM)”

ORMs model relations through foreign keys, which works well for simple associations but lacks graph semantics:

Aspect Traditional ORM TypeGraph
Relationships Foreign keys, eager/lazy loading First-class edges with properties
Traversals Manual joins or N+1 queries Fluent traversal API, compiled to efficient SQL
Inheritance Table-per-class or single-table Semantic subClassOf with query expansion
Constraints Foreign key constraints Disjointness, cardinality, implications
Schema Migrations alter tables Schema versioning, JSON properties

Choose TypeGraph when you need to traverse relationships, model type hierarchies, or enforce semantic constraints beyond what foreign keys provide.

Triple stores and RDF provide rich ontological modeling but have practical challenges:

Aspect Triple Store TypeGraph
Type safety Runtime validation, stringly-typed Full TypeScript inference
Query language SPARQL (powerful but verbose) TypeScript fluent API
Schema OWL/RDFS (complex specification) Zod schemas (familiar, composable)
Integration Separate system, data sync required Embedded in your app
Inference Full reasoning engines available Precomputed closures, practical subset

Choose TypeGraph when you want ontological concepts (subclass, disjoint, implies) without the complexity of full semantic web stack.

TypeGraph is designed for applications where:

  1. The graph is your domain model — not a separate analytical system
  2. You already use SQL — and don’t want another database to manage
  3. Type safety matters — you want compile-time checking, not runtime surprises
  4. Semantic relationships help — inheritance, implications, constraints add value
  5. Scale is moderate — thousands to millions of nodes, not billions

TypeGraph is ideal for:

  • Knowledge bases with typed entities and relationships
  • Organizational structures with hierarchies and roles
  • Content graphs with topics, articles, and references
  • Domain models requiring semantic constraints
  • RAG applications combining graph traversal with vector search
  • Multi-source ingestion & entity resolution — reconcile parallel agent or importer outputs into one canonical graph with graph merge
  • Auditable AI systems and forensics — reconstruct the graph an agent or investigator saw at a recorded instant with bitemporal reads

TypeGraph is not ideal for:

  • Large-scale graph analytics requiring distributed processing
  • Social networks with billions of edges
  • Real-time streaming graph data
  • Applications requiring advanced graph algorithms such as PageRank, community detection, or weighted shortest path (use Neo4j or a graph library; Tier 1 connectivity algorithms ship on store.algorithms.*)