Neo4j Removing duplicate data and adding new node - difference between queries

Viewed 19

I am following the course Graph Data Modeling Fundamentals

On this sections Adding Language nodes they have this query to remove the langue property from nodes and create a new node and relationshiop to Movies

MATCH (m:Movie)
UNWIND m.languages AS language
WITH  language, collect(m) AS movies
MERGE (l:Language {name:language})
WITH l, movies
UNWIND movies AS m
WITH l,m
MERGE (m)-[:IN_LANGUAGE]->(l);
MATCH (m:Movie)
SET m.languages = null

I don't understand why they have collect(m) AS movies and then UNWIND movies AS m. I modified their query to this one and the result is the same:

MATCH (m:Movie)
UNWIND m.languages AS language
WITH  language, m
MERGE (l:Language {name:language})
WITH l, m
MERGE (m)-[:IN_LANGUAGE]->(l);
MATCH (m:Movie)
SET m.languages = null

Is there any difference in execution?

1 Answers

Yes, there is. When you removed to collect the movies per language, you are executing the Merge statement to create the language nodes more than once. Two movies like movieA and movieB can have the same language like Tamil. Without the collect, you will execute MERGE (l:Language {name:'Tamil'}) TWICE but with collect movies, you will execute it only once because language: Tamil and movies: (movie1, movie2) are in one row only.

With collect:
Language  collect(m) as movies 
Tamil     [MovieA, MovieB]

Without collect:
Language  m
Tamil     MovieA
Tamil     MovieB

Although there is no harm since merge will not create another Language node if it exists, but it is more on efficiency, since you are executing less Merge statements.

Related