Databases 19 min read

Master Neo4j: Complete Beginner’s Guide, Core Concepts, Cypher Commands, and Spring Boot Integration

This article introduces Neo4j, explains how graph databases differ from relational tables, walks through three installation methods, details nodes, relationships, and paths, provides extensive Cypher examples for creating, querying, updating, and deleting data, and shows how to integrate Neo4j with Spring Boot, plus pros, cons, and use cases.

Su San Talks Tech
Su San Talks Tech
Su San Talks Tech
Master Neo4j: Complete Beginner’s Guide, Core Concepts, Cypher Commands, and Spring Boot Integration

Graph databases have become essential for knowledge graphs, recommendation systems, and AI agents. Unlike relational databases that store relationships in tables, Neo4j stores data as nodes and relationships, representing the data as a natural social network.

What is Neo4j?

Neo4j is a graph database where a "graph" means a network of nodes (entities) and relationships (edges). MySQL stores "who is who" in tables, while Neo4j stores "who is related to whom" directly as a graph.

Installation

Desktop (recommended for beginners)

Download the appropriate installer from the Neo4j official deployment center (Mac .dmg, Windows .exe, Linux .AppImage).

Install by dragging the Neo4j Desktop icon to Applications (Mac) or running the .exe (Windows).

Create a new local DBMS, set a password, and click Create.

Start the database and open the Browser at http://localhost:7474.

Docker (for users familiar with Docker)

docker run -d --name neo4j \
  -p 7474:7474 -p 7687:7687 \
  -e NEO4J_AUTH=neo4j/your_password_here \
  -e NEO4J_dbms_memory_heap_initial__size=1G \
  -e NEO4J_dbms_memory_heap_max__size=2G \
  -e NEO4J_dbms_memory_pagecache_size=1G \
  -v $HOME/neo4j/data:/data \
  neo4j:5.26.2

Key parameters: -p 7474:7474 -p 7687:7687 maps the HTTP and Bolt ports. -v $HOME/neo4j/data:/data persists data. -e NEO4J_AUTH=… enables authentication (required from Neo4j 5.x).

Memory settings ( heap_initial__size, heap_max__size, pagecache_size) affect performance; omit them and the container may fail to start or be OOM‑killed.

Homebrew (macOS command‑line lovers)

brew tap neo4j/neo4j
brew install neo4j
brew services start neo4j

After any installation, verify the service by opening http://localhost:7474 and running RETURN 1 AS result in the Browser.

Core Concepts: Nodes, Relationships, Paths

Node

A node represents an entity such as a user, movie, or address. Nodes can have labels (e.g., Person, Engineer) and properties (key‑value pairs).

CREATE (n:Person:Student {name: "张珊", age: 22, city: "北京"})
RETURN n

Relationship

Relationships connect two nodes and have a direction, a type, and optional properties.

CREATE (alice:Person {name: "爱丽丝", age: 24}),
      (bob:Person {name: "鲍勃", age: 26})
CREATE (alice)-[r:KNOWS {since: 2021, trust_level: 5}]->(bob)
RETURN alice, r, bob

Direction matters; using -[:KNOWS]- ignores direction for bidirectional queries.

Path

A path is a sequence of relationships. Paths enable powerful traversals such as finding friends‑of‑friends.

MATCH (alice:Person {name: "爱丽丝"})-[r:KNOWS*1..3]-(friend)
RETURN alice.name, friend.name

Cypher Handbook

Creating Data

Single node: CREATE (u:User {id: 1, name: "张三", age: 25}) RETURN u Batch nodes:

CREATE (u1:User {name: "李四", age: 28}), (u2:User {name: "王五", age: 23}) RETURN u1, u2

Node + relationship (ACID transaction):

CREATE (u1:User {name: "赵六", age: 27})-[b:BUY {price: 999}]->(p:Product {name: "耳机", brand: "Sony"}) RETURN u1, b, p

Multi‑hop relationship chain:

CREATE (u1:User {name: "小红"})-[f:朋友]->(u2:User {name: "小明"})-[c:同事]->(u3:User {name: "小强"}) RETURN *

Querying Data

All nodes (development only): MATCH (n) RETURN n – avoid in production.

Conditional query:

MATCH (u:User) WHERE u.age > 25 RETURN u.name, u.age ORDER BY u.age DESC LIMIT 5

