1
votes

I have a problem to connect the list of movies in the database in form of a sorted linked list (in a single cypher query).

Number of movie nodes: 25L

MATCH (movie:Movie)
WITH movie
ORDER BY movie.rating DESC
WITH collect(movie) as p
FOREACH (n IN nodes(p)| CREATE PREV_MOVIE-[:NextMovie]->(n) )
RETURN p

This will need reference to the previous node PREV_MOVIE and the current node n in the FOREACH to create a relationship between the two. How to find the reference to the previous node PREV_MOVIE here, or is there any other way to do the same?

2

2 Answers

6
votes

you need to apply some FOREACH magic:

MATCH (movie:Movie)
WITH movie
ORDER BY movie.rating DESC
WITH collect(movie) as p
FOREACH(i in RANGE(0, length(p)-2) | 
  FOREACH(p1 in [p[i]] | 
    FOREACH(p2 in [p[i+1]] | 
      CREATE UNIQUE (p1)-[:PREV_MOVIE]->(p2))))
1
votes

In the tutorial part of the Neo4j Documentation there is a Linked-list chapter, maybe that will help you:

http://docs.neo4j.org/chunked/stable/cypherdoc-linked-lists.html