I've been playing around (learing) with Cypher. I've created a query that will return list of the cities that are between 190 and 200 distnace units away from London. This is the code:
MATCH path=(:City {name: "London"})-\[:Road \* ..2\]-\>(:City)
WITH nodes(path) AS cities, extract(road IN relationships(path) | road.length) AS lengths
UNWIND lengths AS length
WITH cities, sum(length) AS total_length
WHERE total_length \> 150 AND total_length \< 200
UNWIND cities AS city
RETURN DISTINCT city.name, total_length
ORDER BY total_length DESC
LIMIT 50;
The code works but I'm having a hard time understaning why is this part needed: UNWIND lengths AS length
? Why must i create new variable length
? Could I somehow do the sum directly from unwind?
You need to create the new variable
length
to allow the subsequentWITH
clause to use thesum(length)
aggregation function to calculate the total length of the roads in the path.The
UNWIND
clause is used to transform a list of values into individual rows. In this case, it's used to transform thelengths
list into individual rows containing a singlelength
value. This is done to facilitate the use of thesum(length)
aggregation function, which calculates the total length of the roads in the path by summing up the individuallength
values.As an alternative, you can achieve the same result by using the
reduce()
function directly on the lengths list to calculate the total length.