cancel
Showing results forΒ
Did you mean:Β

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

Node

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

4 REPLIES 4
Neo4j

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.

Hi Andrew, thank you for your post is very useful. I have been testing your queries because I want to get "n" parents and children but I'm not able to get it, could you help me please? "n" could be 2, 5 etc

Node Clone

Hi @lky17

match p=(b:children)<-[]-(n:node)<-[]-(c:Parent)
RETURN
CASE
WHEN count(b)=count(c)  THEN p
END AS result limit (2*n)
try this and change the '=' in the when condition depending on the requirement
Hi @

Nodes 2022

NODES 2022, Neo4j Online Education Summit

OnΒ November 16 and 17 for 24 hours across all timezones, youβll learn about best practices for beginners and experts alike.

Neo4j Resources