3.3.6. UNWIND

UNWIND expands a list into a sequence of rows.

3.3.6.1. Introduction

With UNWIND, you can transform any list back into individual rows. These lists can be parameters that were passed in, previously collect -ed result or other list expressions.

One common usage of unwind is to create distinct lists. Another is to create data from parameter lists that are provided to the query.

UNWIND requires you to specify a new name for the inner values.

3.3.6.2. Unwind a list

We want to transform the literal list into rows named x and return them.

Query. 

UNWIND [1, 2, 3] AS x
RETURN x

Each value of the original list is returned as an individual row.

Result. 

+---+
| x |
+---+
| 1 |
| 2 |
| 3 |
+---+
3 rows

3.3.6.3. Create a distinct list

We want to transform a list 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 list is unwound and passed through DISTINCT to create a unique set.

Result. 

+-------+
| set   |
+-------+
| [1,2] |
+-------+
1 row

3.3.6.4. Create nodes from a list 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 list is unwound and passed through MERGE to find or create the nodes and relationships.

Result. 

+---+
| x |
+---+
| 1 |
| 2 |
+---+
2 rows
Nodes created: 3
Relationships created: 2
Properties set: 3
Labels added: 3