Course contentsShow
← System Design
Lesson 456 of 1,91913. NoSQL: Graph DatabasesFree lesson

Graph Query Languages: Cypher and Gremlin

Overview of declarative query languages designed for expressing pattern matching and graph traversals.

Graph Query Languages: Cypher and Gremlin

What you'll learn: How specialized query languages make it easy to express pattern matching and graph traversals in graph databases.

Why Special Query Languages for Graphs?

Relational databases use SQL to query tables and rows. Graph databases need their own languages because they're all about finding patterns in relationships. Imagine trying to find "all friends of friends who like the same movies" — SQL requires complex self-joins, but graph query languages let you naturally describe the path you want to follow through nodes and edges.

Cypher: Declarative and Visual

Cypher (used by Neo4j) is designed to look like the graph patterns you're searching for. You use ASCII art-style syntax:

  • (node) represents a node
  • -[relationship]-> represents a directed edge
  • MATCH, WHERE, RETURN describe what to find

Think of Cypher like drawing your search pattern on paper, then asking the database to find all matching occurrences in your graph.

Example concept (descriptive, not runnable):
"Match a pattern where person A knows person B, and B knows person C, where C lives in the same city as A"

Gremlin: Imperative Traversal

Gremlin (used by Apache TinkerPop-compatible databases) is more like giving step-by-step walking directions through your graph. You chain traversal steps together:

  • Start at certain nodes
  • Step across edges (out(), in())
  • Filter results
  • Transform and aggregate

Think of Gremlin as writing a recipe: "start here, move there, check this condition, collect those results."

Declarative vs Imperative

Cypher is declarative (describe what pattern you want), while Gremlin is imperative (describe how to traverse). Both excel at expressing multi-hop relationship queries that would be painful in SQL.

Key Takeaway: Cypher and Gremlin are specialized query languages that make graph pattern matching and traversals natural and efficient, replacing complex SQL joins with intuitive relationship-focused syntax.