Search code examples
neo4jcypherneo4j-apoc

How to get all relationships between a set of nodes?


In general, the problem is: there is a query with (variable length) matches of node:

MATCH (a:`SOME.LABEL.1` {...})
MATCH (b:`SOME.LABEL.2` {...})
MATCH (c:`SOME.LABEL.3` {...})
...
MATCH (z:`SOME.LABEL.n` {...})

I need to get all relationships between this set of nodes. I started thinking about searching of distinct combinations of (a, b, c, ..., z):

WITH a,b,c, ..., z

MATCH (a) -[ab]-> (b)
MATCH (a) -[ac]-> (c)
...
MATCH (z) -[za]-> (a)

RETURN ab, ac, ..., za;

But I think its too complex.

There is an apoc function. apoc.algo.cover does what I need, but, unfortunately, I need to do it with pure cypher.


Solution

  • This will work:

    WITH ['LAB1', 'LAB2', 'LAB3', 'LAB4'] AS labs
    MATCH (n)-[r]->(m)
    WHERE
      ANY(l1 IN labs WHERE l1 IN LABELS(n)) AND
      ANY(l2 IN labs WHERE l2 IN LABELS(m))
    RETURN r
    

    But if you are using neo4j 5, the newer label expression syntax will likely be more performant:

    MATCH (:LAB1|LAB2|LAB3|LAB4)-[r]->(:LAB1|LAB2|LAB3|LAB4)
    RETURN r