Minimum Weight Spanning Tree

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 Minimum Weight Spanning Tree (MST) starts from a given node, finds all its reachable nodes and returns the set of relationships that connect these nodes together having the minimum possible weight. Prim’s algorithm is one of the simplest and best-known minimum spanning tree algorithms. It operates similarly to Dijkstra’s shortest path algorithm, but instead of minimizing the total length of a path ending at each relationship, it minimizes the length of each relationship individually. This allows the algorithm to work on graphs with negative weights.

For more information on this algorithm, see:

Use cases

Considerations

The MST algorithm provides meaningful results only when run on a graph where relationships have different weights. If the graph has no weights (or all relationships have the same weight), then any spanning tree is also a minimum spanning tree. The algorithm implementation is executed using a single thread. Altering the concurrency configuration has no effect.

Syntax

This section covers the syntax used to execute the Prim 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.

Spanning Tree syntax per mode
Run the algorithm in stream mode on a named graph.
CALL gds.spanningTree.stream(
  graphName: String,
  configuration: Map
)
YIELD
      nodeId: Integer,
      parentId: Integer,
      weight: 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

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

null

n/a

The starting source node ID.

relationshipWeightProperty

String

null

yes

Name of the relationship property to use as weights. If unspecified, the algorithm runs unweighted.

objective

String

'minimum'

yes

If specified, the parameter dictates whether to find the minimum or the maximum weight spanning tree. By default, a minimum weight spanning tree is returned. Permitted values are 'minimum' and 'maximum'.

Table 3. Results
Name Type Description

nodeId

Integer

a node in the discovered spanning tree

parentId

Integer

the parent of nodeId in the spanning tree or nodeId if it is equal to the source node.

weight

Float

The weight of the relationship from parentId to nodeId.

Run the algorithm in stats mode on a named graph.
CALL gds.spanningTree.stats(
  graphName: String,
  configuration: Map
)
YIELD
      effectiveNodeCount: Integer,
      totalWeight: Float,
      preProcessingMillis: Integer,
      computeMillis: 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

null

n/a

The starting source node ID.

relationshipWeightProperty

String

null

yes

Name of the relationship property to use as weights. If unspecified, the algorithm runs unweighted.

objective

String

'minimum'

yes

If specified, the parameter dictates whether to find the minimum or the maximum weight spanning tree. By default, a minimum weight spanning tree is returned. Permitted values are 'minimum' and 'maximum'.

Table 6. Results
Name Type Description

effectiveNodeCount

Integer

The number of visited nodes.

totalWeight

Float

The sum of the weights of the relationships in the spanning tree.

preProcessingMillis

Integer

Milliseconds for preprocessing the data.

computeMillis

Integer

Milliseconds for running the algorithm.

configuration

Map

The configuration used for running the algorithm.

Run the Spanning Tree algorithm in write mode on a named graph.
CALL gds.spanningTree.write(
  graphName: String,
  configuration: Map
)
YIELD
      effectiveNodeCount: Integer,
      totalWeight: Float,
      relationshipsWritten: Integer,
      preProcessingMillis: Integer,
      computeMillis: Integer,
      writeMillis: Integer,
      configuration: Map
Table 7. 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 8. 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.

writeConcurrency

Integer

value of 'concurrency'

yes

The number of concurrent threads used for writing the result to Neo4j.

writeRelationshipType

String

n/a

no

The relationship type used to persist the computed relationships in the Neo4j database.

writeProperty

String

n/a

no

The relationship property in the Neo4j database to which the weight is written.

sourceNode

Integer

null

n/a

The starting source node ID.

relationshipWeightProperty

String

null

yes

Name of the relationship property to use as weights. If unspecified, the algorithm runs unweighted.

objective

String

'minimum'

yes

If specified, the parameter dictates whether to find the minimum or the maximum weight spanning tree. By default, a minimum weight spanning tree is returned. Permitted values are 'minimum' and 'maximum'.

Table 9. Results
Name Type Description

effectiveNodeCount

Integer

The number of visited nodes.

totalWeight

Float

The sum of the weights of the relationships in the spanning tree.

