hanzgs
hanzgs

Reputation: 1616

Create new relation based on sum of property values in Cypher neo4j?

I have 4 person nodes belong to same team where team name is a property in node, one person has a relation to a new node community as the score is > 100, as shown

CREATE (Paul:Person {id:'1', name:'Paul', Team:'T1', Joined:datetime('2020-03-04T23:13:49.990000000Z'), Score: 111})
CREATE (Jean:Person {id:'2', name:'Jean', Team:'T1', Joined:datetime('2020-03-03T23:13:49.990000000Z'), Score: 88})
CREATE (Dan:Person {id:'3', name:'Dan', Team:'T1', Joined:datetime('2020-03-02T23:13:49.990000000Z'), Score: 45})
CREATE (Mike:Person {id:'4', name:'Mike', Team:'T1', Joined:datetime('2020-03-01T23:13:49.990000000Z'), Score: 36})

CREATE (Community:Teams {id:'11', name:'Community', street:'2626 Wilkinson Court', address:'San Bernardino, CA 92410'})

CREATE (Paul)-[:SCORE_AB100]->(Community)

RETURN *

enter image description here

Each person node has a property named Score, i want to create a new relation between nodes Jean,Dan who joined in last two days to the node Community, if the sum of Scores of 3 nodes(Paul,Jean,Dan) is greater than 200.

To return these nodes

MATCH (p:Person{Team: 'T1'})
WHERE datetime(p.Joined) > datetime('2020-03-01T23:14:49.990000000Z')
MATCH (p1:Person{Team: 'T1'})-[r:SCORE_AB100]-(t:Teams)
RETURN p,r,t,p1

enter image description here

To return the score and sum

MATCH (p:Person{Team: 'T1'})
WHERE datetime(p.Joined) > datetime('2020-03-01T23:14:49.990000000Z')
MATCH (p1:Person{Team: 'T1'})-[r:SCORE_AB100]-(t:Teams)
RETURN collect(p.Score),sum(p.Score)

enter image description here

As the sum is above 200, i want to create a new relation [:SCORE_AB200] between Jean to Community and Dan to Community, and also paul to community another relation. enter image description here

I tried using sum(p.Score) in WHERE its showing error

Upvotes: 0

Views: 310

Answers (1)

cybersam
cybersam

Reputation: 67044

This query creates each SCORE_AB200 relationship (using MERGE to avoid creating duplicates):

MATCH (p:Person{Team: 'T1'})
WHERE p.Joined > datetime('2020-03-01T23:14:49.990000000Z')
WITH COLLECT(p) AS group, SUM(p.Score) AS total
WHERE total > 200
MATCH (community:Teams {id:'11'})
UNWIND group AS person
MERGE (person)-[:SCORE_AB200]->(community)

Upvotes: 1

Related Questions