0

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?

DarqMoth
  • 603
  • 1
  • 13
  • 31

1 Answers1

1

[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;
cybersam
  • 63,203
  • 6
  • 53
  • 76
  • Please help with this question: http://stackoverflow.com/questions/23205781/neo4j-query-to-return-nodes-grouped-by-relation-attributes – DarqMoth Apr 22 '14 at 06:16
  • I have accepted the answer without actually checking how it works. Unfortunaly none of these works on my Neo4J local host. All of them return 0 relations – DarqMoth Apr 22 '14 at 09:35
  • I'm not sure why you are having problems. This is standard Cypher syntax. In fact, you can try these queries out on the default neo4j console: http://console.neo4j.org/. Do you have any relationships in your graph? – cybersam Apr 22 '14 at 09:43
  • I just noticed I may have misunderstood the question 5 years ago, and have updated my answer. – cybersam Feb 01 '19 at 13:45