Neo4j: How can I write this request better?

I am new to Neo4j. I tried this query:

"Mati Gol would like to watch a new movie, so I would like to receive the following list of movies: Write a query that returns all movies liked by any person who is ANOTHER of a person named Mati Gol or FRIENDLY Mati Gol, excluding all movies watched Mati Golom.

My request:

MATCH (a:person {name:"Moti Gol"})-[:WATCHED]->(b)
WITH collect(b) AS Already_Watched
MATCH (a:person {name:"Moti Gol"})-[:FRIEND*1..2]->(b)-[:LIKED]->(c) 
WITH collect(c) AS Friend_Liked
(movie:Friend_Liked) WHERE NOT (movie.name) IN Already_Watched 
RETURN movie.name

      

Is this request OK? Can anyone suggest me to write better about this?

+3


source to share


2 answers


There are some errors in your request ... First, there is no MATCH statement on the first line. You use MATCHing (a:person {name:"Moti Gol"})

twice and update the variable a

.

A simpler and more intuitive way to make the same request:



// get all the movies liked by friends or friends of friends of "Moti Gol"...
MATCH (a:person {name:"Moti Gol"})-[:FRIEND*1..2]->(b:person)-[:LIKED]->(c:movie)
// excluding all movies WATCHED by Mati Gol
WHERE NOT (a)-[:WATCHED]->(c)
// return the movies
RETURN c.name

      

+3


source


Here is the solution from which I think it is what you were with from the start, but not entirely clear.

// find the person and the movies they have already watched
MATCH (a:Person {name:"Mati Gol"})-[:WATCHED]->(movie:Movie)
WITH a, collect(movie) as my_movie_list

// find the person friends and the movies that they like
MATCH (a)-[:FRIEND*1..2]->(:Person)-[:LIKED]->(movie:Movie)
WITH a, my_movie_list, collect(DISTINCT movie) as friend_movie_list

// return the friend like movies that are not already watched
RETURN [m IN friend_movie_list WHERE NOT m in my_movie_list] as movies_to_watch

      



I think this solution gives you a slightly higher cost as it only needs to traverse the movie nodes once. If there is a lot of duplication in the movies LIKED by friends and friends of friends (which I believe is a fairly likely scenario), then we first reduce the list of favorites to a separate list and then filter it against the watched movies in the comparison databases.

+1


source







All Articles