Search code examples
cyphermemgraphdbopencypher

How to check if a certain relationship goes both ways on Memgraph?


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.


Solution

  • 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.