Leiden

This section describes the Leiden algorithm in the Neo4j Graph Data Science library.

Supported algorithm traits:

1. Introduction

The Leiden algorithm is an algorithm for detecting communities in large networks. The algorithm separates nodes into disjoint communities so as to maximize a modularity score for each community. Modularity quantifies the quality of an assignment of nodes to communities, that is how densely connected nodes in a community are, compared to how connected they would be in a random network.

The Leiden algorithm is a hierarchical clustering algorithm, that recursively merges communities into single nodes by greedily optimizing the modularity and the process repeats in the condensed graph. It modifies the Louvain algorithm to address some of its shortcomings, namely the case where some of the communities found by Louvain are not well-connected. This is achieved by periodically randomly breaking down communities into smaller well-connected ones.

For more information on this algorithm, see:

Running this algorithm requires sufficient memory availability. Before running this algorithm, we recommend that you read Memory Estimation.

2. Syntax

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

Leiden syntax per mode
Run Leiden in stream mode on a named graph.
CALL gds.alpha.leiden.stream(
  graphName: String,
  configuration: Map
)
YIELD
  nodeId: Integer,
  communityId: Integer,
  intermediateCommunityIds: List of Integer
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.

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.

relationshipWeightProperty

String

null

yes

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

maxLevels

Integer

10

yes

The maximum number of levels in which the graph is clustered and then condensed.

gamma

Float

1.0

yes

Resolution parameter used when computing the modularity. Internally the value is divided by the number of relationships for an unweighted graph, or the sum of weights of all relationships otherwise. [1]

theta

Float

0.01

yes

Controls the randomness while breaking a community into smaller ones.

includeIntermediateCommunities

Boolean

false

yes

Indicates whether to write intermediate communities. If set to false, only the final community is persisted.

1. Higher resolutions lead to more communities, while lower resolutions lead to fewer communities.

Table 3. Results
Name Type Description

nodeId

Integer

Node ID.

communityId

Integer

The community ID of the final level.

intermediateCommunityIds

List of Integer

Community IDs for each level. Null if includeIntermediateCommunities is set to false.

Run Leiden in stats mode on a named graph.
CALL gds.alpha.leiden.stats(
  graphName: String,
  configuration: Map
)
YIELD
  preProcessingMillis: Integer,
  computeMillis: Integer,
  postProcessingMillis: Integer,
  communityCount: Integer,
  ranLevels: Integer,
  modularity: Float,
  modularities: List of Float,
  nodeCount: Integer,
  didConverge: Boolean,
  communityDistribution: Map,
  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.

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.

relationshipWeightProperty

String

null

yes

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

maxLevels

Integer

10

yes

The maximum number of levels in which the graph is clustered and then condensed.

gamma

Float

1.0

yes

Resolution parameter used when computing the modularity. Internally the value is divided by the number of relationships for an unweighted graph, or the sum of weights of all relationships otherwise. [2]

theta

Float

0.01

yes

Controls the randomness while breaking a community into smaller ones.

includeIntermediateCommunities

Boolean

false

yes

Indicates whether to write intermediate communities. If set to false, only the final community is persisted.

2. Higher resolutions lead to more communities, while lower resolutions lead to fewer communities.

Table 6. Results
Name Type Description

preProcessingMillis

Integer

Milliseconds for preprocessing the data.

computeMillis

Integer

Milliseconds for running the algorithm.

postProcessingMillis

Integer

Milliseconds for computing percentiles and community count.

communityCount

Integer

The number of communities found.

ranLevels

Integer

The number of levels the algorithm actually ran.

modularity

Float

The final modularity score.

modularities

List of Float

The modularity scores for each level.

nodeCount

Integer

The number of nodes in the graph.

didConverge

Boolean

Indicates if the algorithm converged.

communityDistribution

Map

Map containing min, max, mean as well as p50, p75, p90, p95, p99 and p999 percentile values of community size for the last level.

configuration

Map

The configuration used for running the algorithm.

