Need explanation of a query

Hi,

I read an article on Northwind database:

In the article, there is a question at the bottom:
Which Employees Report to Each Other Indirectly?

The answer given is:
MATCH path = (e:Employee)<-[:REPORTS_TO*]-(sub)
WITH e, sub, [person in NODES(path) | person.employeeID][1..-1] AS path
RETURN e.employeeID AS manager, sub.employeeID AS employee, CASE WHEN size(path) = 0 THEN "Direct Report" ELSE path END AS via
ORDER BY size(path);

I need help in understanding what this part of the query is doing:
[person in NODES(path) | person.employeeID][1..-1]

Thanks much,
Vivek

So the first part of the bolded section ([person in NODES(path) | person.employeeID]) is list comprehension, used for extraction and filtering of list elements (though there's no filtering in play here, as there is no WHERE clause present).

In this case, we have a path from the matched pattern, and for all the nodes that make up that path (this is a list of nodes), we're extracting out the employeeID and using that to populate a list.

The last part of the bolded section ([1..-1]) is taking a slice of that list of employee ids. Since lists are using 0-based indexing, we're skipping the first element of the list (which we know is e), and the -1 at the upper bound means we're subtracting from the end, so we're dropping the last element of the list (which we know is sub).

The result of that is we're getting a list of the employeeIDs of all the employees in the reporting chain between (not including) e and sub.

2 Likes

Hi Andrew,

Thanks for the quick response and very detailed explanation. This example (query) is certainly a good way to understand list comprehension.

Regards,
Vivek