9.6. Unwind
With UNWIND
, you can transform any collection back into individual rows.
These collections can be parameters that were passed in, previously ++COLLECT+ed result or other collection expressions.
One common usage of unwind is to create distinct collections. Another is to create data from parameter collections that are provided to the query.
UNWIND
requires you to specify a new name for the inner values.
Unwind a collection
We want to transform the literal collection into rows named x
and return them.
Query.
UNWIND[1,2,3] AS x RETURN x
Each value of the original collection is returned as an individual row.
Result
x |
---|
3 rows |
|
|
|
Try this query live. none UNWIND [1,2,3] as x RETURN x
Create a distinct collection
We want to transform a collection of duplicates into a set using DISTINCT
.
Query.
WITH [1,1,2,2] AS coll UNWIND coll AS x WITH DISTINCT x RETURN collect(x) AS SET
Each value of the original collection is unwound and passed through distinct to create a unique set.
Result
set |
---|
1 row |
|
Try this query live. none WITH [1,1,2,2] as coll UNWIND coll as x WITH DISTINCT x RETURN collect(x) as set
Create nodes from a collection parameter
Create a number of nodes and relationships from a parameter-list without using FOREACH
Parameters.
{ "events" : [ { "year" : 2014, "id" : 1 }, { "year" : 2014, "id" : 2 } ] }
Query.
UNWIND { events } AS event MERGE (y:Year { year:event.year }) MERGE (y)<-[:IN]-(e:Event { id:event.id }) RETURN e.id AS x ORDER BY x
Each value of the original collection is unwound and passed through distinct to create a unique set.
Result
x |
---|
2 rows |
Nodes created: 3 |
Relationships created: 2 |
Properties set: 3 |
Labels added: 3 |
|
|