Srdjan Marjanovic
Srdjan Marjanovic

Reputation: 372

Count the data inside the Neo4j array property

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?

Upvotes: 1

Views: 3161

Answers (1)

wassgren
wassgren

Reputation: 19201

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

Upvotes: 3

Related Questions