# Triangle Count

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

## 1. Introduction

The Triangle Count algorithm counts the number of triangles for each node in the graph. A triangle is a set of three nodes where each node has a relationship to the other two. In graph theory terminology, this is sometimes referred to as a 3-clique. The Triangle Count algorithm in the GDS library only finds triangles in undirected graphs.

Triangle counting has gained popularity in social network analysis, where it is used to detect communities and measure the cohesiveness of those communities. It can also be used to determine the stability of a graph, and is often used as part of the computation of network indices, such as clustering coefficients. The Triangle Count algorithm is also used to compute the Local Clustering Coefficient.

## 2. Syntax

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

 The named graphs must be projected in the `UNDIRECTED` orientation for the Triangle Count algorithm.
Example 1. Triangle Count syntax per mode
Run Triangle Count in stream mode on a named graph:
``````CALL gds.triangleCount.stream(
graphName: String,
configuration: Map
)
YIELD
nodeId: Integer,
triangleCount: 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. General configuration for algorithm execution on a named graph.
Name Type Default Optional Description

nodeLabels

String[]

`['*']`

yes

Filter the named graph using the given node labels.

relationshipTypes

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.

Table 3. Algorithm specific configuration
Name Type Default Optional Description

maxDegree

Integer

`263 - 1`

Yes

If a node has a degree higher than this it will not be considered by the algorithm. The triangle count for these nodes will be `-1`.

Table 4. Results
Name Type Description

nodeId

Integer

Node ID.

triangleCount

Integer

Number of triangles the node is part of. Is `-1` if the node has been excluded from computation using the `maxDegree` configuration parameter.

Run Triangle Count in stats mode on a named graph:
``````CALL gds.triangleCount.stats(
graphName: String,
configuration: Map
)
YIELD
globalTriangleCount: Integer,
nodeCount: Integer,
createMillis: Integer,
computeMillis: Integer,
postProcessingMillis: Integer,
configuration: Map``````
Table 5. 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 6. General configuration for algorithm execution on a named graph.
Name Type Default Optional Description

nodeLabels

String[]

`['*']`

yes

Filter the named graph using the given node labels.

relationshipTypes

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.

Table 7. Algorithm specific configuration
Name Type Default Optional Description

maxDegree

Integer

`263 - 1`

Yes

If a node has a degree higher than this it will not be considered by the algorithm. The triangle count for these nodes will be `-1`.

Table 8. Results
Name Type Description

globalTriangleCount

Integer

Total number of triangles in the graph.

nodeCount

Integer

Number of nodes in the graph.

createMillis

Integer

Milliseconds for creating the graph.

computeMillis

Integer

Milliseconds for running the algorithm.

postProcessingMillis

Integer

Milliseconds for computing the global metrics.

configuration

Map

The configuration used for running the algorithm.

Run Triangle Count in mutate mode on a named graph:
``````CALL gds.triangleCount.mutate(
graphName: String,
configuration: Map
)
YIELD
globalTriangleCount: Integer,
nodeCount: Integer,
nodePropertiesWritten: Integer,
createMillis: Integer,
computeMillis: Integer,
postProcessingMillis: Integer,
mutateMillis: Integer,
configuration: Map``````
Table 9. 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 10. General configuration for algorithm execution on a named graph.
Name Type Default Optional Description

nodeLabels

String[]

`['*']`

yes

Filter the named graph using the given node labels.

relationshipTypes

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.

mutateProperty

String

`n/a`

no

The node property in the GDS graph to which the triangle count is written.

Table 11. Algorithm specific configuration
Name Type Default Optional Description

maxDegree

Integer

`263 - 1`

Yes

If a node has a degree higher than this it will not be considered by the algorithm. The triangle count for these nodes will be `-1`.

Table 12. Results
Name Type Description

globalTriangleCount

Integer

Total number of triangles in the graph.

nodeCount

Integer

Number of nodes in the graph.

nodePropertiesWritten

