how to count 2 relationships as one in neo4j

170 views Asked by At

I have a question. i am trying to resolve one cypher query. i have two nodes and associated two relationships. like,

relationships between two nodes

sometimes its ok. I used the query,

(A)-[:Friend]-(B) with A count (B) return B as newfriend. If i use

(A)-[:Friend]->(B) with A count (B) return B as newfriend OR

(A)<-[:Friend]-(B) with A count (B) return B as newfriend sometimes it returns nothing. Is there any possibility where i can count this relationship as one because if a friend with B or B friend with A its the same thing. thanks in advance.

2

There are 2 answers

0
MicTech On

I think you should have only one relationship for friendship, because one implies the other one. For Neo4j doesn't matter direction of relationship during traversal.

Then you can use cypher query without direction

MATCH (n)-[r:FRIEND]-(m) RETURN n, m, r
0
Michael Hunger On

Usually you wouldn't create two relationships for this as the connection between the nodes is symmetrical.

having said that, you have two different relationships, so you could only group them by their start- and end-node.

MATCH (n)-[r:FRIEND]-(m) 
RETURN case when id(n) < (m) then [n,m] else [m,n] end as pair, count(*);

this case when id(n) < (m) then [n,m] else [m,n] end as pair creates a pair of [n,m] where the left always has a lower id than the right, so for [n,m] and [m,n] it would be the same.