Stephen D
Stephen D

Reputation: 3086

How to find related nodes per relationship depth?

I am trying to come up with a query for the following data model in neo4j.

Readable-[:readBy]-Student
    |
 [:owns]
    |
Readable-[:readBy]-Student
    |
 [:owns] -----------------------------------------
    |                                             |
Readable-[:readBy]-Student           Readable-[:readBy]-Student
    |
 [:owns]
    |  
Readable-[:readBy]-Student

The query:

Return all students by distance their from the first Readable in a map.

MATCH (:Readable{name:'book'})-[:owns*0..3]-(r:Readable)
MATCH (r)-[:readBy]-(s:Student)
RETURN s

That query seems to correctly traverse the tree and find each student at each distance, but I can't seem to record the distance for each student to return at the end.

Upvotes: 0

Views: 48

Answers (1)

Nicole White
Nicole White

Reputation: 7800

I think you're looking for the LENGTH function.

MATCH p = (:Readable{name:'book'})-[:owns*0..3]-(:Readable)-[:readBy]-(s:Student)
RETURN s.name, LENGTH(p);

Edit: To get a map by length (key) and collection of students (value):

MATCH p = (:Readable{name:'book'})-[:owns*0..3]-(:Readable)-[:readBy]-(s:Student)
WITH LENGTH(p) AS len, COLLECT(s) AS students
RETURN {length: len, students: students};

Upvotes: 1

Related Questions