1
votes

Running the following query on the mini movie graph which comes with Neo4j throws 12 results, which is in fact wrong:

MATCH (actor:Person{name:"Tom Hanks"})-[role:ACTED_IN]->(movie) return count(role) as roles

There are indeed 12 relationships from "Tom Hanks" node to movie nodes, but the property role of the ACTED_IN relationship is actually an array, which can contain more then one value (an actor had more then one role in one movie).

So my question is how can I count all values from the role array as well to get the total number of roles actor have played?

1
What do you mean by total number of roles actor have played? - wassgren
Well, the number of roles Cypher is returning is 12, but that is just the number of movies, and in some movies, this actor played multiple roles. By manual counting total number of roles should be 20 - Srdjan Marjanovic

1 Answers

3
votes

The following should do it for you:

MATCH 
    (actor:Person {name:"Tom Hanks"})-[role:ACTED_IN]->(movie) 
WITH 
    length(role.roles) as roleCount, actor
WITH 
    sum(roleCount) as totalRoleCount, actor
MATCH 
    (actor)-[role:ACTED_IN]->(movie) 
WITH 
    count(role) as roles, totalRoleCount
RETURN 
    roles, totalRoleCount

The output will be:

roles: 12, totalRoleCount: 20