cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Compare (count) Relationships to a Single Node

I am trying to count the differences in relationships pointing to a certain node.. If I write the code below with rel = 1 and ler = 1 then I get a proper result showing the count of both having 1 of each type of a relationship.. but I want to also know when there is 1 of rel and 0 of ler
When I try to run this I get 0 results, but know this is not true..

MATCH ()-[rs:OWNED_BY {type:'ipAddress',source:'attr'}]-(s:SourceValue)-[sr:OWNED_BY {type:'ipAddress',source:'ca_model'}]-()
WITH s, count(rs) as rel, count(sr) as ler
WHERE rel = 1 and ler = 0
RETURN count(s)

MATCH ()-[rs:OWNED_BY {type:'ipAddress',source:'attr'}]-(s:SourceValue)-[sr:OWNED_BY {type:'ipAddress',source:'ca_model'}]-()
WITH s, count(rs) as rel, count(sr) as ler
WHERE rel > 1 and ler = 1
RETURN count(s)
1 ACCEPTED SOLUTION

Use the size() function with the pattern that you're looking for, that avoids cardinality issues and the need for aggregations:

MATCH (s:SourceValue)
WITH s, size(()-[:OWNED_BY {type:'ipAddress',source:'attr'}]-(s)) as rel, size((s)-[:OWNED_BY {type:'ipAddress',source:'ca_model'}]-()) as ler
WHERE rel = 1 and ler = 0
RETURN count(s)

View solution in original post

4 REPLIES 4

anthapu
Graph Fellow

May be you can use union to get both in a single query

MATCH ()-[rs:OWNED_BY {type:'ipAddress',source:'attr'}]-(s:SourceValue)-[sr:OWNED_BY {type:'ipAddress',source:'ca_model'}]-()
WITH s, count(rs) as rel, count(sr) as ler
WHERE rel = 1 and ler = 0
RETURN count(s) as count, "no_ler" as status
UNION 
MATCH ()-[rs:OWNED_BY {type:'ipAddress',source:'attr'}]-(s:SourceValue)-[sr:OWNED_BY {type:'ipAddress',source:'ca_model'}]-()
WITH s, count(rs) as rel, count(sr) as ler
WHERE rel > 1 and ler = 1
RETURN count(s) as count, "with_ler" as status

This way you can get both counts and still have the context for the counts.

In my original post, those are actually two different queries I am trying to get results from, not two I am trying to combine, but neither of them work as they are currently set up.

Use the size() function with the pattern that you're looking for, that avoids cardinality issues and the need for aggregations:

MATCH (s:SourceValue)
WITH s, size(()-[:OWNED_BY {type:'ipAddress',source:'attr'}]-(s)) as rel, size((s)-[:OWNED_BY {type:'ipAddress',source:'ca_model'}]-()) as ler
WHERE rel = 1 and ler = 0
RETURN count(s)

sheer genius, thank you for resolving my headache!