Guide

Graph data models

Graphs and where they fit

A graph has vertices (things) and edges (links between them). Trees of data fit documents, and simple many-to-many links fit a relational join table. When anything can link to anything, as with followers, web pages, or roads, use a graph. One graph can hold many types of vertex and edge. An adjacency list suits walking edges; an adjacency matrix suits ML.

Property graphs

Each vertex has an ID, a label (its type), and properties (key-value pairs). Each edge has an ID, a start (tail) vertex, an end (head) vertex, a label, and properties. Any vertex may link to any other, and you can walk edges both ways. One limit: an edge joins exactly two vertices, so a three-way link needs an extra vertex.

Cypher pattern matching

Cypher, made for Neo4j, writes vertices in brackets and edges as arrows. MATCH finds where a pattern fits. WITHIN*0.. means "follow WITHIN edges zero or more times", so one pattern reaches a country from a town or a state. Cypher is declarative, so the engine picks where to start.

Graph queries in SQL

In SQL, each hop is a join, and a graph walk does not know how many hops it needs. A recursive common table expression (WITH RECURSIVE) keeps adding linked rows until nothing new appears. It works, but it is far longer than Cypher. GQL, an ISO standard from 2024, may unify graph languages.

Triple stores and RDF

A triple store keeps facts as (subject, predicate, object). If the object is a value, it is a property; if it is a vertex, it is an edge. RDF came from the Semantic Web and names things with URIs so datasets can merge. Turtle writes triples line by line; RDF can also be written as wordier XML. The Semantic Web vision faded, but it left JSON-LD, Schema.org, and link previews.

Remember

  • Use a graph when links are everywhere.
  • WITHIN*0.. means zero or more hops.
  • SQL can walk graphs with recursion, clumsily.
  • Triples and property graphs are mostly the same idea.