Your First Cypher Queries
Introduction
Welcome back to Introduction to Graph Databases with Neo4j! In the previous lesson, we explored the fundamental concepts of graph databases: nodes, relationships, and properties. We learned how graph databases differ from traditional databases and why they excel at handling connected data, like our ConnectHub social network.
Now it's time to get hands-on. In this second unit, we'll write our first queries to retrieve data from the graph. By the end of this lesson, you'll be able to ask the database questions and get meaningful answers back. We'll start simply and gradually build up your querying skills.
Introducing Cypher: Neo4j's Query Language
Every database needs a way to communicate with it—a language for asking questions and getting answers. For Neo4j, that language is Cypher. Just as SQL is the standard query language for relational databases, Cypher is designed specifically for graph databases.
What makes Cypher special is its visual and intuitive syntax. Instead of thinking in terms of tables and joins, Cypher lets us describe patterns in the graph. The syntax resembles ASCII art drawings of nodes and relationships, making queries easier to read and understand. For example, we might describe a pattern like (person)-[:FRIENDS_WITH]->(friend), which visually represents a friendship connection. Don't worry if that looks unfamiliar—this unit focuses on querying nodes, and we'll cover relationships in a later lesson.
The MATCH Keyword: Finding Patterns
The foundation of most Cypher queries is the MATCH keyword. Think of MATCH as saying, "Find me this pattern in the graph." We describe what we're looking for, and Neo4j searches the graph to find all instances that match our description.
When we write a MATCH clause, we specify the pattern using parentheses for nodes and labels to identify their type. Labels are like categories or types that classify nodes. In our ConnectHub network, we have labels like User for people and Post for content they've created.
The RETURN Keyword: Getting Results Back
Finding patterns is only half the story; we also need to specify what information we want back. That's where the RETURN keyword comes in. After MATCH finds the patterns we described, RETURN tells Neo4j which parts of those patterns to send back to us. Results are always returned as a table, where each row represents one matched result and each column corresponds to something we asked for.
RETURN is flexible: we can ask for entire nodes with all their properties, or we can be selective and request only specific properties. This flexibility lets us tailor our queries to get exactly the information we need without unnecessary data. For example, returning all users might produce a table like this:
| person |
|---|
| { name: "Alice", email: "alice@email.com", age: 28, city: "New York" } |
| { name: "Bob", email: "bob@email.com", age: 34, city: "Austin" } |
| ... |