Run Leiden in mutate mode on a named graph.
CALL gds.alpha.leiden.mutate(
  graphName: String,
  configuration: Map
)
YIELD
  preProcessingMillis: Integer,
  computeMillis: Integer,
  mutateMillis: Integer,
  postProcessingMillis: Integer,
  communityCount: Integer,
  ranLevels: Integer,
  modularity: Float,
  modularities: List of Float,
  nodeCount: Integer,
  didConverge: Integer,
  nodePropertiesWritten: Integer,
  communityDistribution: Map,
  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

mutateProperty

String

n/a

no

The node property in the GDS graph to which the community ID 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.

relationshipWeightProperty

String

null

yes

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

maxLevels

Integer

10

yes

The maximum number of levels in which the graph is clustered and then condensed.

gamma

Float

1.0

yes

Resolution parameter used when computing the modularity. Internally the value is divided by the number of relationships for an unweighted graph, or the sum of weights of all relationships otherwise. [3]

theta

Float

0.01

yes

Controls the randomness while breaking a community into smaller ones.

includeIntermediateCommunities

Boolean

false

yes

Indicates whether to write intermediate communities. If set to false, only the final community is persisted.

3. Higher resolutions lead to more communities, while lower resolutions lead to fewer communities.

Table 9. Results
Name Type Description

preProcessingMillis

Integer

Milliseconds for preprocessing the data.

computeMillis

Integer

Milliseconds for running the algorithm.

mutateMillis

Integer

Milliseconds for adding properties to the projected graph.

postProcessingMillis

Integer

Milliseconds for computing percentiles and community count.

communityCount

Integer

The number of communities found.

ranLevels

Integer

The number of levels the algorithm actually ran.

modularity

Float

The final modularity score.

modularities

List of Float

The modularity scores for each level.

nodeCount

Integer

Indicates if the algorithm converged.

didConverge

Boolean

Indicates if the algorithm converged.

nodePropertiesWritten

Integer

Number of properties added to the projected graph.

communityDistribution

Map

Map containing min, max, mean as well as p50, p75, p90, p95, p99 and p999 percentile values of community size for the last level.

configuration

Map

The configuration used for running the algorithm.

Run Leiden in write mode on a named graph.
CALL gds.alpha.leiden.write(
  graphName: String,
  configuration: Map
)
YIELD
  preProcessingMillis: Integer,
  computeMillis: Integer,
  writeMillis: Integer,
  postProcessingMillis: Integer,
  communityCount: Integer,
  ranLevels: Integer,
  modularity: Float,
  modularities: List of Float,
  nodeCount: Integer,
  didConverge: Integer,
  nodePropertiesWritten: Integer,
  communityDistribution: Map,
  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

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.

writeConcurrency

Integer

value of 'concurrency'

yes

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

writeProperty

String

n/a

no

The node property in the Neo4j database to which the community ID is written.

relationshipWeightProperty

String

null

yes

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

maxLevels

Integer

10

yes

The maximum number of levels in which the graph is clustered and then condensed.

gamma

Float

1.0

yes

Resolution parameter used when computing the modularity. Internally the value is divided by the number of relationships for an unweighted graph, or the sum of weights of all relationships otherwise. [4]

theta

Float

0.01

yes

Controls the randomness while breaking a community into smaller ones.

includeIntermediateCommunities

Boolean

false

yes

Indicates whether to write intermediate communities. If set to false, only the final community is persisted.

4. Higher resolutions lead to more communities, while lower resolutions lead to fewer communities.

Table 12. Results
Name Type Description

preProcessingMillis

Integer

Milliseconds for preprocessing the data.

computeMillis

Integer

Milliseconds for running the algorithm.

writeMillis

Integer

Milliseconds for adding properties to the projected graph.

postProcessingMillis

Integer

Milliseconds for computing percentiles and community count.

communityCount

Integer

The number of communities found.

ranLevels

Integer

The number of levels the algorithm actually ran.

modularity

Float

The final modularity score.

modularities

List of Float

The modularity scores for each level.

nodeCount

Integer

Indicates if the algorithm converged.

didConverge

Boolean

Indicates if the algorithm converged.

nodePropertiesWritten

Integer

Number of properties added to the Neo4j database.

communityDistribution

Map

Map containing min, max, mean as well as p50, p75, p90, p95, p99 and p999 percentile values of community size for the last level.

configuration

Map

The configuration used for running the algorithm.

3. Examples

