UNWIND and List Processing in Neo4j
Introduction
In Neo4j, list processing is a crucial operation, especially when working with collections of nodes and relationships. The UNWIND clause allows you to transform a list into a set of rows, enabling you to work with each item in the list individually.
What is UNWIND?
The UNWIND
clause is used in Cypher to take a list and expand it into rows. Each element from the list becomes a separate row, allowing for easier manipulation and querying of data.
Basic Syntax
UNWIND AS
RETURN
Example
WITH [1, 2, 3] AS numbers
UNWIND numbers AS num
RETURN num
This example takes a list of numbers and unwinds it into rows:
- 1
- 2
- 3
List Processing
In addition to UNWIND, Neo4j provides various functions to process lists, including COLLECT
, FILTER
, and REDUCE
.
Using COLLECT
MATCH (n:Node)
RETURN COLLECT(n.property) AS properties
This example collects properties from nodes into a list.
Using FILTER
WITH [1, 2, 3, 4, 5] AS numbers
RETURN FILTER(num IN numbers WHERE num > 2) AS filtered
This example filters the list to only include numbers greater than 2.
Using REDUCE
WITH [1, 2, 3, 4] AS numbers
RETURN REDUCE(s = 0, num IN numbers | s + num) AS sum
This example calculates the sum of the list elements.
Best Practices
- Use UNWIND when you need to process each item in a list individually.
- Combine UNWIND with other Cypher functions for efficient data manipulation.
- Be cautious with large lists, as unwinding can lead to performance issues.
FAQ
What happens if the list is empty?
If the list provided to UNWIND is empty, no rows will be returned.
Can UNWIND be used with parameters?
Yes, you can pass parameters to UNWIND, as long as they are lists.
How can I combine UNWIND with other clauses?
UNWIND can be combined with MATCH, WITH, and RETURN to create complex queries.