neo4j 4.1.3 -> Where condition with count not working as expected

42 views
Skip to first unread message

Shanthi Viswanathan

unread,
Dec 7, 2020, 6:55:37 AM12/7/20
to Neo4j
I am using neo4j 4.1.3. I have 2 labels : Person and Rec. I need to create a relationship between these 2 only when there exists exactly one person with that last name. When I run the below, relationships are created for all persons with that last name. My code is below: 

MATCH (echk:REC {id: 'abcdef'}) OPTIONAL MATCH (p:Person) WHERE p.name CONTAINS 'Shirley' WITH p, echk, count(p) as personcnt where personcnt=1 CALL apoc.merge.relationship(p, 'Test', {}, {}, echk, {}) YIELD rel RETURN p, echk, rel

I have 33 people with "Shirley' and 33 relationships are getting created with that REC. However, there should be no relationship because personcnt <> 1. When I just write 
OPTIONAL MATCH (p:Person) WHERE p.name CONTAINS 'Shirley'  return count(p) -> I get 33 as the value. I am not sure why my where condition is not kicking in. 
 

Michael Hunger

unread,
Dec 7, 2020, 7:02:57 AM12/7/20
to ne...@googlegroups.com
Best to send questions like this to community.neo4j.com

In general if you aggregate, you must not add the thing you want to count / aggregate on as an aggregation key, you can use collect on those.

MATCH (echk:REC {id: 'abcdef'})
OPTIONAL MATCH (p:Person) WHERE p.name CONTAINS 'Shirley' 
WITH collect(p) as people, echk, count(p) as personcnt where personcnt=1 
UNWIND people as p
MERGE (p)-[:TEST]->(echk)

You don't need apoc.merge.relationship for your case you can just use cypher.



--
You received this message because you are subscribed to the Google Groups "Neo4j" group.
To unsubscribe from this group and stop receiving emails from it, send an email to neo4j+un...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/neo4j/9f5043ee-fec0-4f0b-94e4-85d9b6ee8a45n%40googlegroups.com.

Shanthi Viswanathan

unread,
Dec 7, 2020, 9:40:28 AM12/7/20
to ne...@googlegroups.com
Thanks much Michael - your explanation makes sense.

I am using dynamic relationship because this is part of a cypher where my role  (the "Test" I have in my example) is dynamic. 

Reply all
Reply to author
Forward
0 new messages