Topological Sort

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.

This feature is in the alpha tier. For more information on feature tiers, see API Tiers.

Introduction

A topological sorting of nodes in a graph is an ordering of the nodes in the graph where every node appears only after all the nodes pointing to it have appeared. For example, for a graph with 4 nodes and these relations: a→b, a→c, b→d, c→d, there are two acceptable topological sorts: a, b, c, d and a, c, b, d.

The topological order of the nodes is defined only for directed acyclic graphs (DAGs). See below for the expected result for graphs with cycles.

GDS provides an efficient parallel implementation for this algorithm.

Cycles

Running the algorithm on a graph with cycles will cause the omitting of part of the nodes from the sorting. The omitted nodes are:

  1. Nodes that are part of a cycle (including self cycles)

  2. Nodes that are dependent on a cycle. It means nodes that are reachable from another node which is part of a cycle

All the other nodes in the graph will be ordered in a valid topological order.

For example, in the following graph only node 0 will be part of the sorting. Nodes 1 and 2 are part of a cycle, therefore will be excluded from the sorting. Node 3 is reachable from node 1, which is part of a cycle, therefore it will also be excluded.

Visualization of the example graph

Usage

Topological ordering of the nodes is beneficial when you want to guarantee a node will only be processed after its dependencies were processed. This is very useful for dependency related tasks such as scheduling or calculations that derive values from their dependencies.

Cycles detection

The algorithm can also be used to determine if the graph contains a cycle or not. If all the nodes in the graph appear in the sorting, there is no cycle in the graph. If some of the nodes are missing from the sorting, there is a cycle. It does not tell which nodes constitute the cycle, but it does give a clue, as described in the cycles section.

Maximum distance from source

In addition to the sorted node IDs, the algorithm can return the maximal distance of a noe from any source node (i.e., a node without any incoming relationships). If you are interested at the actual longest paths, you should look into the longest path algorithm instead.

In the case that nodes model tasks with dependencies between them, knowing maximal distances can help schedule tasks more efficient: If two nodes have the same maximal distance from a source, then they have no dependencies between them, and can be scheduled in parallel.

To use this feature set computeMaxDistanceFromSource to true. Note that this comes with higher memory usage and slightly longer run time.

Syntax

This section covers the syntax used to execute the Topological Sort algorithm in each of its execution modes. We are describing the named graph variant of the syntax. To learn more about general syntax variants, see Syntax overview.

Example 1. Topological Sort syntax per mode
Run Topological Sort in stream mode on a named graph.
CALL gds.dag.topologicalSort.stream(
  graphName: String,
  configuration: Map
) YIELD
  nodeId: Integer,
  maxDistanceFromSource: Float
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

4

yes

The number of concurrent threads used for running the algorithm.

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.

computeMaxDistanceFromSource

Boolean

false

yes

Whether to enable computation of the maximal distance from source

Table 3. Results
Name Type Description

nodeId

Integer

The ID of the current node in the ordering

maxDistanceFromSource

Integer

The maximal number of nodes between the node and a source node

Examples

In this section we will show examples of running the Topological Sort 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 supply chain graph of a handful nodes connected in a particular pattern. The example graph looks like this:

Visualization of the example graph
The following Cypher statement will create the example graph in the Neo4j database:
CREATE
       (n0:Part {name: 'Cement'}),
       (n1:Part {name: 'Base'}),
       (n2:Part {name: 'Skeleton'}),
       (n3:Part {name: 'Steel'}),
       (n4:Part {name: 'Support'}),
       (n5:Part {name: 'Door'}),
       (n6:Part {name: 'House'}),

       (n0)-[:REQUIRED]->(n1),
       (n1)-[:REQUIRED]->(n2),
       (n3)-[:REQUIRED]->(n4),
       (n4)-[:REQUIRED]->(n2),
       (n2)-[:REQUIRED]->(n5),
       (n5)-[:REQUIRED]->(n6)

This graph describes a simplified supply chain of building a house. Each part of the house cannot be worked on before its requirements are met. For example, we cannot build support before getting the steel, the skeleton is not ready until both support and base are ready.

The following Cypher statement will project the graph to GDS:
MATCH (n)
OPTIONAL MATCH (n)-[r:REQUIRED]->(target)
RETURN gds.graph.project("g", n, target, {})

Stream

The stream procedure streams the nodes in the graph ordered by a valid topological order. The nodes can then be processed one by one, guaranteeing that each node is processed only after its dependencies were processed.

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

The following will run the Topological Sort algorithm in stream mode with max distance from source feature enabled.
CALL gds.dag.topologicalSort.stream("g", {computeMaxDistanceFromSource: true})
YIELD nodeId, maxDistanceFromSource
RETURN gds.util.asNode(nodeId).name AS name, maxDistanceFromSource
ORDER BY maxDistanceFromSource, name

We use the utility function asNode to return the name of node instead of its ID to make results more readable.

Table 4. Results
name maxDistanceFromSource

"Cement"

0.0

"Steel"

0.0

"Base"

1.0

"Support"

1.0

"Skeleton"

2.0

"Door"

3.0

"House"

4.0