Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all connected nodes in neo4j

Tags:

enter image description here

I want to get list of all connected nodes starting from node 0 as shown in the diagram

like image 572
chetan dev Avatar asked Jul 11 '17 10:07

chetan dev


People also ask

How do I return all nodes and relationships in Neo4j?

When you want to return all nodes, relationships and paths found in a query, you can use the * symbol. This returns the two nodes, the relationship and the path used in the query.

What is the syntax for getting all the nodes under specific label in Neo4j?

If you want to get the labels of a specify node, then use labels(node) ; If you only want to get all node labels in neo4j, then use this function instead: call db. labels; , never ever use this query: MATCH n RETURN DISTINCT LABELS(n) . It will do a full table scan, which is very very slow..


2 Answers

Based on your comment:

I want to get a list of all the connected nodes. For example in the above case 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 nodes connected with a node with id=0 (I'm considering that the numbers inside the nodes are values of an id property) in any depth, both directions and considering any relationship type. Take a look in the section Relationships in depth of the docs.

While this will work fine for small graphs note that this is a very expensive operation. It will go through the entire graph starting from the start point ({id : 0}) considering any relationship type. This is really not a good idea for production environments.

like image 79
Bruno Peres Avatar answered Sep 18 '22 04:09

Bruno Peres


If you wish to match the nodes that have a relationship to another node, you can use this:

MATCH (n) MATCH (n)-[r]-() RETURN n,r 

It will return you all the nodes that have a relationship to another node or nodes, irrespective of the direction of the relationship.

If you wish to add a constraint you can do it this way:

MATCH (n:Label {id:"id"}) MATCH (n)-[r]-() RETURN n,r 
like image 33
Trishant Pahwa Avatar answered Sep 22 '22 04:09

Trishant Pahwa