djvs
djvs

Reputation: 552

Getting counts of 2nd hop, OPTIONAL MATCH nodes in Neo4j Cypher

I tried this:

 START u=node(25)
 MATCH u-[p:captains]-(b:Boat)
 OPTIONAL MATCH b-[r:sails]-(s:Sea)
 OPTIONAL MATCH b-[p1:rides]-(u1:Person) WHERE p1.prop = 'foo'
 OPTIONAL MATCH b-[p2:rides]-(u2:Person) WHERE p2.prop = 'bar'
 OPTIONAL MATCH b-[p3:rides]-(u3:Person) WHERE p3.prop = 'baz'
 RETURN b, count(s), count(u1), count(u2), count(u3)

All the counts are incorrect though. I'm expecting a count of every row starting with an OPTIONAL MATCH to accompany each "b". Anyone help? Like, 3 seas, 2 passengers who are foo, 5 who are bar, etc..

edit: I get the feeling this is closer, but still wrong...

 START u=node(25)
 MATCH u-[p:captains]-(b:Boat)
 WITH b
 OPTIONAL MATCH b-[r:sails]-(s:Sea)
 OPTIONAL MATCH b-[p1:rides{prop:'foo'}]-(u1:Person)
 OPTIONAL MATCH b-[p2:rides{prop:'bar'}]-(u2:Person)
 OPTIONAL MATCH b-[p3:rides{prop:'baz'}]-(u3:Person)
 RETURN c, count(s), count(u1), count(u2), count(u3)

Seems to be giving me something like the count for all rels on b...

Upvotes: 0

Views: 181

Answers (1)

djvs
djvs

Reputation: 552

The answer is to replace each

count(

with

count(DISTINCT 

To remove null values!

Upvotes: 2

Related Questions