How to all get parent and child of particular node from thousand of data in NEo4j

I have this data and I want only parent and child of Node2.

I've got to point out first that a separate label per node in your graph doesn't make sense. If they're the same type of thing, then they should have the same label, though they would usually have different property values to differentiate each other.

However, for the sake of adhering to your model, you could use this approach to get the list of ancestors and descendants:

MATCH (n:Node2)
WITH n, [(n)<-[:Child*]-(x) | x] as ancestors,  [(x)<-[:Child*]-(n) | x] as descendants
RETURN n, ancestors, descendants 

If you only need the single parent, and the list of children, then that's even easier:

MATCH (n:Node2)
WITH n, [(n)<-[:Child]-(x) | x][0] as parent,  [(x)<-[:Child]-(n) | x] as children
RETURN n, parent, children 

I'm using pattern comprehensions here (all the stuff happening in the brackets) to expand a pattern and collect the results into lists. This is also why we're using [0] for the parent, this extracts the first element of the list, which should make sense since each node only has at most a single parent.

The pattern comprehensions here are useful not only because they're concise, but also because they work even when such patterns don't exist, such as getting the (empty) list of children from a leaf node, or a null for a parent of the root node.

2 Likes