pablor21
pablor21

Reputation: 89

Get Actor with Movie and Role played

I'm new in Neo4j and I'm facing a little problem:

I'm using move/actors example database, and I'd like to have the actor with the movies that the actor has acted and the role (for each movie)

Actually I'm doing like this:

MATCH (a:Person)-[r:ACTED_IN]-(m:Movie)
WHERE ALL (role in r.roles WHERE NOT role IS NULL)
WITH DISTINCT(a), collect(r.roles) as roles, collect(m) as movies
RETURN a{.*, roles, movies} as result

I'm getting the movies and the roles separated, I'd like to include the role inside movies node, the structure that I want is:

{
name:"the actor's name"
movies:[
  {
     title:"the movie title",
     roles:[{role:"the role of the actor"}] /// there could be more than one role for the actor
  }
]

}```

Thanks

Upvotes: 0

Views: 176

Answers (2)

Cameron Tinker
Cameron Tinker

Reputation: 9789

You should try using map projections: https://neo4j.com/docs/cypher-manual/current/syntax/maps/

Something like this should work:

 MATCH (a:Person)-[r:ACTED_IN]-(m:Movie)
 WHERE ALL (role in r.roles WHERE NOT role IS NULL)
 WITH DISTINCT(a)
 RETURN { a.name, movies: collect( { m.title, roles: r.roles } ) }

Upvotes: 1

cybersam
cybersam

Reputation: 66999

This is very straightforward (assuming actors have unique names):

MATCH (a:Person)-[r:ACTED_IN]->(m:Movie)
WHERE EXISTS(r.roles)
RETURN {name: a.name, movies: COLLECT({title: m.title, roles: r.roles})} AS result

If multiple actors might have the same name, you can use the aggregating function COLLECT to collect the data for each distinct Person node:

MATCH (a:Person)-[r:ACTED_IN]->(m:Movie)
WHERE EXISTS(r.roles)
WITH a, COLLECT({title: m.title, roles: r.roles}) AS movies
RETURN {name: a.name, movies: movies} AS result

Upvotes: 2

Related Questions