Aran Mulholland
Aran Mulholland

Reputation: 23945

Neo4j Cypher get all nodes in a circular linked list

I have a graph that looks like this

(user)->[:Comments]->(comment)->[:Comments]->(comment)->[:Comments]->(comment)->(user)

Basically it is a circular linked list of comments that a user has made. The list circles around and ends up back at the user. How do I use cypher to retrieve all of the comments?

Upvotes: 0

Views: 748

Answers (1)

Luanne
Luanne

Reputation: 19373

Took a stab at this and it looks a bit convoluted to me, but here it is anyway.

Assumed the relation from the last comment to the user is :Comments

i.e instead of ..->(comment)->(user)

I assumed ..->(comment)-[:Comments]->(user)

START n=node(1) 
MATCH n-[:Comments*0..]->(c) 
WHERE c<>n 
WITH collect(c) AS allComments,n 
WITH last(allComments) AS lastcomment,n,allComments 
WHERE lastcomment-[:Comments]->n 
RETURN allComments

I had to put in WHERE c<>n since the last comment->user relation is Comments. If it's something else, all the better, don't need this (it's there to just pick the last comment in the chain). Also it returns a collection.

http://console.neo4j.org/r/17d1fy

Bet @Wes Freeman has a niftier solution

Upvotes: 2

Related Questions