Integer

Number of properties added to the in-memory graph.

createMillis

Integer

Milliseconds for creating the graph.

computeMillis

Integer

Milliseconds for running the algorithm.

postProcessingMillis

Integer

Milliseconds for computing the global metrics.

mutateMillis

Integer

Milliseconds for adding properties to the in-memory graph.

configuration

Map

The configuration used for running the algorithm.

Run Triangle Count in write mode on a named graph:
``````CALL gds.triangleCount.write(
graphName: String,
configuration: Map
)
YIELD
globalTriangleCount: Integer,
nodeCount: Integer,
nodePropertiesWritten: Integer,
createMillis: Integer,
computeMillis: Integer,
postProcessingMillis: Integer,
writeMillis: Integer,
configuration: Map``````
Table 13. 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 14. General configuration for algorithm execution on a named graph.
Name Type Default Optional Description

nodeLabels

String[]

`['*']`

yes

Filter the named graph using the given node labels.

relationshipTypes

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.

mutateProperty

String

`n/a`

no

The node property in the GDS graph to which the triangle count is written.

Table 15. Algorithm specific configuration
Name Type Default Optional Description

maxDegree

Integer

`263 - 1`

Yes

If a node has a degree higher than this it will not be considered by the algorithm. The triangle count for these nodes will be `-1`.

Table 16. Results
Name Type Description

globalTriangleCount

Integer

Total number of triangles in the graph.

nodeCount

Integer

Number of nodes in the graph.

nodePropertiesWritten

Integer

Number of properties written to Neo4j.

createMillis

Integer

Milliseconds for creating the graph.

computeMillis

Integer

Milliseconds for running the algorithm.

postProcessingMillis

Integer

Milliseconds for computing the global metrics.

writeMillis

Integer

Milliseconds for writing results back to Neo4j.

configuration

Map

The configuration used for running the algorithm.

### 2.1. Anonymous graphs

It is also possible to execute the algorithm on a graph that is projected in conjunction with the algorithm execution. In this case, the graph does not have a name, and we call it anonymous. When executing over an anonymous graph the configuration map contains a graph projection configuration as well as an algorithm configuration. All execution modes support execution on anonymous graphs, although we only show syntax and mode-specific configuration for the `write` mode for brevity.

Run Triangle Count in write mode on an anonymous graph:
``````CALL gds.triangleCount.write(
configuration: Map
)
YIELD
globalTriangleCount: Integer,
nodeCount: Integer,
nodePropertiesWritten: Integer,
createMillis: Integer,
computeMillis: Integer,
writeMillis: Integer,
configuration: Map``````
Table 17. General configuration for algorithm execution on an anonymous graph.
Name Type Default Optional Description

nodeProjection

String, String[] or Map

`null`

yes

The node projection used for anonymous graph creation via a Native projection.

relationshipProjection

String, String[] or Map

`null`

yes

The relationship projection used for anonymous graph creation a Native projection.

nodeQuery

String

`null`

yes

The Cypher query used to select the nodes for anonymous graph creation via a Cypher projection.

relationshipQuery

String

`null`

yes

The Cypher query used to select the relationships for anonymous graph creation via a Cypher projection.

nodeProperties

String, String[] or Map

`null`

yes

The node properties to project during anonymous graph creation.

relationshipProperties

String, String[] or Map

`null`

yes

The relationship properties to project during anonymous graph creation.

concurrency

Integer

`4`

yes

The number of concurrent threads used for running the algorithm. Also provides the default value for 'readConcurrency' and 'writeConcurrency'.

Integer

`value of 'concurrency'`

yes

The number of concurrent threads used for creating the graph.

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 triangle count is written.

Table 18. Algorithm specific configuration
Name Type Default Optional Description

maxDegree

Integer

`263 - 1`

Yes

If a node has a degree higher than this it will not be considered by the algorithm. The triangle count for these nodes will be `-1`.

The results are the same as for running write mode with a named graph, see the write mode syntax above.

### 2.2. Triangles listing

In addition to the standard execution modes there is an `alpha` procedure `gds.alpha.triangles` that can be used to list all triangles in the graph.

This algorithm is in the alpha tier. For more information on algorithm tiers, see Algorithms.

The following will return a stream of node IDs for each triangle:
``````CALL gds.alpha.triangles(
graphName: String,
configuration: Map
)
YIELD nodeA, nodeB, nodeC``````
Table 19. 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 20. General configuration for algorithm execution on a named graph.
Name Type Default Optional Description

nodeLabels

String[]

`['*']`

yes

Filter the named graph using the given node labels.

relationshipTypes

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.

Table 21. Results
Name Type Description

nodeA

Integer

The ID of the first node in the given triangle.

nodeB

Integer

The ID of the second node in the given triangle.

nodeC

Integer

The ID of the third node in the given triangle.

## 3. Examples

In this section we will show examples of running the Triangle Count 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: The following Cypher statement will create the example graph in the Neo4j database:
``````CREATE
(alice:Person {name: 'Alice'}),
(michael:Person {name: 'Michael'}),
(karin:Person {name: 'Karin'}),
(chris:Person {name: 'Chris'}),
(will:Person {name: 'Will'}),
(mark:Person {name: 'Mark'}),

(michael)-[:KNOWS]->(karin),
(michael)-[:KNOWS]->(chris),
(will)-[:KNOWS]->(michael),
(mark)-[:KNOWS]->(michael),
(mark)-[:KNOWS]->(will),
(alice)-[:KNOWS]->(michael),
(will)-[:KNOWS]->(chris),
(chris)-[:KNOWS]->(karin)``````

With the graph in Neo4j we can now project it into the graph catalog to prepare it for algorithm execution. We do this using a native projection targeting the `Person` nodes and the `KNOWS` relationships. For the relationships we must use the `UNDIRECTED` orientation. This is because the Triangle Count algorithm is defined only for undirected graphs.

 In the examples below we will use named graphs and native projections as the norm. However, anonymous graphs and/or Cypher projections can also be used.
The following statement will create a graph using a native projection and store it in the graph catalog under the name 'myGraph'.
``````CALL gds.graph.create(
'myGraph',
'Person',
{
KNOWS: {
orientation: 'UNDIRECTED'
}
}
)``````
 The Triangle Count algorithm requires the graph to be created using the `UNDIRECTED` orientation for relationships.

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

### 3.1. 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 `write` 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 write mode:
``````CALL gds.triangleCount.write.estimate('myGraph', { writeProperty: 'triangleCount' })
YIELD nodeCount, relationshipCount, bytesMin, bytesMax, requiredMemory``````
Table 22. Results
nodeCount relationshipCount bytesMin bytesMax requiredMemory

6

16

152

152

"152 Bytes"

Note that the relationship count is 16 although we only created 8 relationships in the original Cypher statement. This is because we used the `UNDIRECTED` orientation, which will project each relationship in each direction, effectively doubling the number of relationships.

### 3.2. Stream

In the `stream` execution mode, the algorithm returns the triangle count for each node. This allows us to inspect the results directly or post-process them in Cypher without any side effects. For example, we can order the results to find the nodes with the highest triangle count.

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

The following will run the algorithm in `stream` mode:
``````CALL gds.triangleCount.stream('myGraph')
YIELD nodeId, triangleCount
RETURN gds.util.asNode(nodeId).name AS name, triangleCount
ORDER BY triangleCount DESC``````
Table 23. Results
name triangleCount

"Michael"

3

"Chris"

2

"Will"

2

"Karin"

1

"Mark"

1

"Alice"

0

Here we find that the 'Michael' node has the most triangles. This can be verified in the example graph. Since the 'Alice' node only `KNOWS` one other node, it can not be part of any triangle, and indeed the algorithm reports a count of zero.

### 3.3. Stats

