Reputation:
I'm currently trying to get the count of all movies that each actor has acted in (neo4j example movie database), and then set that as a num_movies_acted
attribute for the person node.
So far, I'm able to get a list of all the actors and their respective movie count (including if it's 0 because of the OPTIONAL MATCH)
This is what I have:
MATCH (p:Person)
OPTIONAL MATCH (p)-[:ACTED_IN]->(m:Movie)
RETURN p.name as name, count(m) as num_movies_acted
How would I then set that into the Person Node? I know I should use something like:
SET p.num_movies_acted = count(m)
, but that fails to work.
Invalid use of aggregating function count(...) in this context (line 3, column 26 (offset: 84))
"SET p.num_movies_acted = count(m)"
EDIT: Would this work?
MATCH (p:Person)
OPTIONAL MATCH (p)-[:ACTED_IN]->(m:Movie)
WITH p, count(m) as num_movies_acted
SET p.num_movies_acted = num_movies_acted
RETURN p
since I am "storing" the count(m) into a variable first
Upvotes: 0
Views: 854
Reputation: 79
This is a note for someone expecting a tree with an aggregation property.
I need a tree( Person-[ACTED_IN]->Movie ) with p.num_movies_acted, so finally I got a cypher:
MATCH (p:Person)-[r:ACTED_IN]->(m:Movie)
WHERE m.released > 2000
WITH p, count(r) as num_movies_acted
MATCH (p:Person)-[r:ACTED_IN]->(m:Movie)
WHERE m.released > 2000
SET p.num_movies_acted = num_movies_acted
RETURN p,r,m
I got the same error of aggregation, so tried to somehow avoid it.
I'm not confident in it. So, kindly tell me more efficient one.
Upvotes: 0
Reputation: 415
MATCH (p:Person) OPTIONAL MATCH (p)-[:ACTED_IN]->(m:Movie) RETURN p.name as name, count(m) as num_movies_acted
This query returns a list as num_movies_acted, which fails to work when you try to set it as an property of an individual node.
EDIT: Would this work?
MATCH (p:Person) OPTIONAL MATCH (p)-[:ACTED_IN]->(m:Movie) WITH p, count(m) as num_movies_acted SET p.num_movies_acted = num_movies_acted RETURN p
Yes this would work fine as you are counting the Movie node for each of the Person node and setting the property.
You can also try:
MATCH (p:Person)
OPTIONAL MATCH (p)-[r:ACTED_IN]->(m:Movie)
WITH p, count(r) as num_movies_acted
SET p.num_movies_acted = num_movies_acted
RETURN p
Upvotes: 1