0
votes

How to build a Neo4J query that:

1) Will return all nodes where any pair of nodes are connected by a certain number of different relations? For example, nodes connected by 2, 3 or 5 different relations? So instead of a query returning connected nodes with unknown number of relations:

MATCH (n)-[r]->(m) RETURN n, r, m;

How, in general case, will look query for sub-graph where any pair of nodes are connected by n > K, n = L or n < M relations?

1

1 Answers

1
votes

[UPDATED]

To find nodes connected by a path of exactly 3 relationships:

MATCH (n)-[r*3]->(m) RETURN n, r, m;

To find nodes connected by a path consisting of relationships in the range [2..5]:

MATCH (n)-[r*2..5]->(m) RETURN n, r, m;

To find nodes connected by a path of up to 5 relationships (the lower bound of 1 avoids the case where there there is no relationship, i.e., n is the same as m):

MATCH (n)-[r*1..5]->(m) RETURN n, r, m;

To find nodes connected by a path of at least 2 relationships:

MATCH (n)-[r*2..]->(m) RETURN n, r, m;

To find pairs of nodes that are directly connected by, say, 3 relationships:

MATCH (n)-[r]->(m)
WITH n, m, COLLECT(r) AS rels
WHERE SIZE(rels) = 3
RETURN n, rels, m;