How to get all connected nodes in neo4j
Based on your comment:
I want to get a list of all connected nodes. For example, in the above, when I search for connected nodes for 0, it should return nodes - 1,2,3
This query will do what you want:
MATCH ({id : 0})-[*]-(connected)
RETURN connected
The above query will return all the nodes associated with a node with id=0
(I believe the numbers inside the nodes are the values โโof the id property) at any depth, in both directions, and given any type of relationship. Take a look at the section on Depth Relationships in Documents.
While this will work well for small charts, please note that this is a very expensive operation. It will run through the entire graph starting from the starting point ({id : 0})
for any type of relationship. This is not a good idea for production environments.
source to share
If you want to match nodes that are related to another node, you can use this:
MATCH (n) MATCH (n)-[r]-() RETURN n,r
It will return you all the nodes that are related to another node or nodes, regardless of the direction of the relationship.
If you want to add a constraint, you can do it like this:
MATCH (n:Label {id:"id"}) MATCH (n)-[r]-() RETURN n,r
source to share
For larger or more tightly coupled graphs, APOC routines offer more efficient traversals that return all the nodes in a subgraph.
As mentioned, it is best to use labels on your nodes and add either an index or a unique constraint on the label + property to quickly find your starting node.
Using the "Label" label and parameter idParam
, the request to get the subgraph nodes with APOC will be:
MATCH (n:Label {id:$idParam})
CALL apoc.path.subgraphNodes(n, {minLevel:1}) YIELD node
RETURN node
The nodes will be different and the original node will not be returned by the rest.
source to share