In the `stats` execution mode, the algorithm returns a single row containing a summary of the algorithm result. The summary result contains the global triangle count, which is the total number of triangles in the entire graph. 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 in `stats` mode:
``````CALL gds.triangleCount.stats('myGraph')
YIELD globalTriangleCount, nodeCount``````
Table 24. Results
globalTriangleCount nodeCount

3

6

Here we can see that the graph has six nodes with a total number of three triangles. Comparing this to the stream example we can see that the 'Michael' node has a triangle count equal to the global triangle count. In other words, that node is part of all of the triangles in the graph and thus has a very central position in the graph.

### 3.4. 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 triangle count 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 example, using the triangle count to compute the local clustering coefficient.

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

The following will run the algorithm in `mutate` mode:
``````CALL gds.triangleCount.mutate('myGraph', {
mutateProperty: 'triangles'
})
YIELD globalTriangleCount, nodeCount``````
Table 25. Results
globalTriangleCount nodeCount

3

6

The returned result is the same as in the `stats` example. Additionally, the graph 'myGraph' now has a node property `triangles` which stores the triangle count for each node. To find out how to inspect the new schema of the in-memory graph, see :/management-ops/graph-catalog-ops/index.adoc#catalog-graph-list.

### 3.5. Write

The `write` execution mode extends the `stats` mode with an important side effect: writing the triangle count 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 in `write` mode:
``````CALL gds.triangleCount.write('myGraph', {
writeProperty: 'triangles'
})
YIELD globalTriangleCount, nodeCount``````
Table 26. Results
globalTriangleCount nodeCount

3

6

The returned result is the same as in the `stats` example. Additionally, each of the six nodes now has a new property `triangles` in the Neo4j database, containing the triangle count for that node.

### 3.6. Maximum Degree

The Triangle Count algorithm supports a `maxDegree` configuration parameter that can be used to exclude nodes from processing if their degree is greater than the configured value. This can be useful to speed up the computation when there are nodes with a very high degree (so-called super nodes) in the graph. Super nodes have a great impact on the performance of the Triangle Count algorithm. To learn about the degree distribution of your graph, see :/management-ops/graph-catalog-ops/index.adoc#catalog-graph-list.

The nodes excluded from the computation get assigned a triangle count of `-1`.

The following will run the algorithm in `stream` mode with the `maxDegree` parameter:
``````CALL gds.triangleCount.stream('myGraph', {
maxDegree: 4
})
YIELD nodeId, triangleCount
RETURN gds.util.asNode(nodeId).name AS name, triangleCount
ORDER BY name ASC``````
Table 27. Results
name triangleCount

"Alice"

0

"Chris"

0

"Karin"

0

"Mark"

0

"Michael"

-1

"Will"

0

Running the algorithm on the example graph with `maxDegree: 4` excludes the 'Michael' node from the computation, as it has a degree of 5.

As this node is part of all the triangles in the example graph excluding it results in no triangles.

## 4. Triangles listing

It is also possible to list all the triangles in the graph. To do this we make use of the `alpha` procedure `gds.alpha.triangles`.

This algorithm is in the alpha tier. For more information on algorithm tiers, see Algorithms.

The following will compute a stream of node IDs for each triangle and return the name property of the nodes:
``````CALL gds.alpha.triangles('myGraph')
YIELD nodeA, nodeB, nodeC
RETURN
gds.util.asNode(nodeA).name AS nodeA,
gds.util.asNode(nodeB).name AS nodeB,
gds.util.asNode(nodeC).name AS nodeC``````
Table 28. Results
nodeA nodeB nodeC

"Michael"

"Karin"

"Chris"

"Michael"

"Chris"

"Will"

"Michael"

"Will"

"Mark"

We can see that there are three triangles in the graph: "Will, Michael, and Chris", "Will, Mark, and Michael", and "Michael, Karin, and Chris". The node "Alice" is not part of any triangle and thus does not appear in the triangles listing.