In this section we will show examples of running the Leiden community detection 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 social network 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
  (nAlice:User {name: 'Alice', seed: 42}),
  (nBridget:User {name: 'Bridget', seed: 42}),
  (nCharles:User {name: 'Charles', seed: 42}),
  (nDoug:User {name: 'Doug'}),
  (nMark:User {name: 'Mark'}),
  (nMichael:User {name: 'Michael'}),

  (nAlice)-[:LINK {weight: 1}]->(nBridget),
  (nAlice)-[:LINK {weight: 1}]->(nCharles),
  (nCharles)-[:LINK {weight: 1}]->(nBridget),

  (nAlice)-[:LINK {weight: 5}]->(nDoug),

  (nMark)-[:LINK {weight: 1}]->(nDoug),
  (nMark)-[:LINK {weight: 1}]->(nMichael),
  (nMichael)-[:LINK {weight: 1}]->(nMark);

This graph has two clusters of Users, that are closely connected. These clusters are connected by a single edge. The relationship property weight determines the strength of each respective relationship between nodes.

We can now project the graph and store it in the graph catalog. We load the LINK relationships with orientation set to UNDIRECTED as this works best with the Leiden algorithm.

In the examples below we will use named graphs and native projections as the norm. However, Cypher projections can also be used.

The following statement will project the graph and store it in the graph catalog.
CALL gds.graph.project(
    'myGraph',
    'User',
    {
        LINK: {
            orientation: 'UNDIRECTED'
        }
    },
    {
        nodeProperties: 'seed',
        relationshipProperties: 'weight'
    }
)

In the following examples we will demonstrate using the Leiden algorithm on this graph.

3.1. Stream

In the stream execution mode, the algorithm returns the community ID for each node. 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 algorithm and stream results:
CALL gds.alpha.leiden.stream('myGraph', { randomSeed: 19 })
YIELD nodeId, communityId
RETURN gds.util.asNode(nodeId).name AS name, communityId
ORDER BY name ASC
Table 13. Results
name communityId

"Alice"

2

"Bridget"

2

"Charles"

2

"Doug"

5

"Mark"

5

"Michael"

5

We use default values for the procedure configuration parameter. The maxLevels is set to 10, and the gamma, theta parameters are set to 1.0 and 0.01 respectively.

3.2. 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 algorithm and returns the result in form of statistical and measurement values
CALL gds.alpha.leiden.stats('myGraph', { randomSeed: 19 })
YIELD communityCount
Table 14. Results
communityCount

2

3.3. Mutate

The mutate execution mode extends the stats mode with an important side effect: updating the named graph with a new node property containing the community ID for that node. 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 algorithm and store the results in myGraph:
CALL gds.alpha.leiden.mutate('myGraph', { mutateProperty: 'communityId', randomSeed: 19 })
YIELD communityCount
Table 15. Results
communityCount

2

In mutate mode, only a single row is returned by the procedure. The result contains meta information, like the number of identified communities. The result is written to the GDS in-memory graph instead of the Neo4j database.

3.4. Write

The write execution mode extends the stats mode with an important side effect: writing the community ID for each node 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 algorithm and store the results in the Neo4j database:
CALL gds.alpha.leiden.write('myGraph', { writeProperty: 'communityId', randomSeed: 19 })
YIELD communityCount, nodePropertiesWritten
Table 16. Results
communityCount nodePropertiesWritten

2

6

In write mode, only a single row is returned by the procedure. The result contains meta information, like the number of identified communities. The result is written to the Neo4j database instead of the GDS in-memory graph.

3.5. Weighted

The Leiden algorithm can also run on weighted graphs, taking the given relationship weights into concern when calculating the modularity.

The following will run the algorithm on a weighted graph and stream results:
CALL gds.alpha.leiden.stream('myGraph', { relationshipWeightProperty: 'weight', randomSeed: 19 })
YIELD nodeId, communityId
RETURN gds.util.asNode(nodeId).name AS name, communityId
ORDER BY name ASC
Table 17. Results
name communityId

"Alice"

3

"Bridget"

2

"Charles"

2

"Doug"

3

"Mark"

5

"Michael"

5

Using the weighted relationships, we see that Alice and Doug have formed their own community, as their link is much stronger than all the others.