Search code examples
neo4jcypher

Get neighbors of a node that can be reached with n jumps (edges)


I am trying to get all of the nodes and relationships of a node up to n jumps(edges). Meaning that what are the nodes that I can reach with e.g., n edges, and what are the relations in between each node.

Assume that my entire graph looks like the following: s-[r1]-x-[r2]-n, where s, x and n are nodes, and r1 and r2 are relations.

The following query returns entire paths going from "s" to "n":

MATCH (s:Type1 {id: "some_id"})-[r*1..2]-(n)
RETURN s,r,n
// please note that I don't necessarily mean 1..2 connections
// it should be generalizable to 1..n

It returns:

  1. s-r1-x
  2. s-(r1 and r2)-n

However, what I want is:

  1. s-r1-x
  2. x-r2-n

How can I achieve this?


Solution

  • [UPDATED]

    To get info on all nodes and relationships up to a specified depth (say, 5), you can use a query like this:

    MATCH (:Type1 {id: "some_id"})-[rs*..5]->()
    UNWIND rs AS r
    WITH DISTINCT r
    RETURN STARTNODE(r) AS s, r, ENDNODE(r) AS n