Skip to the content.

Neo4j Basics

Overview

Neo4j is a graph database designed to efficiently store, query, and traverse graph data.
It is based on the property graph model, making it ideal for social networks, recommendation engines, fraud detection, and knowledge graphs.


1. Property Graph Model

Components

| Component | Description | |———–|————-| | Node | Represents an entity (e.g., Person, Product). | | Relationship | Connects nodes and describes the type of connection (e.g., FRIENDS_WITH). | | Properties | Key-value pairs associated with nodes or relationships (e.g., name: "Alice"). | | Labels | Categorize nodes for easy querying (e.g., :Person, :Movie). |

Example


(:Person {name: "Alice", age: 30})-[:FRIENDS_WITH]->(:Person {name: "Bob", age: 25})


2. Neo4j Architecture


3. Cypher Query Language

Cypher is Neo4j’s declarative query language, optimized for graph patterns.

3.1 Basic Queries

Create Nodes

CREATE (a:Person {name: 'Alice', age: 30})
CREATE (b:Person {name: 'Bob', age: 25})

Create Relationships

MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'})
CREATE (a)-[:FRIENDS_WITH]->(b)

Read Nodes

MATCH (p:Person)
RETURN p.name, p.age

Read Relationships

MATCH (a:Person)-[r:FRIENDS_WITH]->(b:Person)
RETURN a.name, b.name

3.2 Filtering and Conditions

MATCH (p:Person)
WHERE p.age > 25
RETURN p.name, p.age

3.3 Updating Data

MATCH (p:Person {name: 'Alice'})
SET p.age = 31
RETURN p

3.4 Deleting Nodes and Relationships

MATCH (p:Person {name: 'Bob'})
DETACH DELETE p

DETACH DELETE removes the node and all its relationships.


4. Common Graph Operations

Operation Cypher Example
Find friends of a person MATCH (a:Person {name:'Alice'})-[:FRIENDS_WITH]->(b) RETURN b.name
Shortest path MATCH p=shortestPath((a:Person {name:'Alice'})-[:FRIENDS_WITH*]-(b:Person {name:'Eve'})) RETURN p
Count nodes MATCH (p:Person) RETURN count(p)
Aggregation MATCH (p:Person) RETURN avg(p.age)

5. Indexes and Constraints

CREATE INDEX FOR (p:Person) ON (p.name)
CREATE CONSTRAINT unique_name ON (p:Person) ASSERT p.name IS UNIQUE

6. Use Cases


7. Best Practices


References

```