12.5. With

12.5.1. Filter on aggregate function results
12.5.2. Sort results before using collect on them
12.5.3. Limit branching of your path search

The ability to chain queries together allows for powerful constructs. In Cypher, the WITH clause is used to pipe the result from one query to the next.

WITH is also used to separate reading from updating of the graph. Every sub-query of a query must be either read-only or write-only.

Figure 12.5. Graph


12.5.1. Filter on aggregate function results

Aggregated results have to pass through a WITH clause to be able to filter on.

Query. 

MATCH david--otherPerson-->()
WHERE david.name='David'
WITH otherPerson, count(*) AS foaf
WHERE foaf > 1
RETURN otherPerson

The person connected to David with the at least more than one outgoing relationship will be returned by the query.

Result

otherPerson
1 row

Node[3]{name:"Anders"}


12.5.2. Sort results before using collect on them

You can sort your results before passing them to collect, thus sorting the resulting collection.

Query. 

MATCH n
WITH n
ORDER BY n.name DESC LIMIT 3
RETURN collect(n.name)

A list of the names of people in reverse order, limited to 3, in a collection.

Result

collect(n.name)
1 row

["Emil","David","Ceasar"]


12.5.3. Limit branching of your path search

You can match paths, limit to a certain number, and then match again using those paths as a base As well as any number of similar limited searches.

Query. 

MATCH n--m
WHERE n.name = 'Anders'
WITH m
ORDER BY m.name DESC LIMIT 1
MATCH m--o
RETURN o.name

Starting at Anders, find all matching nodes, order by name descending and get the top result, then find all the nodes connected to that top result, and return their names.

Result

o.name
2 rows

"Anders"

"Bossman"