2.11. List Clauses / Expressions

TQL supports both the UNWIND clause and list comprehension.

2.11.1. UNWIND Clause

The UNWIND clause expands a list of elements into a sequence of one column rows with one row for each element in the list. The following will return three rows, each with a single string value:

UNWIND ["a", "b", "c"] AS x

This example returns 1000 rows with a boolean true for values divisible by 3, false otherwise.

UNWIND range(0, 1000) AS x
RETURN x % 3 = 0

The UNWIND clause can also be used together with a MATCH clause to expand lists stored as properties of a frame:

UNWIND a.list AS element
RETURN element + 10

In this case, the number of rows produced, is the product of the number of matches times the number of entries in each list for each matched instance.

It is also possible to use the elements of an unwound list to drive a MATCH clause:

WITH a.property AS mylist
UNWIND mylist AS element
WHERE b.value >= element
RETURN count(*)

The UNWIND clause can be applied to lists derived from captured path variables:

MATCH p = ()-[:Edge0 | :Edge1 *1..10]->()
WITH relationships(p) AS edges
UNWIND edges AS elem
MATCH ()-[e:Edge0]->()
WHERE e = elem AND e.value > 1
RETURN count(*)

In this case, we apply the relationships() function to the path variable to extract its edge constituents. Each edge is then tested against the constrained MATCH clause.

Vertices from a captured path variable can be expanded as follows:

MATCH p = ()-[:Edge0 | :Edge1 *1..10]->()
WITH nodes(p) AS n
UNWIND n AS elem
WHERE b = elem AND b.value > 1
RETURN count(*)

We apply the nodes() function to the captured path variable to extract the vertex components of the path and pass those on to the subsequent UNWIND and MATCH clauses.

It is possible to extract properties from the frames involved in an unwound path variable as described in section Property Extraction from Multiple Candidate Frames.

2.11.2. List Comprehension

List comprehension creates a list based on an existing list using constraints, expressions or operators. The following returns a list of 1000 elements multiplied by 2:

RETURN [x IN range(0, 1000) | x * 2]

List comprehension can also use the WHERE clause to constrain the list:

RETURN [x IN range(0, 1000) WHERE x < 5]

These operations can be combined as well:

RETURN [x IN range(0, 1000) WHERE x < 5 | x * 2]

Similarly to the UNWIND, list comprehension can be used with a MATCH clause on properties stored as a list:

RETURN [x IN a.list WHERE x < 50]

This would return a new list for each match where each list contains only values that are less than 50.

It can also be used to create a new list by comparing lists:

WITH ['A', 'B', 'C', 'D'] AS old_list,
     ['A', 'B', 'C', 'D', 'E', 'F'] AS new_list
RETURN [x IN new_list WHERE NOT x IN old_list] AS changes_found

This would return [‘E’, ‘F’].