Showing results for 
Search instead for 
Did you mean: 

How to find 1st degree, 2nd degree and so on ..

Node Clone

I want to find all the relationships of particular node which is directly connected to the node.

for the 2nd degree I want to find all relationships to that node and also find all the relationships for their relationships node 

How to write query to find in this way

I have written this query and here "1", "2", "3" are variable

any one help me write this query in correct and efficient way

Thank you so much



// For 1st degree relationships  
match (n:Movie)-[*..1]-(b) where id(n)= 682 return n

// For second degree realtionships
match (n:Movie)-[*..2]-(b) where id(n)= 682 return n

//For third degree relationships 
match (n:Movie)-[*..3]-(b) where id(n)= 682 return n


This is what I have written query

match p=(n:Movie)-[*..3]-(b) where id(n)= 682 
unwind nodes(p) as nodes  unwind relationships(p) as re
with collect(DISTINCT{id: ID(nodes)}) as nl,
collect(DISTINCT{id:ID(re), startNode: id(startNode(re)), endNode: id(endNode(re))}) as rl
return {nl: nl, rl: rl}




I think you can get them all in one query, realizing that the 1st relations along a path will have index 0, the 2nd index 1, and the 3rd index 2, within the path's relationships list. 

Try this:

match (n:Movie) where id(n)= 682
match p=(n)-[*..3]-()
with relationships(p) as relationships
with relationships[0] as x, relationships[1] as y, relationships[2] as z
return collect(distinct x) as `1st degree`, collect(distinct y) as `2nd degree`, collect(distinct z) as `3rd degree`

You can format the output by using map projection to return the values of the relationships x, z, and z that you want. 

@glilienfieldthank you so much. I was with in other stuff so I forgot to reply.
my requirement is when user want to see 1st degree I want to return 1st degree relationships. if user want to see 2nd degree relationships I want to return response 1st and 2nd degree and similarly If you want see nth degree I want to return 1st, 2nd, 3rd and so on.... degree relationships

Do you have a specific requirement you need help with, that your query is not providing? 

I think query is working as expected  but I'm not confident about the performance

Graph Maven

Try this:

MATCH (n:Movie) where id(n)= 682
CALL apoc.path.spanningTree(n, {maxLevel: 1}}) YIELD path
maxLevel: 1 means 1st degree, maxLevel: 2 is 2nd degree  and so on

@ameyasoft  Thank you so much for answering to my question. I will check this