1

I have a dataset in Memgraph and I'm trying to check if a certain relationship goes both ways.

But I'm either getting a failed query or wrong results.

cybersam
  • 63,203
  • 6
  • 53
  • 76
An Martin
  • 53
  • 2

2 Answers2

0

If I understood correctly what your issue is, this is my idea of the solution:

Let's say we have two nodes created, p1 and p2, both with labels Person and relationship CONNECTED_TO between them. The following query will check if the person p1 is connected to the person p2 and vice versa:

MATCH (p1), (p2)
WHERE exists((p1)-[:CONNECTED_TO]->(p2)) AND
      exists((p2)-[:CONNECTED_TO]->(p1))
RETURN p1, p2

Hope this helps.

MPesi
  • 212
  • 8
0

The query below avoids creating a cartesian product.

MATCH (p1)-[:FOO]->(p2)-[:FOO]->(p1)
WHERE ID(p1) <= ID(p2)
RETURN DISTINCT p1, p2

It also enforces an ordering on the native IDs of the returned p1 and p2 so that the same pair of nodes is not returned twice as p1/p2 and also p2/p1 -- unless the same pair has more than two such relationships, in which case the same pair can still show up multiple times; let's call this Caveat #1. Also, if a node has self-relationships in both directions, it would show up multiple times in the result -- Caveat #2.

To address Caveats #1 and #2, we eliminate duplicate results by returning DISTINCT p1/p2 pairs.

cybersam
  • 63,203
  • 6
  • 53
  • 76