Milkncookiez
Milkncookiez

Reputation: 7397

Nested MATCH statements in cypher

(client)-[:listens]->(album)-[:contains]->(song) are my relationships. I need to find how many different and which songs are listened by clients have listened a song with ID 4 (f.e.).

In SQL I could easily accomplish that with double-nested JOINs and SELECTs, but since I am a novice in Cypher, I'm kinda lost. The scenario is as follows:

  1. Find which clients (their IDs) have listened to song with ID 4
  2. Get all songs that have been listened to, from the clients found in the previous step, and return them (and their count as well).

I tried to start with smth like:

MATCH (c:Client)--(a:Album)--(s:Song)
WITH a, s, {cIDs: c.clientID} AS clientsIDs
// MATCH that gets all songs in albums listened by clients WHERE c.clientID IN clientsIDs -- how to make that?
WITH COUNT(s), COLLECT(s) as songs
WHERE s.songID = "4"
RETURN songs

This was another try:

MATCH (c:Client)--(a:Album)--(s:Song)
WHERE s.songID = "4"
WITH a, s, {cID: c.clientID} AS clientsIDs
MATCH (c {clientID: clientsIDs})-[:LISTENS]->(a)-[:CONTAINS]->(s)
WITH COUNT(s) AS songsCount, COLLECT(s) as songs
RETURN songs, songsCount

which obviously didn't work.

I just can't get around the part where I pass the clientsIDs to another MATCH statement...

Upvotes: 0

Views: 3193

Answers (1)

Dave Bennett
Dave Bennett

Reputation: 11216

I think you might be overcomplicating things. Here is my effort...

// find all of the clients that have listed to the song with id =4
MATCH (c:Client)--(a:Album)--(s:Song)
WHERE s.songID = "4"

// then with those clients find all of the songs they have listened to
WITH c 
MATCH (c)-[:LISTENS]->(a)-[:CONTAINS]->(s)
WITH COLLECT(s) as songs
RETURN songs, size(songs) as songsCount

Upvotes: 1

Related Questions