简体   繁体   中英

Get relationship between nodes

I have this following type of graph which I get using this query:

MATCH (p:Person)-[:REPORTS_TO *]->(c:Person) WHERE p.name="F"
WITH COLLECT (c) + p AS all 
UNWIND all as p MATCH (p)-[:REPORTS_TO]-(c) 
RETURN p,c;

在此处输入图片说明

Use-Case:

1. I want to find what level is a node at with respect to node F ? Example :

    Node `D`, `E` are direct child of `F`, hence they are at level 1

    Node `A,B,C` are childs of `D` (which is child of `F`) hence level 2

    Node `X` is child of `A' (which is at level 2), hence level 3

and so onnnnn....

I tried to solve this by introducing a variable i and increment it with each iteration ( but it didn't worked ).

MATCH (p:Person)-[:REPORTS_TO *]->(c:Person) WHERE p.name="F"
WITH COLLECT (c) + p AS all ,i:int=0
UNWIND all as p MATCH (p)-[:REPORTS_TO]->(c) 
RETURN p,c, i=i+1;

2. Given two nodes find relation between then

eg Find relation between F and X?

Expected answer = 3 (as it is at level 3)

How should I proceed to solve these use-cases?

Note : Graphical response from Neo4j server isn't necessarily needed , Json response will also be fine.

UC1 Use Path and length(p) function

MATCH p=(root:Person)-[:REPORTS_TO *]->(child:Person) 
WHERE root.name="F"
RETURN nodes(p)[-2], nodes(p)[-1],length(p)

This will find all paths from root node, and return pairs of second to last and last nodes + level you want.

nodes(p) - list of nodes on path p

[-2] - second node from the end of the list

UC2: use shortestPath function:

MATCH (p1:Person),(p2:Person)
WHERE p1.name = '..' AND p2.name = '...'
MATCH p=shortestPath((p2)-[:REPORTS_TO*]->(p2))
RETURN length(p)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM