# Cypher Query Language - A Beginner's Guide ## Core Concept: ASCII Art Pattern Matching Cypher queries look like ASCII art! The syntax visually represents the patterns you're trying to match in your graph. ```(node1)-[relationship]->(node2)``` ## Basic Building Blocks 1. Nodes * Represented with parentheses: `()` * Labels use a colon: `(:Person)` * Properties use curly braces: `(:Person {name: "John"})` ```MATCH (p:Person {name: "John"}) RETURN p``` 2. Relationships * Represented with square brackets: `[]` * Arrows show direction: `->` or `<-` * Types use colon: `[:WORKS_AT]` * Properties in curly braces: `[:WORKS_AT {since: 2020}]` ```MATCH (:Person)-[r:WORKS_AT]->(c:Company) RETURN r, c``` 3. Common Commands * `MATCH`: Find patterns in your graph * `WHERE`: Filter results * `RETURN`: Specify what to output * `CREATE`: Make new nodes/relationships * `MERGE`: Create if doesn't exist * `SET`: Update properties * `DELETE`: Remove nodes/relationships ## Common Patterns ### Finding Connected Nodes ```cypher // Find John's friends MATCH (john:Person {name: "John"})-[:FRIENDS_WITH]->(friend:Person) RETURN friend.name ``` ### Creating Relationships ```cypher // Make John work at Acme Corp MATCH (p:Person {name: "John"}) MATCH (c:Company {name: "Acme Corp"}) CREATE (p)-[:WORKS_AT {since: 2024}]->(c) ``` ### Optional Matching ```cypher // Find all people and their managers (if they have one) MATCH (p:Person) OPTIONAL MATCH (p)-[:MANAGED_BY]->(manager:Person) RETURN p.name, manager.name ``` ### Aggregation ```cypher // Count employees per company MATCH (c:Company)<-[:WORKS_AT]-(p:Person) RETURN c.name, COUNT(p) as employee_count ``` ## Best Practices ### Start Small * Begin with simple patterns * Add complexity gradually * Test each part separately ### Use Parameters * Instead of: `{name: "John"}` * Use: `{name: $personName}` * Prevents injection, improves caching ### Name Your Patterns * Use meaningful variable names * Makes queries more readable * Helps with maintenance ### Limit Results * Use LIMIT for large datasets * Add ORDER BY for consistency * Consider pagination ## Interactive Learning Resources * Neo4j's Official Sandbox: https://neo4j.com/sandbox/ + Free interactive environment + Comes with sample datasets + Guided tutorials * Neo4j Browser Tutorial: + Type `:play cypher` in Neo4j Browser + Interactive, step-by-step lessons + Real-time feedback * Cypher Manual: https://neo4j.com/docs/cypher-manual/ + Comprehensive reference + Detailed examples + Best practices