AlgoViz

Video lesson · Chapter 1 of 5

Who is Ana's grandchild?

0:00 / 3:59

Neo4j in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Neo4j stores a property graph. A node is a thing, such as a person or an account. A relationship joins two nodes, has exactly one type and one direction, and may hold properties of its own. A label groups nodes of one kind.

The links are part of the stored data. From one node, the database can step to its neighbours without searching the rest of the graph. You describe the pattern you want in a language called Cypher, and the planner decides how to find it.

Why it exists

In a relational database a link is a matching value, found again by a join each time you ask. One or two joins are fine. A question such as "which accounts are within five steps of this one, through any shared phone or address" needs a join per step and gets hard to write and slow to run.

A graph database makes such questions short, and their cost depends on the part of the graph you touch rather than on the size of all tables. The price is that work without a starting point, such as a total over every node, gains nothing, and that a connected graph is hard to split over machines.

A short history

  1. 2007

    Neo Technology is founded in Sweden and the database, which began inside a content management product, becomes an open source project.

  2. 2010

    Neo4j 1.0 is released.

  3. 2011

    Neo4j engineers create Cypher, a language that draws the pattern to find, as an SQL-like language for graphs.

  4. 2018

    From version 3.5, Enterprise Edition becomes commercial only and its source is no longer published. Community Edition stays under GPLv3.

  5. 2024

    GQL, the graph query language standard ISO/IEC 39075, is published. Cypher accommodates most of its mandatory features.

  6. 2025

    Version numbers follow the calendar from 2025.01. Cypher 25 arrives with 2025.06. Property sharding, part of Infinigraph, is introduced in 2025.12.

Words to know

Node
A thing in the graph. It has an identity, labels and properties.
Relationship
A stored link between two nodes, with one type and one direction.
Property graph
A graph whose nodes and relationships both carry named values.
Traversal
Walking from node to node along relationships.
Anchor
The node or nodes where a query starts, usually found with an index.
Cardinality
How many rows a step of the plan produces. Growth here is what makes a graph query slow.
Dense node
A node with very many relationships, such as a country or a celebrity.
Bookmark
A token for a committed state. A later read that carries it waits until the server has caught up.

How it works

Step through the idea, or press Play.

Step 1 of 3

Anchor. An index finds the starting node by a key

Understand it

Start here

The embroidered family tree

Imagine a cloth where every person in a family is a sewn patch, and coloured threads join the patches. To find Ana's grandchildren you do not read a book of names again and again. You put a finger on Ana and follow the thread.

Following a thread with a finger
AnaBenCyDotEveparent ofmarried toThe cloth

The cloth can hold thousands of patches. Ana's question still touches three.

The product

What you get, and under which licence

Ways to run it, checked November 2026

Community EditionEnterprise EditionAura
LicenceGPLv3, open sourceCommercial, closed partsManaged service
ServersOne instanceCluster with failoverRun for you
BackupOffline dump and loadOnline backup tooRun for you
Default store formatalignedblockNot your choice
ConstraintsUniquenessAlso existence, key and typeCheck your tier
Releases are named by year and month, such as 2026.10. Some carry LTS for long-term support. Read the licence before you put Community Edition inside a product you distribute.

Two ports matter. Drivers speak the Bolt protocol on port 7687. The HTTP interface and browser listen on 7474. The query language has versions too: databases created on 2026.02 or later get Cypher 25 by default, while older ones stay on Cypher 5 unless you change the setting.

Model

Nodes, relationships and what becomes which

A small fraud graph

A fraud graph. Two customer nodes, Ana and Max, each own an account. Both accounts have used the same phone node. Ana's account sent money to a third account, the merchant.
Two customers look unrelated in their own rows. The shared phone joins them in two steps from account to account.

Turning a whiteboard into a model

You haveMake itBecause
A thing you look up or arrive atA node with a labelYou can anchor on it and walk through it
A verb between two thingsA relationshipIt becomes one step
A fact about the verb, such as an amount or a dateA relationship propertyIt can be filtered during the walk
A value many things share, such as a phoneA nodeShared values are the links fraud teams look for
A value nobody else shares, such as a birth dateA propertyA node would add a hop and say nothing
A verb with many parties or its own historyA node in the middleA relationship has exactly two ends
Choose specific types, such as SENT and OWNS. One type called RELATED with a property for the meaning forces every step to read that property.

Inside

