In the previous lesson we covered CASE, DISTINCT and OPTIONAL MATCH. Today you’ll be focusing on lists and aggregating functions!

Lists are data structures used to hold multiple elements. Here is an example of a list containing 5 elements:

RETURN [1, 2, 3, 4, 5] AS list

Lists can be unpacked to get a stream of disjoint elements, similar to what you get when you use the MATCH clause. The UNWIND clause unpacks a list into a stream of disjoint elements.

WITH [1, 2, 3, 4, 5] AS list
UNWIND list AS number
RETURN number

This query returns numbers 1 through 5 as rows in a table, instead as 1 row of a list of elements. You’ll encounter lists when working with paths. If you wanted to make a road trip, driving along six roads, surely you’d like to share all the cities you’ve visited:

MATCH path = ()-[:Road * 6]->()
WITH nodes(path) AS cities
LIMIT 1
UNWIND cities AS city
RETURN city

The collect function does the inverse, it joins a stream of disjoint elements back into a list. Working with lists is very common when manipulating data. You’ll find yourself working frequently with sum, min, and extract functions coupled together with list comprehension. extract, as it’s name suggests, extracts properties from nodes and edges! If you create a list of adjacent cities along with distances to them and want to extract only the city names you could write the following:

MATCH (city)-[road:Road]->(city2)
WITH city, collect([city2.name, road.length]) AS city_distances
RETURN city.name,
       extract(pair IN city_distances | pair[0]) AS cities

Go satisfy your curiosity at the playground! Stay tuned for the next lesson. Advanced queries mini series is on the way. Three lessons of advanced cypher queries back to back.

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.