Depth First Search

Glossary

Directed

Directed trait. The algorithm is well-defined on a directed graph.

Directed

Directed trait. The algorithm ignores the direction of the graph.

Directed

Directed trait. The algorithm does not run on a directed graph.

Undirected

Undirected trait. The algorithm is well-defined on an undirected graph.

Undirected

Undirected trait. The algorithm ignores the undirectedness of the graph.

Heterogeneous nodes

Heterogeneous nodes fully supported. The algorithm has the ability to distinguish between nodes of different types.

Heterogeneous nodes

Heterogeneous nodes allowed. The algorithm treats all selected nodes similarly regardless of their label.

Heterogeneous relationships

Heterogeneous relationships fully supported. The algorithm has the ability to distinguish between relationships of different types.

Heterogeneous relationships

Heterogeneous relationships allowed. The algorithm treats all selected relationships similarly regardless of their type.

Weighted relationships

Weighted trait. The algorithm supports a relationship property to be used as weight, specified via the relationshipWeightProperty configuration parameter.

Weighted relationships

Weighted trait. The algorithm treats each relationship as equally important, discarding the value of any relationship weight.

Introduction

The Depth First Search algorithm is a graph traversal that starts at a given node and explores as far as possible along each branch before backtracking, see https://en.wikipedia.org/wiki/Depth-first_search. A related algorithm is the Breadth First Search algorithm, Breadth First Search. This algorithm can be preferred over Breadth First Search for example if one wants to find a target node at a large distance and exploring a random path has decent probability of success. There are multiple termination conditions supported for the traversal, based on either reaching one of several target nodes, reaching a maximum depth, exhausting a given budget of traversed relationship cost, or just traversing the whole graph. The output of the procedure contains information about which nodes were visited and in what order.

Syntax

Depth First Search syntax per mode
Run Depth First Search in stream mode:
CALL gds.dfs.stream(
  graphName: String,
  configuration: Map
)
YIELD
  sourceNode: Integer,
  nodeIds: Integer,
  path: Path
Table 1. Parameters
Name Type Default Optional Description

graphName

String

n/a

no

The name of a graph stored in the catalog.

configuration

Map

{}

yes

Configuration for algorithm-specifics and/or graph filtering.

Table 2. Configuration
Name Type Default Optional Description

nodeLabels

List of String

['*']

yes

Filter the named graph using the given node labels. Nodes with any of the given labels will be included.

relationshipTypes

List of String

['*']

yes

Filter the named graph using the given relationship types. Relationships with any of the given types will be included.

concurrency

Integer

1

yes

The algorithm is single-threaded and changing the concurrency parameter has no effect on the runtime.

jobId

String

Generated internally

yes

An ID that can be provided to more easily track the algorithm’s progress.

logProgress

Boolean

true

yes

If disabled the progress percentage will not be logged.

sourceNode

Integer

n/a

no

The node id of the node where to start the traversal.

targetNodes

List of Integer

empty list

yes

Ids for target nodes. Traversal terminates when any target node is visited.

maxDepth

Integer

-1

yes

The maximum distance from the source node at which nodes are visited.

Table 3. Results
Name Type Description

sourceNode

Integer

The node id of the node where to start the traversal.

nodeIds

List of Integer

The ids of all nodes that were visited during the traversal.

path

Path

A path containing all the nodes that were visited during the traversal.

Run Depth First Search in stream mode:
CALL gds.dfs.mutate(
  graphName: string,
  configuration: map
)
YIELD
  relationshipsWritten: Integer,
  preProcessingMillis: Integer,
  computeMillis: Integer,
  postProcessingMillis: Integer,
  mutateMillis: Integer,
  configuration: Map
Table 4. Parameters
Name Type Default Optional Description

graphName

String

n/a

no

The name of a graph stored in the catalog.

configuration

Map

{}

yes

Configuration for algorithm-specifics and/or graph filtering.

Table 5. Configuration
Name Type Default Optional Description

nodeLabels

List of String

['*']

yes

Filter the named graph using the given node labels. Nodes with any of the given labels will be included.

relationshipTypes

List of String

['*']

yes

Filter the named graph using the given relationship types. Relationships with any of the given types will be included.

concurrency

Integer

1

yes

The algorithm is single-threaded and changing the concurrency parameter has no effect on the runtime.

jobId

String

Generated internally

yes

An ID that can be provided to more easily track the algorithm’s progress.

logProgress

Boolean

true

yes

If disabled the progress percentage will not be logged.

sourceNode

Integer

n/a

no

The node id of the node where to start the traversal.

targetNodes

List of Integer

empty list

yes

Ids for target nodes. Traversal terminates when any target node is visited.

maxDepth

Integer

-1

yes

The maximum distance from the source node at which nodes are visited.

mutateRelationshipType

String

n/a

no

The relationship type used for the new relationships written to the projected graph.

Table 6. Results
Name Type Description

