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

Shortest Path Algorithms

Finding shortest paths between nodes using built-in functions like shortestPath() and allShortestPaths().

Shortest Path Algorithms

What you'll learn: How to find the most efficient route between two nodes in a graph using Neo4j's built-in shortest path functions.

The Core Problem

In graph databases, you often need to answer: "What's the shortest way to get from point A to point B?" Think of finding the quickest route between two cities on a map, or the fewest hops between two people in a social network. Graph databases like Neo4j provide optimized built-in functions to solve this automatically.

Built-in Functions

Neo4j's Cypher offers two primary functions:

shortestPath() finds one shortest path between two nodes. If multiple paths have the same length, it returns just one arbitrarily.

allShortestPaths() returns all paths that tie for shortest. This matters when you need to see every equally-good option—like finding all the fastest routes between two people who share mutual friends.

How They Work

Both functions work with the pattern-matching syntax you've already learned. You specify the start node, end node, and relationship pattern, then wrap it in the function. The database traverses relationships efficiently using its index-free adjacency structure, avoiding the need to check every possible path manually.

Real-World Analogy

Imagine asking "How do I get from Alice to Bob?" In a poorly designed system, you'd check every possible path (Alice→Carol→Dan→Bob, Alice→Eve→Bob, etc.) and compare lengths. Shortest path algorithms use smart techniques (like breadth-first search) to find the answer without exhaustive checking—like a GPS calculating your route instantly instead of trying every street combination.

Key Takeaway: Graph databases provide shortestPath() and allShortestPaths() functions to efficiently find optimal routes between nodes, leveraging specialized traversal algorithms built into the database engine.