Search code examples
neo4jcypher

How can I create nodes and create a one-to-many relationship another newly created node?


    UNWIND $likedMovies AS likedMovie
    MERGE (lm:LikedMovie {
      id: likedMovie.id,
      name: likedMovie.name,
    })

    CREATE p = (:Person $person)-[:LIKES]->(lm)

This doesn't solve my problem as it creates a new Person for every likedMovie Instead I want the single Person to be related to all the likedMovie's

I also tried this:

    UNWIND $likedMovies AS likedMovie
    MERGE (lm:LikedMovie {
      id: likedMovie.id,
      name: likedMovie.name,
    })

    CREATE p = (:Person $person)

    FOREACH (lm in likedMovie | 
       MERGE (p)->[:LIKES]-(lm)
    )

But, it's giving me an error that p is a Path and needs to be a Node


Solution

  • When you assigned p = (:Person), it created a path with nodes in it. But if you assign a variable (p:Person), the variable p is the node itself. Thus, you can use it to create your relationship with p one-to-many.

    CREATE (p:Person $person)
    UNWIND $likedMovies AS likedMovie
    WITH p, likedMovie
    MERGE (p)-[:LIKES]->(likedMovie)