Search code examples
neo4jcypher

How to set a count(variable) as a property of a node


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


Solution

  • 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