Neo4j Cypher Cheat Sheet

Advertisement

Neo4j Cypher Cheat Sheet: In the realm of graph databases, Neo4j stands out as one of the most powerful and versatile systems available. Its query language, Cypher, allows developers and data analysts to interact with graph data efficiently and intuitively. This cheat sheet serves as a comprehensive guide to the essential Cypher syntax, functions, and patterns, making it easier for both beginners and seasoned professionals to leverage the full potential of Neo4j.

Basics of Cypher Syntax



Understanding the foundational elements of Cypher is crucial for writing effective queries. Cypher syntax is designed to be human-readable, resembling natural language, which makes it accessible.

Nodes and Relationships



In Neo4j, data is represented as nodes and relationships.

- Nodes: Represent entities (e.g., people, places, events).
- Relationships: Connect nodes and represent the associations between them.

Basic Query Structure



A Cypher query typically follows this structure:

```
MATCH (node1:Label1)-[relationship:TYPE]->(node2:Label2)
RETURN node1, relationship, node2
```

- `MATCH`: Used to specify the pattern to search for in the graph.
- `RETURN`: Specifies what to return from the query.

Creating Nodes and Relationships



Creating data in Neo4j is straightforward. Use the `CREATE` command to build nodes and relationships.

Creating Nodes



To create a single node, you can use the following syntax:

```
CREATE (n:Label {propertyKey: 'value'})
```

Example:

```
CREATE (p:Person {name: 'Alice', age: 30})
```

For multiple nodes, you can separate them with commas:

```
CREATE (p:Person {name: 'Bob', age: 25}), (p:Person {name: 'Charlie', age: 35})
```

Creating Relationships



Relationships can be created between existing nodes using:

```
MATCH (a:Label1), (b:Label2)
WHERE a.propertyKey = 'value' AND b.propertyKey = 'value'
CREATE (a)-[r:RELATIONSHIP_TYPE]->(b)
```

Example:

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

Retrieving Data



Retrieving data from Neo4j can be done using various queries depending on the required information.

Basic Retrieval



To retrieve all nodes of a specific label:

```
MATCH (n:Label)
RETURN n
```

To return specific properties:

```
MATCH (n:Label)
RETURN n.propertyKey
```

Using WHERE Clauses



The `WHERE` clause allows for filtering results:

```
MATCH (n:Label)
WHERE n.propertyKey = 'value'
RETURN n
```

Example:

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

Aggregation Functions



Cypher supports several aggregation functions:

- `COUNT()`: Counts the number of elements.
- `SUM()`: Computes the sum of a numerical property.
- `AVG()`: Computes the average of a numerical property.
- `MIN()`: Finds the minimum value.
- `MAX()`: Finds the maximum value.

Example:

```
MATCH (p:Person)
RETURN COUNT(p) AS totalPersons, AVG(p.age) AS averageAge
```

Updating Data



Updating existing nodes and relationships is crucial for maintaining accurate data.

Updating Properties



To update properties of a node:

```
MATCH (n:Label {propertyKey: 'value'})
SET n.propertyKey = 'newValue'
```

Example:

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

Deleting Nodes and Relationships



Deleting data is straightforward but should be done cautiously.

- Deleting Relationships:

```
MATCH (a:Label1)-[r:RELATIONSHIP_TYPE]->(b:Label2)
DELETE r
```

- Deleting Nodes:

To delete a node, it must not have any relationships:

```
MATCH (n:Label {propertyKey: 'value'})
DELETE n
```

If the node has relationships, you can either delete the relationships first or use `DETACH DELETE`:

```
MATCH (n:Label {propertyKey: 'value'})
DETACH DELETE n
```

Advanced Queries



Once you are comfortable with the basics, you can explore advanced querying techniques.

Pattern Comprehension



Pattern comprehension allows for complex data retrieval:

```
MATCH (a:Label1)-[r:TYPE]->(b:Label2)
RETURN [x IN collect(b.name) WHERE x STARTS WITH 'A'] AS namesStartingWithA
```

Using WITH Clause



The `WITH` clause is useful for chaining multiple operations:

```
MATCH (p:Person)
WITH p
WHERE p.age > 30
RETURN p.name
```

Indexes and Constraints



Indexes improve query performance, while constraints ensure data integrity.

Creating Indexes



To create an index on a property:

```
CREATE INDEX ON :Label(propertyKey)
```

Example:

```
CREATE INDEX ON :Person(name)
```

Creating Constraints



To ensure uniqueness:

```
CREATE CONSTRAINT ON (n:Label) ASSERT n.propertyKey IS UNIQUE
```

Example:

```
CREATE CONSTRAINT ON (p:Person) ASSERT p.name IS UNIQUE
```

Using APOC Procedures



APOC (Awesome Procedures on Cypher) provides a set of utilities to enhance Cypher's capabilities.

Commonly Used APOC Procedures



- apoc.help(): Displays available procedures.
- apoc.load.json(): Loads JSON data from a URL.
- apoc.export.csv(): Exports data to CSV format.

Example of loading JSON data:

```
CALL apoc.load.json('http://example.com/data.json') YIELD value
CREATE (n:Node {propertyKey: value.propertyKey})
```

Conclusion



The Neo4j Cypher Cheat Sheet encapsulates the essential commands and constructs needed to navigate the powerful capabilities of Neo4j effectively. By mastering these commands, users can create, retrieve, update, and delete graph data with ease. As one delves deeper into the intricacies of Cypher, the potential for data analysis and visualization becomes boundless, allowing for innovative solutions across various domains. Whether you are a newcomer or an experienced developer, this cheat sheet serves as a valuable resource in your graph database journey.

Frequently Asked Questions


What is a Neo4j Cypher cheat sheet?

A Neo4j Cypher cheat sheet is a quick reference guide that summarizes the syntax and commands used in Cypher, the query language for Neo4j, allowing users to efficiently write and understand graph queries.

What are some common Cypher commands included in the cheat sheet?

Common Cypher commands include MATCH, CREATE, DELETE, SET, RETURN, and WHERE, which are used for querying, creating, updating, and deleting data in a Neo4j graph database.

How can I use the MATCH command in Cypher?

The MATCH command is used to search for patterns in the graph. For example, 'MATCH (n:Person) RETURN n;' retrieves all nodes labeled 'Person'.

What is the purpose of the RETURN clause in Cypher?

The RETURN clause specifies which data to return from a query. It can be used to return nodes, relationships, or specific properties, such as 'RETURN n.name' to return the names of nodes.

Can the Cypher cheat sheet help with performance optimization?

Yes, the Cypher cheat sheet often includes tips on writing efficient queries, such as using indexes, avoiding Cartesian products, and leveraging the WHERE clause effectively.

How do I delete nodes and relationships in Cypher?

To delete a node or relationship, you can use the DELETE command. For example, 'MATCH (n:Person {name: 'John'}) DELETE n;' deletes the node with the name 'John'. For relationships, you would first MATCH the relationship before deleting it.

Where can I find an up-to-date Neo4j Cypher cheat sheet?

An up-to-date Neo4j Cypher cheat sheet can be found on the official Neo4j website or GitHub repositories, as well as in developer documentation and community resources.