apoc.path.elements

Function APOC Core

apoc.path.elements(path) - returns a list of node-relationship-node-…​

Signature

apoc.path.elements(path :: PATH?) :: (LIST? OF ANY?)

Input parameters

Name Type Default

path

PATH?

null

Usage Examples

The examples in this section are based on the following sample graph:

MERGE (manUtd:Club {name: 'Man Utd'})
MERGE (juventus:Club {name: 'Juventus'})
MERGE (flamengo:Club {name: 'Flamengo'})

MERGE (premierLeague:League {name: 'Premier League'})
MERGE (serieA:League {name: 'Serie A'})
MERGE (brasileirao:League {name: 'Brasileirão'})

MERGE (england:Country {name: 'England'})
MERGE (brazil:Country {name: 'Brazil'})

MERGE (uefa:Confederation {name: 'UEFA'})

MERGE (manUtd)-[:IN_LEAGUE]->(premierLeague)
MERGE (premierLeague)-[:IN_COUNTRY]->(england)
MERGE (england)-[:IN_CONFEDERATION]->(uefa)

MERGE (juventus)-[:IN_LEAGUE]->(serieA)

MERGE (flamengo)-[:IN_LEAGUE]->(brasileirao)
MERGE (brasileirao)-[:IN_COUNTRY]->(brazil);

The apoc.path.elements function converts a path into a list of nodes and relationships.

The following returns a list of entities in the (club)-[:IN_LEAGUE]→(league)-[:IN_COUNTRY]→(country) path
MATCH path = (club:Club)-[:IN_LEAGUE]->(league)-[:IN_COUNTRY]->(country)
RETURN path, apoc.path.elements(path);
Table 1. Results
path apoc.path.elements(path)

(:Club {name: "Man Utd"})-[:IN_LEAGUE]→(:League {name: "Premier League"})-[:IN_COUNTRY]→(:Country {name: "England"})

[(:Club {name: "Man Utd"}), [:IN_LEAGUE], (:League {name: "Premier League"}), [:IN_COUNTRY], (:Country {name: "England"})]

(:Club {name: "Flamengo"})-[:IN_LEAGUE]→(:League {name: "Brasileirão"})-[:IN_COUNTRY]→(:Country {name: "Brazil"})

[(:Club {name: "Flamengo"}), [:IN_LEAGUE], (:League {name: "Brasileirão"}), [:IN_COUNTRY], (:Country {name: "Brazil"})]

We can use this function to return a stream of triples representing the nodes and relationships contained in paths.

The following returns triples of (subject, predicate, object):

MATCH path = (club:Club)
OPTIONAL MATCH path1 = (club)-[:IN_LEAGUE]->(league)
OPTIONAL MATCH path2 = (league)-[:IN_COUNTRY]->(country)
WITH apoc.path.combine(path1, path2) AS path
WITH apoc.path.elements(path) AS elements
UNWIND range(0, size(elements)-2) AS index
WITH elements, index
WHERE index %2 = 0
RETURN elements[index] AS subject, elements[index+1] AS predicate, elements[index+2] AS object;
Table 2. Results
subject predicate object

(:Club {name: "Man Utd"})

[:IN_LEAGUE]

(:League {name: "Premier League"})

(:League {name: "Premier League"})

[:IN_COUNTRY]

(:Country {name: "England"})

(:Club {name: "Juventus"})

[:IN_LEAGUE]

(:League {name: "Serie A"})

(:Club {name: "Flamengo"})

[:IN_LEAGUE]

(:League {name: "Brasileirão"})

(:League {name: "Brasileirão"})

[:IN_COUNTRY]

(:Country {name: "Brazil"})