Why do I neeed to use new variable after unwinding in Cypher?

78 Views Asked by At

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?

1

There are 1 best solutions below

1
On

You need to create the new variable length to allow the subsequent WITH clause to use the sum(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 the lengths list into individual rows containing a single length value. This is done to facilitate the use of the sum(length) aggregation function, which calculates the total length of the roads in the path by summing up the individual length 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.

MATCH path=(:City {name: "London"})-[:Road * ..2]->(:City)
WITH nodes(path) AS cities, [road IN relationships(path) | road.length] AS lengths
WITH cities, reduce(total = 0, l IN lengths | total + l) 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;