Cypher Essentials
1. Introduction
Cypher is a declarative query language for graph databases, primarily used with Neo4j. It allows users to express complex graph patterns in a simple and readable manner. This lesson aims to provide essential knowledge about Cypher, including its syntax, key concepts, and best practices.
2. Key Concepts
- Nodes: The primary entities in a graph (e.g., people, products).
- Relationships: Connections between nodes that link them (e.g., friends, purchases).
- Properties: Attributes associated with nodes and relationships (e.g., name, age).
- Labels: A way to categorize nodes (e.g., Person, Product).
3. Query Syntax
Cypher syntax is designed for clarity and conciseness. Here's a basic structure:
MATCH (n:Person)-[r:FRIENDS_WITH]->(m:Person)
RETURN n.name, m.name
This query matches two nodes labeled as Person
with a relationship FRIENDS_WITH
and returns their names.
3.1 Creating Nodes and Relationships
CREATE (a:Person {name: 'Alice', age: 30}),
(b:Person {name: 'Bob', age: 25}),
(a)-[:FRIENDS_WITH]->(b)
3.2 Updating Nodes
MATCH (a:Person {name: 'Alice'})
SET a.age = 31
3.3 Deleting Nodes and Relationships
MATCH (a:Person {name: 'Bob'})
DELETE a
4. Best Practices
- Always use labels for clarity.
- Limit the number of results returned with
LIMIT
to improve performance. - Utilize indexes for faster lookups on properties.
- Write readable queries using line breaks and indentation.
5. FAQ
What is Cypher?
Cypher is a query language for graph databases which allows you to describe the data you want to retrieve from the database in a declarative manner.
Is Cypher specific to Neo4j?
Yes, Cypher is primarily designed for use with Neo4j, but similar syntax is adopted in other graph databases.
Can I use Cypher for complex queries?
Yes, Cypher is capable of handling complex queries involving multiple relationships and patterns.