Saturday, April 22, 2017

How to create a linked list in neo4j?

Having a "Post" nodes that have "FILED_IN" relations to "Topic" model. We can retrieve all posts filed under the Topic using;

MATCH (p:Post)-[FILED_IN]->(t:Topic) return p

But what if we need to retrieve next post. It will be convenient to have a relation to the next post. We can add this relation anytime using the following Cypher.

MATCH (p:post)-[FILED_IN]->(t:Topic)
WITH p
ORDER BY p.timestamp
WITH COLLECT(p) AS posts
UNWIND RANGE(0,LENGTH(posts) - 2) as idx 
WITH posts[idx] AS p1, posts[idx+1] AS p2
MERGE (p1)-[:NEXT]->(p2)
 

 
  

No comments:

The Y Combinator (Slight Return)

Tiger got to hunt, Bird got to fly; Lisper got to sit and wonder, (Y (Y Y))? Tiger got to sleep, Bird got to land; Lisper got to tell hims...