relationshipsWritten

Integer

The number of relationships written to the graph.

preProcessingMillis

Integer

Milliseconds for preprocessing the data.

computeMillis

Integer

Milliseconds for running the algorithm.

writeMillis

Integer

Milliseconds for writing result data back.

configuration

Map

The configuration used for running the algorithm.

Run the Spanning Tree algorithm in write mode on a named graph.
CALL gds.spanningTree.mutate(
  graphName: String,
  configuration: Map
)
YIELD
      effectiveNodeCount: Integer,
      totalWeight: Float,
      relationshipsWritten: Integer,
      preProcessingMillis: Integer,
      computeMillis: Integer,
      mutateMillis: Integer,
      configuration: Map
Table 10. 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 11. Configuration
Name Type Default Optional Description

mutateRelationshipType

String

n/a

no

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

mutateProperty

String

n/a

no

The relationship property in the GDS graph to which the weight is written.

nodeLabels

List of String

['*']

yes

Filter the named graph using the given node labels.

relationshipTypes

List of String

['*']

yes

Filter the named graph using the given relationship types.

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.

sourceNode

Integer

null

n/a

The starting source node ID.

relationshipWeightProperty

String

null

yes

Name of the relationship property to use as weights. If unspecified, the algorithm runs unweighted.

objective

String

'minimum'

yes

If specified, the parameter dictates whether to find the minimum or the maximum weight spanning tree. By default, a minimum weight spanning tree is returned. Permitted values are 'minimum' and 'maximum'.

Table 12. Results
Name Type Description

effectiveNodeCount

Integer

The number of visited nodes.

totalWeight

Float

The sum of the weights of the relationships in the spanning tree.

relationshipsWritten

Integer

The number of relationships added to the in-memory graph.

preProcessingMillis

Integer

Milliseconds for preprocessing the data.

computeMillis

Integer

Milliseconds for running the algorithm.

mutateMillis

Integer

Milliseconds for writing result data back.

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 Prim 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 road network graph of a handful nodes connected in a particular pattern. The example graph looks like this:

Visualization of the example graph
The following will create the sample graph depicted in the figure:
CREATE (a:Place {id: 'A'}),
       (b:Place {id: 'B'}),
       (c:Place {id: 'C'}),
       (d:Place {id: 'D'}),
       (e:Place {id: 'E'}),
       (f:Place {id: 'F'}),
       (g:Place {id: 'G'}),
       (d)-[:LINK {cost:4}]->(b),
       (d)-[:LINK {cost:6}]->(e),
       (b)-[:LINK {cost:1}]->(a),
       (b)-[:LINK {cost:3}]->(c),
       (a)-[:LINK {cost:2}]->(c),
       (c)-[:LINK {cost:5}]->(e),
       (f)-[:LINK {cost:1}]->(g);
The following will project and store a named graph:
MATCH (source:Place)-[r:LINK]->(target:Place)
RETURN gds.graph.project(
  'graph',
  source,
  target,
  { relationshipProperties: r { .cost } },
  { undirectedRelationshipTypes: ['*'] }
)

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 stats 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 stats mode:
MATCH (n:Place {id: 'D'})
CALL gds.spanningTree.stats.estimate('graph', {sourceNode: id(n),relationshipWeightProperty:'cost'})
YIELD nodeCount, relationshipCount, bytesMin, bytesMax, requiredMemory
RETURN nodeCount, relationshipCount, bytesMin, bytesMax, requiredMemory
Table 13. Results
nodeCount relationshipCount bytesMin bytesMax requiredMemory

7

14

520

520

"520 Bytes"

Stream

In the stream execution mode, the algorithm returns the weight 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.

The following will run the Minimum Weight Spanning Tree algorithm in stream mode and return results for each valid node.
MATCH (n:Place{id: 'D'})
CALL gds.spanningTree.stream('graph', {
  sourceNode: n,
  relationshipWeightProperty: 'cost'
})
YIELD nodeId,parentId, weight
RETURN gds.util.asNode(nodeId).id AS node, gds.util.asNode(parentId).id AS parent,weight
ORDER BY node
Table 14. Results
node parent weight

