Nicky Feller
Nicky Feller

Reputation: 3889

How to get all nodes connected to one node in neo4j graph in py2neo

I want to pick a node and get all of the nodes that are connected to it by relationship. Even this they are nth degree connections.

What is the py2neo or simply cypher query for this?

Upvotes: 2

Views: 1626

Answers (2)

cybersam
cybersam

Reputation: 66967

[UPDATE]

This Cypher query should work (n is the "picked node"):

MATCH p=(n:MyLabel { myId:123 })-[*]-()
UNWIND [x IN NODES(p) WHERE x <> n] AS node
RETURN DISTINCT node;

It uses list comprehension to filter out the picked node, even if there are paths that cycle back to it.

[ORIGINAL] (Obsolete, as FILTER is no longer supported)]

This Cypher query should work (if the picked node has a myId value of 123):

MATCH p=(n { myId:123 })-[*]-()
UNWIND FILTER(x IN NODES(p) WHERE x <> n) AS node
RETURN DISTINCT node;

The FILTER function filters out the picked node, even if there are paths that cycle back to it.

Upvotes: 3

Tao Chen
Tao Chen

Reputation: 1

Suppose every node has a unique property "node_id". Function find_linked_nodes() finds 1-step linked nodes of node "2". And then the remaining code means a BFS search, which uses a set connected_nodes to remember the traversed nodes, and a queue to record every node to traverse. Every time we traverse a node from queue and remember it in connected_nodes, and record the linked nodes in queue.Finnally, the connected_nodes - node(node_id="2") would be all nodes connected to node "2".

from py2neo import NodeMatcher, RelationShipMatcher

node_matcher = NodeMatcher(graph)
relation_matcher = RelationShipMatcher(graph)


def find_linked_nodes(node):
    linked_nodes = set()
    matched_relations = relation_matcher.match(nodes=(None,node))
    linked_nodes.update([relation.start_node for relation in matched_relations])
    matched_relations = relation_matcher.match(nodes=(node,None))
    linked_nodes.update([relation.end_node for relation in matched_relations])
    return linked_nodes


node = node_matcher.match(node_id="2").first()
connected_nodes = {node}
queue = [node]

while True:
    if len(queue) == 0:
        break
    current_node = queue.pop(0)
    linked_nodes = find_linked_nodes(current_node)
    for linked_node in linked_nodes:
        if linked_node in connected_nodes:
            continue
        queue.append(linked_node)
        connected_nodes.add(linked_node)

Upvotes: 0

Related Questions