4.10. TQL List Clauses/Expressions¶
TQL supports both the UNWIND clause and list comprehension.
4.10.1. TQL 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
RETURN 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:
MATCH (a)
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
MATCH (b)
WHERE b.value >= element
RETURN count(*)
The UNWIND clause can be applied to lists derived from captured path variables:
...
MATCH p = ()-[:myedge0 | :myedge1 *1..10]->()
WITH relationships(p) AS edges
UNWIND edges AS elem
MATCH ()-[e:myedge0]->()
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 = ()-[:myedge0 | :myedge1 *1..10]->()
WITH nodes(p) AS n
UNWIND n AS elem
MATCH (b)
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.
4.10.2. TQL 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:
MATCH (a)
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’].