Ch HaXam
Ch HaXam

Reputation: 499

how to count 2 relationships as one in neo4j

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.

Upvotes: 0

Views: 170

Answers (2)

Michael Hunger
Michael Hunger

Reputation: 41706

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.

Upvotes: 1

MicTech
MicTech

Reputation: 45123

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

Upvotes: 3

Related Questions