WITH

Introduction

Using WITH, you can manipulate the output before it is passed on to the following query parts. The manipulations can be of the shape and/or number of entries in the result set.

WITH can also, like RETURN, alias expressions that are introduced into the results using the aliases as the binding name.

WITH is also used to separate the reading of the graph from updating of the graph. Every part of a query must be either read-only or write-only. When going from a writing part to a reading part, the switch can be done with an optional WITH clause.

Filter on aggregate function results

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

Query

SELECT *
FROM cypher('graph_name', $$
	MATCH (david {name: 'David'})-[]-(otherPerson)-[]->()
	WITH otherPerson, count(*) AS foaf
	WHERE foaf > 1RETURN otherPerson.name
	RETURN otherPerson.name
$$) as (name agtype);

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

Result

name
"Anders"
1 row

Sort results before using collect on them

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

Query

SELECT *
FROM cypher('graph_name', $$
	MATCH (n)WITH n
	ORDER BY n.name DESC LIMIT 3
	RETURN collect(n.name)
$$) as (names agtype);

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

Result

names
["Emil","David","Ceasar"]
1 row