preProcessingMillis

Integer

Milliseconds for preprocessing the graph.

computeMillis

Integer

Milliseconds for running the algorithm.

postProcessingMillis

Integer

Unused.

mutateMillis

Integer

Milliseconds for adding relationships to the projected graph.

relationshipsWritten

Integer

The number of relationships that were added.

configuration

Map

The configuration used for running the algorithm.

Examples

All the examples below should be run in an empty database.

The examples use Cypher projections as the norm. Native projections will be deprecated in a future release.

In this section we will show examples of running the Depth First Search algorithm on a concrete graph. The intention is to illustrate what the results look like and to provide a guide in how to make use of the algorithm in a real setting. We will do this on a small graph of a handful nodes connected in a particular pattern. The example graph looks like this:

Visualization of the example graph

Consider the graph projected by the following Cypher statement:

CREATE
       (nA:Node {name: 'A'}),
       (nB:Node {name: 'B'}),
       (nC:Node {name: 'C'}),
       (nD:Node {name: 'D'}),
       (nE:Node {name: 'E'}),

       (nA)-[:REL]->(nB),
       (nA)-[:REL]->(nC),
       (nB)-[:REL]->(nE),
       (nC)-[:REL]->(nD)
The following statement will project the graph and store it in the graph catalog.
MATCH (source:Node)-[r:REL]->(target:Node)
RETURN gds.graph.project(
  'myGraph',
  source,
  target
)

In the following examples we will demonstrate using the Depth First Search algorithm on this graph.

Memory Estimation

First off, we will estimate the cost of running the algorithm using the estimate procedure. This can be done with any execution mode. We will use the stream mode in this example. Estimating the algorithm is useful to understand the memory impact that running the algorithm on your graph will have. When you later actually run the algorithm in one of the execution modes the system will perform an estimation. If the estimation shows that there is a very high probability of the execution going over its memory limitations, the execution is prohibited. To read more about this, see Automatic estimation and execution blocking.

For more details on estimate in general, see Memory Estimation.

The following will estimate the memory requirements for running the algorithm in stream mode:
MATCH (source:Node {name: 'A'})
CALL gds.dfs.stream.estimate('myGraph', {
  sourceNode: source
})
YIELD nodeCount, relationshipCount, bytesMin, bytesMax, requiredMemory
RETURN nodeCount, relationshipCount, bytesMin, bytesMax, requiredMemory
Table 7. Results
nodeCount relationshipCount bytesMin bytesMax requiredMemory

5

4

352

352

"352 Bytes"

Stream

In the stream execution mode, the algorithm returns the path in traversal order for each relationship. This allows us to inspect the results directly or post-process them in Cypher without any side effects.

For more details on the stream mode in general, see Stream.

Running the Depth First Search algorithm:
MATCH (source:Node{name:'A'})
CALL gds.dfs.stream('myGraph', {
  sourceNode: source
})
YIELD path
RETURN path

If we do not specify any of the options for early termination, the algorithm will traverse the entire graph: In the image below we can see the traversal order of the nodes, marked by relationship type NEXT:

Visualization of Depth First Search stream without early termination conditions
Running the Depth First Search algorithm with target nodes:
MATCH (source:Node{name:'A'}), (d:Node{name:'D'}), (e:Node{name:'E'})
WITH source, [d, e] AS targetNodes
CALL gds.dfs.stream('myGraph', {
  sourceNode: source,
  targetNodes: targetNodes
})
YIELD path
RETURN path

If specifying nodes D and E as target nodes, not all nodes at distance 1 will be visited due to the depth first traversal order, in which node D is reached before B.

Visualization of Depth First Search stream with target nodes
Running the Depth First Search algorithm with maxDepth:
MATCH (source:Node{name:'A'})
CALL gds.dfs.stream('myGraph', {
  sourceNode: source,
  maxDepth: 1
})
YIELD path
RETURN path

In the above case, nodes D and E were not visited since they are at distance 2 from node A.

Visualization of Depth First Search stream with max depth

Mutate

The mutate execution mode updates the named graph with new relationships. The path returned from the Depth First Search algorithm is a line graph, where the nodes appear in the order they were visited by the algorithm. The relationship type has to be configured using the mutateRelationshipType option.

The mutate mode is especially useful when multiple algorithms are used in conjunction.

For more details on the mutate mode in general, see Mutate.

Depth First Search mutate supports the same early termination conditions as the stream mode.

The following will run the algorithm in mutate mode:
MATCH (source:Node{name:'A'})
CALL gds.dfs.mutate('myGraph', {
  sourceNode: source,
  mutateRelationshipType: 'DFS'
})
YIELD relationshipsWritten
RETURN relationshipsWritten
Table 8. Results
relationshipsWritten

4

After executing the above query, the in-memory graph will be updated with new relationships of type DFS.

The relationships produced are always directed, even if the input graph is undirected.