Simple recursive query CYPHER

This is a very simple question, but after reading through the documents for the first time, I can’t understand how to build this query. Let's say I have a graph that looks like this:

enter image description here

and, in addition, each person has an age associated with them. What query will CYPHER provide me with a list of John's ages and all ages of the entire John tree tree?

What I have tried so far:

MATCH (start)-[:friend]>(others) WHERE start.name="John" RETURN start.age, others.age 

This has a few problems

  • This is only one deep friend, and I would like to go to all of John's friends.

  • It does not return a list, but a series (john.age, other.age) .

+5
source share
1 answer

So you need not only John’s friend, but also friends of friends. So you need to say that neo4j recursively goes deep into the chart.

This request occupies 2 depth levels.

 MATCH (john:Person { name:"John" })-[:friend *1..2]->(friend: Person) RETURN friend.name, friend.age; 

To go n depth depth, do not put anything, that is *1..

Oh and I also found this good example in neo4j

So what does *1..2 here:

* to indicate its recursion.

1 so as not to include john himself, i.e. this is the beginning of node. If you put 0 here, it will also include John node .

.. to indicate that to move from this node to ...

2 indicates the level of recursion. Here you say to stop at level 2. ie do not go beyond steve. If you don’t put anything there, it will continue to move until it finds a node that has a “friend” relationship

The documentation for these types of query matching is here and a similar answer.

+15
source

All Articles