Relationship query:

MATCH (p1:Person)-[r:KNOWS]->(p2:Person) RETURN p1.name, p2.name, r.since

Two‑degree friends:

MATCH (p1:Person {name: "张三"})-[:KNOWS]->(p2:Person)-[:KNOWS]->(p3:Person) RETURN p3.name AS secondDegreeFriend

Common friends (classic graph capability):

MATCH (p1:Person {name: "张三"})-[:KNOWS]-(common)-[:KNOWS]-(p2:Person {name: "李四"}) RETURN common.name AS commonFriend

Shortest path:

MATCH p = shortestPath((alice:Person {name: "爱丽丝"})-[*]-(bob:Person {name: "鲍勃"})) RETURN p

All shortest paths:

MATCH p = allShortestPaths((a:Location {name: "A站"})-[*]-(b:Location {name: "B站"})) RETURN p

Updating Data

MATCH (u:User {name: "张三"})
SET u.age = 26, u.updated_at = datetime()
RETURN u
MATCH (u:User {name: "张三"})-[r:KNOWS]-(friend)
SET r.meeting_place = "北京"

Deleting Data

Delete a relationship only: MATCH (u:User {name: "张三"})-[r:KNOWS]-(friend) DELETE r Detach‑delete a node (removes its relationships first): MATCH (u:User {name: "王五"}) DETACH DELETE u Clear the whole database (use with backup):

MATCH (n) DETACH DELETE n

Practical Tips

Preview deletions with MATCH (n) before adding DELETE.

Always limit the scope in large graphs using WHERE on labels.

Use LIMIT for pagination when many nodes are returned.

From Neo4j 5.21 onward prefer the SHORTEST 1 syntax over shortestPath().

Spring Boot Integration

Dependency

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-neo4j</artifactId>
</dependency>

YAML Configuration

spring:
  data:
    neo4j:
      uri: bolt://localhost:7687
      authentication:
        username: neo4j
        password: your_password

Entity Mapping

import org.springframework.data.neo4j.core.schema.*;

@Data
@Node("Person")
public class Person {
    @Id @GeneratedValue private Long id;
    private String name;
    private Integer age;
    @Relationship(type = "KNOWS", direction = Relationship.Direction.OUTGOING)
    private Set<Person> friends;
}

Repository

@Repository
public interface PersonRepository extends Neo4jRepository<Person, Long> {
    Optional<Person> findByName(String name);

    @Query("MATCH (p1:Person {name: $name1})-[:KNOWS]-(common)-[:KNOWS]-(p2:Person {name: $name2}) RETURN common")
    List<Person> findCommonFriends(@Param("name1") String name1, @Param("name2") String name2);
}

Service Example

@Service
public class SocialService {
    @Autowired
    private PersonRepository personRepository;

    public void demo() {
        Person alice = new Person();
        alice.setName("爱丽丝");
        alice.setAge(24);
        personRepository.save(alice);

        List<Person> friends = personRepository.findCommonFriends("张三", "李四");
        System.out.println("共同好友个数:" + friends.size());
    }
}

Two common pitfalls: use Spring Boot 2.5+ for full Neo4j 4.4/5.x support, and prefer the SDN6 Java driver in production to avoid OGM conflicts.

Advantages of Neo4j

Exceptional relationship‑query performance thanks to the native graph storage engine.

Intuitive modeling that mirrors real‑world diagrams, reducing development and communication overhead.

Concise, declarative Cypher language that reads like natural language.

Full ACID transaction guarantees, suitable for financial or transactional workloads.

Mature ecosystem with tools such as Bloom, Graph Data Science library, and ETL connectors.

Limitations

Community edition is single‑node only; high‑availability and clustering require the Enterprise edition.

High memory consumption because the whole graph is cached for optimal traversal speed.

Horizontal scaling is limited; very large graphs (hundreds of billions of edges) may need a distributed graph database.

Write throughput is generally lower than that of relational databases due to graph‑structure maintenance.

Typical Use Cases

Neo4j excels wherever deep relationship traversal is required—social networks, recommendation engines, fraud detection, knowledge graphs, and any scenario where the answer depends on multi‑hop connections.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

graph-databaseData Modelingspring-bootInstallationNeo4jCypher
Su San Talks Tech
Written by

Su San Talks Tech

Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.