Minimum Weight Spanning Tree
Glossary
 Directed

Directed trait. The algorithm is welldefined 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 welldefined 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 bestknown 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

Minimum spanning trees were used to analyze airline and sea connections of Papua New Guinea, and minimize the travel cost for exploring the country. For example, they were used to help design lowcost tours that visit many destinations across the country. See "An Application of Minimum Spanning Trees to Travel Planning".

Minimum spanning trees have been used to analyze and visualize correlations in a network of currencies, based on the correlation between currency returns. This is described in "Minimum Spanning Tree Application in the Currency Market".

Minimum spanning trees have also proven to be a useful tool for tracing transmission of infections in outbreaks. See Use of the Minimum Spanning Tree Model for Molecular Epidemiological Investigation of a Nosocomial Outbreak of Hepatitis C Virus Infection.
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.
CALL gds.spanningTree.stream(
graphName: String,
configuration: Map
)
YIELD
nodeId: Integer,
parentId: Integer,
weight: Float
Name  Type  Default  Optional  Description 

graphName 
String 

no 
The name of a graph stored in the catalog. 
configuration 
Map 

yes 
Configuration for algorithmspecifics and/or graph filtering. 
Name  Type  Default  Optional  Description 

List of String 

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

List of String 

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

Integer 

yes 
The algorithm is singlethreaded and changing the concurrency parameter has no effect on the runtime. 

String 

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

Boolean 

yes 
If disabled the progress percentage will not be logged. 

sourceNode 
Integer 

n/a 
The starting source node ID. 
String 

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

objective 
String 

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'. 
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. 
CALL gds.spanningTree.stats(
graphName: String,
configuration: Map
)
YIELD
effectiveNodeCount: Integer,
totalWeight: Float,
preProcessingMillis: Integer,
computeMillis: Integer,
configuration: Map
Name  Type  Default  Optional  Description 

graphName 
String 

no 
The name of a graph stored in the catalog. 
configuration 
Map 

yes 
Configuration for algorithmspecifics and/or graph filtering. 
Name  Type  Default  Optional  Description 

List of String 

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

List of String 

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

Integer 

yes 
The algorithm is singlethreaded and changing the concurrency parameter has no effect on the runtime. 

String 

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

Boolean 

yes 
If disabled the progress percentage will not be logged. 

sourceNode 
Integer 

n/a 
The starting source node ID. 
String 

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

objective 
String 

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'. 
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. 
CALL gds.spanningTree.write(
graphName: String,
configuration: Map
)
YIELD
effectiveNodeCount: Integer,
totalWeight: Float,
relationshipsWritten: Integer,
preProcessingMillis: Integer,
computeMillis: Integer,
writeMillis: Integer,
configuration: Map
Name  Type  Default  Optional  Description 

graphName 
String 

no 
The name of a graph stored in the catalog. 
configuration 
Map 

yes 
Configuration for algorithmspecifics and/or graph filtering. 
Name  Type  Default  Optional  Description 

List of String 

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

List of String 

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

Integer 

yes 
The algorithm is singlethreaded and changing the concurrency parameter has no effect on the runtime. 

String 

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

Boolean 

yes 
If disabled the progress percentage will not be logged. 

Integer 

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

writeRelationshipType 
String 

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

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

sourceNode 
Integer 

n/a 
The starting source node ID. 
String 

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

objective 
String 

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'. 
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. 
CALL gds.spanningTree.mutate(
graphName: String,
configuration: Map
)
YIELD
effectiveNodeCount: Integer,
totalWeight: Float,
relationshipsWritten: Integer,
preProcessingMillis: Integer,
computeMillis: Integer,
mutateMillis: Integer,
configuration: Map
Name  Type  Default  Optional  Description 

graphName 
String 

no 
The name of a graph stored in the catalog. 
configuration 
Map 

yes 
Configuration for algorithmspecifics and/or graph filtering. 
Name  Type  Default  Optional  Description 

mutateRelationshipType 
String 

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

no 
The relationship property in the GDS graph to which the weight is written. 
List of String 

yes 
Filter the named graph using the given node labels. 

List of String 

yes 
Filter the named graph using the given relationship types. 

Integer 

yes 
The number of concurrent threads used for running the algorithm. 

String 

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

sourceNode 
Integer 

n/a 
The starting source node ID. 
String 

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

objective 
String 

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'. 
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 inmemory 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 native projections as the norm, although Cypher projections can be used as well. 
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:
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);
CALL gds.graph.project(
'graph',
'Place',
{
LINK: {
properties: 'cost',
orientation: 'UNDIRECTED'
}
}
)
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.
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
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 postprocess them in Cypher without any side effects.
For more details on the stream
mode in general, see Stream.
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
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.
MATCH (n:Place{id: 'D'})
CALL gds.spanningTree.stats('graph', {
sourceNode: n,
relationshipWeightProperty: 'cost'
})
YIELD effectiveNodeCount, totalWeight
RETURN effectiveNodeCount, totalWeight
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.
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;
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
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.
MATCH (n:Place {id: 'D'})
CALL gds.spanningTree.mutate('graph', {
sourceNode: n,
relationshipWeightProperty: 'cost',
mutateProperty: 'writeCost',
mutateRelationshipType: 'MINST'
})
YIELD relationshipsWritten
RETURN relationshipsWritten
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.
MATCH (n:Place{id: 'D'})
CALL gds.spanningTree.stats('graph', {
sourceNode: n,
relationshipWeightProperty: 'cost',
objective: 'maximum'
})
YIELD totalWeight
RETURN totalWeight
totalWeight 

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