Why a step does not need an index

The idea is often called index-free adjacency: a node's record leads to its relationships, and each relationship leads to the node at the other end. An index is needed once, to find the anchor. After that, the next node is found from the current one.

One query, two kinds of access

A bad plan starts from a label scan, which reads every node with that label.

Store formats

FormatWhereHow it storesNode limit
alignedDefault in CommunityRecords linked like lists on disk2^35, about 34 billion
blockEnterprise, default for new databases since 5.22Properties in blocks with their nodes, so fewer pages are read2^48
standard, high_limitDeprecated since 5.23Older record formatsMigrate away
The documentation says changing the format changes internal ids. That is one more reason never to store an internal id outside the database: give each node your own key.

How far does a walk spread?

E(h)=d+d2+⋯+dhd=50:;E(2)=2,550,E(3)=127,550E(h) = d + d^2 + \dots + d^h \qquad d = 50:; E(2) = 2{,}550,\quad E(3) = 127{,}550
dd is the assumed average number of relationships followed per node and hh the number of hops. The size of the whole graph is not in the formula. The exponent is: the decision it drives is a depth limit.

Language

Cypher in ten minutes

Cypher draws the pattern. Round brackets are nodes and arrows with square brackets are relationships. Always pass values as parameters, with a dollar sign, so that plans are reused and input cannot become code.

Text
// 1. Keys first: a constraint also creates the index that backs itCREATE CONSTRAINT person_id IF NOT EXISTSFOR (p:Person) REQUIRE p.id IS UNIQUE;// 2. Write once, even if the request is repeatedMERGE (a:Person {id: $from})MERGE (b:Person {id: $to})MERGE (a)-[r:FOLLOWS]->(b)ON CREATE SET r.since = datetime();// 3. People followed by those I follow, whom I do not follow yetMATCH (me:Person {id: $id})-[:FOLLOWS]->(:Person)-[:FOLLOWS]->(other:Person)WHERE other <> me AND NOT (me)-[:FOLLOWS]->(other)RETURN other.id, count(*) AS pathsORDER BY paths DESC LIMIT 10;// 4. A bounded path: one to four stepsMATCH (a:Person {id: $id})-[:FOLLOWS]->{1,4}(b:Person)RETURN DISTINCT b.id LIMIT 100;// 5. The shortest connectionMATCH p = SHORTEST 1 (a:Person {id: $a})-[:FOLLOWS]-+(b:Person {id: $b})RETURN length(p);
MERGE matches the whole pattern or creates the whole pattern, which is why each node is merged on its key before the relationship is.

How to read a slow query

  1. 1

    PROFILE it

    EXPLAIN shows the plan. PROFILE runs it and shows the rows and the database hits of every step.

  2. 2

    Check the anchor

    A NodeIndexSeek or unique seek is good. AllNodesScan or a label scan means a missing index or a missing label.

  3. 3

    Find the growth

    Look for the step where rows jump. That expansion needs a type, a direction, a filter or a lower depth.

  4. 4

    Cut duplicates early

    WITH DISTINCT before the next expansion, and LIMIT before collecting.

Speed

Indexes and constraints

  • Range

    Equality, ranges, prefixes and ordering. The everyday index for keys and dates.

  • Text and point

    Text for string predicates such as contains and ends with. Point for places and distances.

  • Token lookup

    Finds nodes by label and relationships by type. Two exist when a database is created: keep them.

  • Full-text and vector

    Search indexes backed by Apache Lucene. Vector search is approximate, for meaning and similarity.

A uniqueness constraint does two jobs: it protects the data, and it makes MERGE on that key fast and safe when two requests arrive together. The vector index lets a retrieval system find similar text and then walk to related facts, which people call GraphRAG. Word search itself belongs to full-text search.

Transactions

ACID, locks and lost updates

All access runs in ACID transactions. The default is read committed: a reader does not block a writer. Writers lock the nodes and relationships they change. Creating or deleting a relationship also involves the nodes at its ends, so many writers attaching links to one popular node queue up behind each other. What the levels allow is explained in isolation levels.

Safe

  • SET n.count = n.count + 1 in one statement: the write lock is taken first
  • Take a lock on one agreed node before a read-then-decide
  • Driver transaction functions, which retry transient errors
  • Work that is safe to repeat

Risky

  • Read the value, compute in the application, write it back
  • Updating the same two nodes in different orders: deadlock
  • Loading ten million rows in one transaction: changes are held in memory
  • Calling a payment service inside a retried function

