
A fraud analyst has a simple question: "Which accounts share a phone number or a device with an account we already closed, directly or through up to three other accounts?"
In a relational database that question becomes a self-join, then a join on the result of that join, then another. The SQL grows by a screen for every extra hop, and the query slows down with it. Written for a graph database, the same question is three lines, and adding a fourth hop means changing one digit.
That is the reason Neo4j exists. Some questions are about how things are connected, and they deserve a database that stores the connections as carefully as the things.
What Neo4j is
Neo4j is a graph database. Instead of tables and rows it stores a property graph, which has four parts:
| Part | What it is | Example |
|---|---|---|
| Node | A thing | A person, an account, a product |
| Label | A tag that groups nodes | :Person, :Account |
| Relationship | A named, directed link between two nodes | (:Person)-[:OWNS]->(:Account) |
| Property | A key and value on a node or a relationship | name: 'Asha', since: 2021 |
Relationships are stored as first-class records, each pointing straight at its two nodes. Following one is a pointer hop, not an index lookup on a foreign key. So the cost of a traversal depends on how much of the graph you actually touch, not on how large the whole database is.
You query it with Cypher, a language that draws the pattern you are looking for with ASCII art: round brackets for nodes, square brackets and arrows for relationships.
MATCH (p:Person)-[:OWNS]->(a:Account)
WHERE p.name = 'Asha'
RETURN a.number, a.opened_on;
Neo4j is fully transactional (ACID), so a group of changes either all happen or none do.
Editions
Neo4j comes as a Community Edition under the GPLv3 licence, an Enterprise Edition under a commercial licence, and AuraDB, the managed cloud service run by Neo4j itself. Community Edition runs a single user database on a single server. Clustering, multiple databases, role-based access control and some constraint types belong to Enterprise and AuraDB. Check the edition before you design around a feature.
Why teams choose it
- Deep traversals stay readable and fast. "Friends of friends who bought this" is one pattern, not a pile of joins.
- The model matches the whiteboard. The circles and arrows you draw to explain a domain are close to what you store.
- Flexible schema. Nodes with the same label can carry different properties, and adding a new relationship type needs no migration.
- Path questions are built in. Shortest path, variable-length paths and "is there any route from A to B" are part of the language.
- A mature ecosystem. Official drivers for the main languages, a graph algorithms library (Graph Data Science), and Cypher itself fed into GQL, the ISO standard for graph query languages published in 2024.
Where Neo4j fits, and where it does not
A strong choice for:
- Fraud rings, identity resolution and anything where shared attributes link records
- Recommendations ("people who bought this also bought")
- Network and IT dependency maps, and impact analysis ("what breaks if this server goes down?")
- Permissions and organisational hierarchies with inheritance
- Knowledge graphs, including retrieval for AI applications
- Supply chains, routes and bills of materials
Look elsewhere when:
- Your data is simple and tabular. Orders, invoices and users with a few foreign keys are happier in PostgreSQL or MySQL.
- You mostly aggregate across everything. "Total revenue by month over ten years" is a job for an analytical database such as ClickHouse or BigQuery. A graph database shines when a query starts from a few nodes and walks outward.
- You need very high volume simple writes, such as sensor readings or logs. Use a time-series or log store.
- You store large documents or files. Keep them in a document database or object storage, and keep the identifiers in the graph.
- A recursive query would do. If you only need one tree (a category hierarchy), a recursive common table expression in a relational database may be enough.
Many teams run both: the system of record stays relational, and a graph holds the connections that are painful to query there.
Using it the right way
Examples use cypher-shell, the command-line client that ships with Neo4j. They are written for Neo4j 5.
cypher-shell -a neo4j://localhost:7687 -u neo4j
Model the questions, not the tables
Start from the questions you need to answer and draw the path each one takes. Three rules of thumb:
- Things are nodes. Verbs between things are relationships.
- Give relationship types specific names.
:PURCHASEDand:REVIEWEDare faster and clearer than one:RELATED_TOwith atypeproperty, because Neo4j can skip the types you did not ask for. - If something is shared and you want to find who shares it (a phone number, a device, an address), make it a node, not a property. That is what turns "who else uses this phone" into a one-hop question.
Constraints first, data second
A uniqueness constraint protects you from duplicates and creates the index that makes lookups fast.
CREATE CONSTRAINT person_email IF NOT EXISTS
FOR (p:Person) REQUIRE p.email IS UNIQUE;
CREATE INDEX account_number IF NOT EXISTS
FOR (a:Account) ON (a.number);
Indexes in Neo4j find the starting nodes of a query. After that, the traversal follows relationships and needs no index.
Write with MERGE, on the key only
CREATE always makes something new. MERGE finds a pattern or creates it, which is what you want when the same data may arrive twice.
MERGE (p:Person {email: 'asha@example.com'})
ON CREATE SET p.name = 'Asha', p.created_at = datetime()
ON MATCH SET p.last_seen = datetime();
MATCH (p:Person {email: 'asha@example.com'})
MERGE (ph:Phone {number: '+1-555-0100'})
MERGE (p)-[:USES]->(ph);
Merge on the unique key alone and set the other properties afterwards. MERGE matches the whole pattern you give it, so MERGE (p:Person {email: ..., name: ...}) creates a second person the day the name changes.
Read with patterns
// Who shares a phone with a closed account?
MATCH (bad:Account {status: 'closed'})<-[:OWNS]-(:Person)-[:USES]->(ph:Phone)
<-[:USES]-(other:Person)-[:OWNS]->(a:Account)
WHERE a.status = 'open'
RETURN DISTINCT a.number, ph.number
LIMIT 50;
Variable-length paths walk a range of hops. Always give an upper bound:
MATCH (a:Person {email: 'asha@example.com'})-[:KNOWS*1..3]-(b:Person)
RETURN DISTINCT b.name
LIMIT 100;
MATCH p = shortestPath(
(a:Person {email: 'asha@example.com'})-[:KNOWS*..6]-(b:Person {email: 'ben@example.com'})
)
RETURN length(p), [n IN nodes(p) | n.name];
Use parameters
Never build Cypher by gluing strings together. Parameters prevent injection and let Neo4j reuse the query plan.
:param email => 'asha@example.com';
MATCH (p:Person {email: $email})-[:OWNS]->(a:Account)
RETURN a.number;
In application code, every official driver takes the parameters as a separate map.
Load and delete in batches
One huge transaction holds every change in memory until it commits. For bulk work, split it. CALL { ... } IN TRANSACTIONS needs Neo4j 4.4 or later and must run as an auto-commit statement, which in cypher-shell and Neo4j Browser means prefixing it with :auto.
:auto LOAD CSV WITH HEADERS FROM 'file:///people.csv' AS row
CALL {
WITH row
MERGE (p:Person {email: row.email})
SET p.name = row.name
} IN TRANSACTIONS OF 1000 ROWS;
:auto MATCH (s:Session)
WHERE s.expires_at < datetime()
CALL {
WITH s
DETACH DELETE s
} IN TRANSACTIONS OF 10000 ROWS;
DETACH DELETE removes a node together with its relationships. A plain DELETE refuses to remove a node that is still connected. For a first load of a very large data set into an empty database, the offline neo4j-admin database import tool is much faster than Cypher.
Check the plan
Put EXPLAIN in front of a query to see the plan without running it, or PROFILE to run it and see how many rows each step handled.
PROFILE
MATCH (p:Person {email: 'asha@example.com'})-[:OWNS]->(a:Account)
RETURN a.number;
Look at the first operator. NodeUniqueIndexSeek or NodeIndexSeek is good. NodeByLabelScan means Neo4j is reading every node with that label, and AllNodesScan means it is reading the whole graph. Both usually point to a missing index or a missing label in the pattern.
Look after memory and backups
Neo4j is fastest when the graph fits in the page cache, the memory it uses to hold data files. On a self-managed server, set the heap and the page cache deliberately in neo4j.conf:
server.memory.heap.initial_size=4g
server.memory.heap.max_size=4g
server.memory.pagecache.size=8g
The command neo4j-admin server memory-recommendation suggests starting values for your machine. For backups, Community Edition offers an offline dump (neo4j-admin database dump neo4j --to-path=/backups, with the database stopped), while Enterprise and AuraDB support online backups. Test a restore before you need one.
Common mistakes
- Patterns without labels.
MATCH (n {email: $email})cannot use an index, so it scans every node. WriteMATCH (n:Person {email: $email}). - Unbounded paths.
-[*]-explores every route in the graph. Give an upper limit and a relationship type. - Accidental cartesian products.
MATCH (a:Person), (b:Account)with nothing joining them returns every combination. Neo4j warns about it. Listen. - Merging on too many properties, which quietly creates duplicates.
- Supernodes. A node with millions of relationships (a
:Countryevery user points at) makes any traversal through it slow. Ask whether it should be a property, or whether queries really need to pass through it. - Relying on internal ids. Internal identifiers can be reused after a delete. Keep your own unique key. In Neo4j 5,
elementId()replaces the deprecatedid(), and neither belongs in your application's data. - Forgetting direction or type on relationships in a query, so Neo4j checks far more of them than it needs to.
- Modelling tables as a graph. If every query filters a single label by its properties and never follows a relationship, you built a relational database the hard way.
Quick reference
| Task | Cypher |
|---|---|
| List databases | SHOW DATABASES; |
| Labels in use | CALL db.labels(); |
| Relationship types in use | CALL db.relationshipTypes(); |
| Picture of the schema | CALL db.schema.visualization(); |
| Indexes and constraints | SHOW INDEXES; and SHOW CONSTRAINTS; |
| Count nodes of a label | MATCH (n:Person) RETURN count(n); |
| Count relationships by type | MATCH ()-[r]->() RETURN type(r), count(*); |
| A small sample | MATCH (n:Person) RETURN n LIMIT 25; |
| Change a property | MATCH (p:Person {email: $email}) SET p.name = $name; |
| Remove a node and its links | MATCH (p:Person {email: $email}) DETACH DELETE p; |
| See the plan | EXPLAIN or PROFILE before the query |
A graph database earns its place when the connections are the question. Model those connections with clear names, anchor every query on an indexed starting node, bound every path, and Neo4j will answer in a few lines what would take a page of joins elsewhere.
Exploring Neo4j with CreamDB
A graph is easier to understand when you can see it. CreamDB has a Neo4j explorer that runs in the browser, with nothing to install.
- A schema panel lists node labels and relationship types with their counts, property keys, indexes and constraints. Click a label to see its nodes.
- Write Cypher with parameters and view the result as a table, as a graph you can look around, or as JSON. Results can be charted and exported.
- Select a node or a relationship to read its properties, edit them or delete it.
- Ask in plain English and the assistant writes the Cypher and shows the result.
The assistant's own queries run in a read transaction, so the Neo4j server itself rejects anything that would change the graph. A change it proposes waits as an approval card that you answer. With read-only mode on, only reads run, and the server enforces that. Connection passwords are encrypted at rest.
CreamDB connects over Bolt from its own servers, so your Neo4j instance (AuraDB or self-hosted) must be reachable from the internet. It is free to start.
About the author
- CreamDB is a web-based database explorer with an AI assistant. Connect your databases, ask questions in plain English and get answers, tables and charts from any browser. Product news and tips here.
Comments
Join the discussionNo comments yet. Be the first to comment.