"A"

"B"

1.0

"B"

"D"

4.0

"C"

"A"

2.0

"D"

"D"

0.0

"E"

"C"

5.0

Stats

In the stats execution mode, the algorithm returns a single row containing a summary of the algorithm result. This execution mode does not have any side effects. It can be useful for evaluating algorithm performance by inspecting the computeMillis return item. In the examples below we will omit returning the timings. The full signature of the procedure can be found in the syntax section.

For more details on the stats mode in general, see Stats.

The following will run the Minimum Weight Spanning Tree algorithm and return its statistics.
MATCH (n:Place{id: 'D'})
CALL gds.spanningTree.stats('graph', {
  sourceNode: n,
  relationshipWeightProperty: 'cost'
})
YIELD effectiveNodeCount, totalWeight
RETURN effectiveNodeCount, totalWeight
Table 15. Results
effectiveNodeCount totalWeight

5

12.0

Write

The write execution mode extends the stats mode with an important side effect: writing the weight for each relationship as a property to the Neo4j database. The name of the new property is specified using the mandatory configuration parameter writeProperty. The result is a single summary row, similar to stats, but with some additional metrics. The write mode enables directly persisting the results to the database.

For more details on the write mode in general, see Write.

The following will run the Minimum Weight Spanning Tree algorithm and write the result back to the graph.
MATCH (n:Place {id: 'D'})
CALL gds.spanningTree.write('graph', {
  sourceNode: n,
  relationshipWeightProperty: 'cost',
  writeProperty: 'writeCost',
  writeRelationshipType: 'MINST'
})
YIELD preProcessingMillis, computeMillis, writeMillis, effectiveNodeCount
RETURN preProcessingMillis, computeMillis, writeMillis, effectiveNodeCount;
To find the relationships included in the minimum spanning tree, we can run the following query:
MATCH path = (n:Place {id: 'D'})-[:MINST*]-()
WITH relationships(path) AS rels
UNWIND rels AS rel
WITH DISTINCT rel AS rel
RETURN startNode(rel).id AS Source, endNode(rel).id AS Destination, rel.writeCost AS Cost
Table 16. Results
Source Destination Cost

"D"

"B"

4.0

"B"

"A"

1.0

"A"

"C"

2.0

"C"

"E"

5.0

The minimum spanning tree excludes the relationship with cost 6 from D to E, and the one with cost 3 from B to C. Nodes F and G are not included because they’re unreachable from D.

The relationships written back to the graph are always directed, even if the input graph is undirected.

Mutate

The mutate execution mode extends the stats mode with an important side effect: updating the named graph with a new relationship property containing the weight for that relationship. The name of the new property is specified using the mandatory configuration parameter mutateProperty. The result is a single summary row, similar to stats, but with some additional metrics. The mutate mode is especially useful when multiple algorithms are used in conjunction.

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

The following will run the Minimum Weight Spanning Tree algorithm and mutate the in-memory graph.
MATCH (n:Place {id: 'D'})
CALL gds.spanningTree.mutate('graph', {
  sourceNode: n,
  relationshipWeightProperty: 'cost',
  mutateProperty: 'writeCost',
  mutateRelationshipType: 'MINST'
})
YIELD relationshipsWritten
RETURN relationshipsWritten
Table 17. Results
relationshipsWritten

4

The relationships added back to the graph are always directed, even if the input graph is undirected.

Maximum spanning Tree

The maximum weighted tree spanning algorithm is similar to the minimum one, except that it returns a spanning tree of all nodes in the component where the total weight of the relationships is maximized.

The following will run the Maximum Weight Spanning tree algorithm and return its statistics.
MATCH (n:Place{id: 'D'})
CALL gds.spanningTree.stats('graph', {
  sourceNode: n,
  relationshipWeightProperty: 'cost',
  objective: 'maximum'
})
YIELD totalWeight
RETURN totalWeight
Table 18. Results
totalWeight

17.0

As can be seen, the maximum weighted spanning tree returns a different tree having a larger sum of relationship weights.