'How to get all parent nodes of a particular node based on ID

I want to fetch all 3rd level nodes(4,5,6 and 7 in below pic) and its relationships along with its parent node details In the below example:

  • If I send ID : 7 then I should get node info of 3 and `1
  • If I send ID : 4 then I should get node info of 2 and `1

enter image description here

How can I get parent node details? Please help

EDIT: I am trying query to get nodes, edges and immediate parent details. Nodes and edges I am getting but with parent I am getting big list of nodes. Not sure why

Match (n)-[r]-() OPTIONAL MATCH (parent:ParentNodeType)<--(child) return n,r,COLLECT(parent) as parent

enter image description here



Solution 1:[1]

This is a typical path query. If you link it to both child and root, you only have to retrieve a single path. Below I assume that you pass myid as a parameter and that you have linked the nodes using :HAS_CHILD relationships

// the path pattern
MATCH path=(root)-[:HAS_CHILD*]->(child)  
// limiting the search
WHERE NOT ()-[:HAS_CHILD]->(root)
      AND child.ID = $myid

//returning the results
RETURN path

or 

// return the IDs, except the last one, because it is the node you started from
UNWIND nodes(path)[..-1] AS node
RETURN node.ID AS parent

Solution 2:[2]

So If you want to get all nodes of parent then use below query

Match (n)-[r]-() OPTIONAL MATCH (parent:ParentNodeType)<-[r1*]-(child)  return n,r,COLLECT(parent) as parent

As you mentioned in comment you are looking for 3rd level parent so you can give level number also whatever you want to get. Please see below query for specific level

Match (n)-[r]-() OPTIONAL MATCH (parent:ParentNodeType)<-[r1*3]-(child)  return n,r,COLLECT(parent) as parent

and as per my understanding you do not need to write this long query. check below query if you are getting your required result

MATCH (p)<-[r*3]-(c)  return p,r,c

Solution 3:[3]

MATCH (n:Child)
WHERE n.id = "ID"
WITH n, [(n)<-[:CHILDREN*]-(Root) | Root] as ancestors,  [(Root)<- [:CHILDREN*]-(n) | Root] as descendants
RETURN n, ancestors, descendants

Where n -> The node that we used for fetching data
      ancestors -> Represents list of Parent nodes
      descendants -> Represents list of Child nodes
      CHILDREN -> Is the relation-ship between Parent and Child (change accordingly)
      Root -> It is the label for accessing Parent (change accordingly)

This query is capable of fetching all the parent and child nodes of the provided node

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Graphileon
Solution 2
Solution 3 M D A