DEV Community

Cover image for Graph Databases: When Relationships Are the Data
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

Graph Databases: When Relationships Are the Data

Some questions are about things: "what is this user's email?". Others are about connections: "which people does Sara know through at most three introductions?", "which accounts share a phone number with an account flagged for fraud?", "what depends on this package, directly or indirectly?". Relational databases answer the first kind very well. For the second kind, where the path between records is the answer, a graph database is often the better fit.

The property graph model

Most graph databases, such as Neo4j, Memgraph and Amazon Neptune, use the property graph model:

  • Nodes are the entities: a person, a company, a product. A node has one or more labels (Person, Company) and properties (key and value pairs, like name: "Sara").
  • Relationships (edges) connect two nodes. Each has a type (KNOWS, WORKS_AT, BOUGHT), a direction, and can have its own properties (since: 2021).

The key point: relationships are stored as first-class data, not computed at query time. In SQL, a relationship is a foreign key value that you match during a join. In a graph database, it is a stored record that points to both ends.

There is another family, RDF triple stores, which model data as subject, predicate, object triples and are queried with SPARQL. They are common in linked data and knowledge graphs. This article focuses on property graphs.

Why multi-hop queries are cheap: index-free adjacency

Take the question "friends of friends of Sara". In SQL, with a friendships(person_id, friend_id) table:

SELECT DISTINCT f2.friend_id
FROM friendships f1
JOIN friendships f2 ON f2.person_id = f1.friend_id
WHERE f1.person_id = 42;
Enter fullscreen mode Exit fullscreen mode

Each hop is another join. Each join looks up rows in an index, and an index lookup in a B-tree costs time that grows with the size of the table (logarithmically). For two hops this is fine. For five or six hops, or for "any path up to length N", the query gets long and the intermediate results can explode.

Native graph databases use index-free adjacency: each node record points directly to its relationship records, and each relationship points to its two nodes. Moving from a node to its neighbours means following stored pointers, not searching an index. The cost of a traversal depends on how much of the graph you actually touch, not on the total size of the database.

This is the core trade. A graph engine is built to walk from a starting point along connections. It is not built to scan and aggregate every record, which is what column stores and SQL engines do well.

Querying with Cypher

Cypher is the query language of Neo4j and several other graph databases, and the ISO GQL standard grew out of the same ideas. You describe a pattern with ASCII art: (node) and -[:RELATIONSHIP]->.

Create some data:

CREATE (s:Person {name: "Sara"})-[:KNOWS]->(a:Person {name: "Amine"}),
       (a)-[:KNOWS]->(y:Person {name: "Yasmine"}),
       (y)-[:WORKS_AT]->(:Company {name: "Acme"})
Enter fullscreen mode Exit fullscreen mode

Friends of friends of Sara, excluding people she already knows:

MATCH (s:Person {name: "Sara"})-[:KNOWS]->()-[:KNOWS]->(fof)
WHERE NOT (s)-[:KNOWS]->(fof) AND fof <> s
RETURN DISTINCT fof.name
Enter fullscreen mode Exit fullscreen mode

Everyone within one to four hops, a query that is awkward in SQL:

MATCH (s:Person {name: "Sara"})-[:KNOWS*1..4]->(p)
RETURN DISTINCT p.name
Enter fullscreen mode Exit fullscreen mode

And the shortest connection between two people:

MATCH path = shortestPath(
  (:Person {name: "Sara"})-[:KNOWS*]-(:Person {name: "Yasmine"})
)
RETURN path
Enter fullscreen mode Exit fullscreen mode

The pattern reads like the whiteboard drawing you would make to explain the question. That readability is a real benefit when queries involve many relationship types.

Note that the starting node still has to be found. Graph databases have ordinary indexes on properties (for example on Person.name) for that first lookup, then traversal takes over.

Where graphs fit well

  • Fraud detection. Accounts, devices, cards, phone numbers and addresses form a graph. Rings of accounts sharing devices or cards show up as connected clusters.
  • Recommendations. "People who bought this also bought" is a two-hop walk: product to buyers to their other products.
  • Social and organizational networks. Followers, mutual connections, reporting lines, permissions inherited through groups.
  • Dependency and impact analysis. Packages, services, network devices: "what breaks if this goes down?" is a traversal.
  • Knowledge graphs. Entities and typed relations between them, often used to give search or AI systems structured context.
  • Routing and logistics. Shortest or cheapest paths through a network, with algorithms like Dijkstra.

Many graph platforms also ship graph algorithm libraries: PageRank, community detection, centrality, similarity. These are useful for analytics on top of the stored graph.

Where they do not

  • Simple CRUD with few relationships. Users, orders, invoices with one or two joins are what relational databases are made for, with mature tooling, constraints and reporting.
  • Large aggregations. "Total revenue per month" scans many records and walks few connections. A relational or analytical database does this better.
  • Very large graphs that must be sharded. Splitting a graph across machines is hard, because traversals cross partitions. Some products do it, but it adds latency and complexity.

Alternatives before adopting a new database

You do not always need a dedicated engine:

  • Recursive CTEs in PostgreSQL, MySQL and SQLite handle hierarchies and bounded traversals (WITH RECURSIVE).
  • Apache AGE adds openCypher queries to PostgreSQL as an extension.
  • Some relational databases have added graph query features on top of their tables.

If your graph queries are occasional and shallow, these may be enough. If traversals are the heart of the product, a native graph database is worth it.

Common mistakes

  • Making everything a node. Properties like a person's birth date are better as properties, not as separate Date nodes, unless you really query through them.
  • Unbounded variable-length paths. [:KNOWS*] without an upper bound can explore a huge part of the graph. Set limits.
  • Super nodes. A node with millions of relationships (a celebrity account, a "country: Algeria" node) slows down every traversal that passes through it. Model around it, for example with more specific relationship types.
  • No index on the starting point. Traversal is fast, but finding the first node without an index is a full scan.

In short

A graph database stores relationships as data, so walking from one record to its neighbours costs pointer hops instead of index lookups. That makes multi-hop questions (friends of friends, fraud rings, dependency chains, shortest paths) natural to write and fast to run. Use one when the connections are the main thing you query, and stay relational when your work is mostly rows, joins of one or two levels and aggregates.

Watch the animated version: https://youtu.be/1OOn3m98tCw


Originally published at abdeldjalilchougui.biz.

Top comments (0)