Brenna
Brenna

Reputation: 95

Cypher Neo4j Count number of bidirectional Relationship between two nodes and avoid duplicate results

Here is my query:

MATCH (a:Person)-[:Sent]->(m2:message)-[r:forward]->(m1:message)<-[Sent]-(b:Person)
   WITH a, b, COUNT(r) as count
   RETURN a,b,count

Here is the result sample:

  a             b            count
   name1         name2          2
   name2         name1          3

and I want to get the sum of forwarded messages between the 2 nodes in both direction, therefore I don't want to have duplicated results like on the previous example

For the previous example I want such kind of results:

 a             b            count
name1         name2          5

I tried many queries but couldn't find any solution or syntax to get this results.

Is there any way to get this kind of results? Thank you in advance for your time.

Upvotes: 0

Views: 354

Answers (2)

cybersam
cybersam

Reputation: 66967

Here is how you'd get the total number of forwarded messages between every applicable pair of people:

MATCH (a:Person)-[:Sent]->(:message)-[r:forward]-(:message)<-[:Sent]-(b:Person)
WHERE ID(a) < ID(b)
RETURN a, b, COUNT(r) as count;

The MATCH clause specifies a non-directional pattern for the forward relationship, so that it matches relationships in both directions. The WHERE clause ensures that you only get one row of results for each pair of people. Also, this query uses [:Sent] consistently, fixing a typo in your original query.

Upvotes: 1

Bruno Peres
Bruno Peres

Reputation: 16355

Try it:

MATCH (a:Person)-[:Sent]->(m2:message)-[r:forward]->(m1:message)<-[:Sent]-(b:Person)
WITH COLLECT(a) as rows, count(r) as count
RETURN {a:properties(rows[0]), b:properties(rows[1]), count: count}

Upvotes: 0

Related Questions