A deadlock and its retry

Sort keys before writing and most of these never happen. See also concurrency control.

Growth

Clusters: primaries, secondaries and bookmarks

One database in a cluster

An application driver sends writes to the leader among three primaries, which replicate among themselves. A secondary receives the transaction log later and returns rows to the application when it reads.
A write is safe once a majority of primaries has it. The secondary is filled later, so it can lag.

How many primaries?

M=2F+1F=1⇒M=3,F=2⇒M=5M = 2F + 1 \qquad F = 1 \Rightarrow M = 3,\qquad F = 2 \Rightarrow M = 5
To survive FF failed primaries you need MM of them. With too many down, the database becomes read-only. More primaries make writes slower, so add secondaries for reads.

Reading your own write

Within one session the driver passes bookmarks for you. Between two services you must hand the bookmark over yourself. Without one, a lagging read is normal: see consistency models.

Ways to grow

NeedMoveLimit
More memory for the hot partScale upThe largest machine
More readsSecondariesThey lag; each holds a full copy
Separate tenants or regionsOne database each, queried together as a composite databaseRelationships cannot cross databases
Huge property volumeProperty sharding (Infinigraph)Separate subscription; the graph shard holds all nodes and relationships
More writesSmaller transactions, fewer hot nodes, split databasesOne leader per database
Why a graph resists sharding: wherever you cut, some walks cross the cut and pay the network for every step.

Operations

Memory, loading, backup and monitoring

  1. 1

    Set memory explicitly

    The page cache holds graph data, the heap runs queries and holds transaction state. Defaults are guesses made at startup; the manual recommends setting both, and leaving room for the operating system. Vector indexes use memory outside the page cache.

  2. 2

    Load in the right tool

    First load of billions: the offline neo4j-admin database import. Regular loads: batches with UNWIND $rows, or CALL { ... } IN TRANSACTIONS.

  3. 3

    Back up and restore

    Enterprise has online backup. Community stops the database and dumps it. A secondary is not a backup: a wrong delete is copied to it.

  4. 4

    Watch

    Page cache hit ratio, heap and garbage collection pauses, slow query log, checkpoint time, secondary lag and the number of open transactions.

Keeping the graph in step with the system of record

Often the graph is a second view. Feed it with change data capture, make writes repeatable with MERGE, and be ready to rebuild it.

Decide

When to choose it, and when not

Choose it when

  • Questions walk three or more steps, or an unknown number
  • The path itself is the answer: fraud rings, access rights, dependencies
  • Relationships change often and have facts of their own
  • Anchored queries touch a small neighbourhood

Do not when

  • Queries are lists, filters and one join
  • You total a billion rows: use a column store such as ClickHouse
  • Writes far exceed one leader
  • A graph library in memory, run once a night, is enough

Alternatives

ChoiceBetter whenWeaker when
PostgreSQL with recursive queriesOne or two hops, data already thereDeep patterns and path conditions
Adjacency lists in a key-value storeOnly "who are the neighbours", at enormous scaleAnything past two hops is your own code
Another graph databaseYou need a managed cloud service or another licenceCypher dialects and features differ
A graph algorithm libraryBatch ranking and communitiesLive transactional queries
How a large social graph is served is worked through in LinkedIn connection graph.

Cost has three parts: memory for the hot graph, the licence if you need failover or online backup, and a second data model your team must feed and operate. For a first version, recursive SQL on the database you already run is often the honest answer.

Summary

The whole topic in one minute.

Neo4j keeps links as data. A query finds one or a few anchor nodes through an index and then follows relationships, so the cost is the number of steps it takes and not the size of the database.

Model the links you will walk as relationships with clear types, put a uniqueness constraint on every lookup key, bound the depth of paths and beware of dense nodes. Writes go to one leader per database and need a majority of primaries. Reads scale with secondaries and stay causally consistent with bookmarks.

  • Links are stored, so a step follows data and needs no join.
  • Find the anchor with a constraint or index, then expand by type and direction.
  • Bound every path. Work grows as degree to the power of hops.
  • Dense nodes hurt reads through fan-out and writes through locks.
  • Community is one GPLv3 instance. Clusters and online backup are Enterprise.
  • One leader per database: 2F + 1 primaries, secondaries for reads, bookmarks for your own writes.

Sources