vital
vital

Reputation: 1348

Neo4j Cypher get all nodes in a linked list

With the following graph:

(Boxer)-[:starts]->(Round)-[:continues]->(Round)-[:continues]->(Round)-[:continues]->(Round)

How can I get all the rounds done by a specific boxer?

Right now, I'm only able to get ALL the rounds from ALL the boxers with this: (And i miss the first rounds because the first relationship is STARTS and not CONTINUES.

MATCH (boxer:Boxer {id: 5})
MATCH ()-[:continues]->(round:Round)
 RETURN
  boxer {
   .*,
   rounds: collect(distinct round {
    .*
   })
  } as boxer

Upvotes: 1

Views: 340

Answers (1)

cybersam
cybersam

Reputation: 66967

This may work for you:

MATCH p = (boxer:Boxer)-[:starts]->()-[:continues*0..]->(lastRound)
WHERE boxer.id = 5 AND NOT (lastRound)-[:continues]->()
RETURN boxer {
   .*,
   rounds: NODES(p)[1..]
  } as boxer
  • The variable-length relationship pattern [:continues*0..] uses 0 as the lower bound, in case a bout only has one round.
  • The NOT (lastRound)-[:continues]->() test filters for the paths that end at a leaf node, so that the MATCH only gets the paths of entire bouts.
  • The returned rounds property should contain all the rounds in a bout.
  • This query assumes that the starts and continues relationship types always have Round end nodes, so for efficiency we do not bother to specify those node labels in the MATCH pattern.

Upvotes: 2

Related Questions