Overview
The FILTER
statement allows you to filter out records in the current working table that do not satisfy the specified conditions. It typically references columns in the working table.
<filter statement> ::= "FILTER" [ "WHERE" ] <search condition>
The FILTER
and FILTER WHERE
behave the same way. The use of WHERE
in this context is often a matter of style or readability. For example:
MATCH (n:User)
FILTER n.age > 25
RETURN n
is functionally identical to:
MATCH (n:User)
FILTER WHERE n.age > 25
RETURN n
In both cases, the FILTER
statement will return only those nodes where the user's age is greater than 25.
FILTER vs. MATCH WHERE
The FILTER
statement and the WHERE
clause used in the MATCH
statement are both used to apply conditions in queries, but they differ in when and how they are evaluated.
The WHERE
clause can only be used as part of the MATCH
statement and is evaluated as part of the graph pattern process.
MATCH (n:User)
WHERE n.age > 25
RETURN n
The FILTER
statement is evaluated after the previous statements has been executed. It takes the results from the preceding statement and applies an additional condition to filter these results.
MATCH (n:User)
FILTER n.age > 25
RETURN n
Example Graph
The following examples run against this graph:
To create this graph, run the following query against an empty graph:
INSERT (rowlock:User {_id: 'U01', name: 'rowlock'}),
(brainy:User {_id: 'U02', name: 'Brainy'}),
(purplechalk:User {_id: 'U03', name: 'purplechalk'}),
(mochaeach:User {_id: 'U04', name: 'mochaeach'}),
(lionbower:User {_id: 'U05', name: 'lionbower'}),
(c01:Club {_id: 'C01', since: 2005}),
(c02:Club {_id: 'C02', since: 2005}),
(rowlock)-[:Follows {createdOn: '2024-1-5'}]->(brainy),
(mochaeach)-[:Follows {createdOn: '2024-2-10'}]->(brainy),
(brainy)-[:Follows {createdOn: '2024-2-1'}]->(purplechalk),
(lionbower)-[:Follows {createdOn: '2024-5-3'}]->(purplechalk),
(brainy)-[:Joins {memberNo: 1}]->(c01),
(lionbower)-[:Joins {memberNo: 2}]->(c01),
(mochaeach)-[:Joins {memberNo: 9}]->(c02)
Simple Filtering
MATCH (c:Club)
FILTER c._id = "C01"
RETURN c
Result: c
_id | _uuid | schema | values |
---|---|---|---|
C01 | Sys-gen | Club | {since: 2005} |
Filtering with Cartesian Product
This query returns users who follow Brainy
and are also members of C02
:
MATCH (u1:User)-[:Follows]->(:User {name: "Brainy"})
MATCH (u2:User)-({_id: "C02"})
FILTER u1 = u2
RETURN u1
Result: u1
_id | _uuid | schema | values |
---|---|---|---|
U04 | Sys-gen | User | {name: "mochaeach"} |
Note that the Cartesian product is formed between u1
and u2
, which are produced by different MATCH
statements, before the FILTER
statement is applied to perform the filtering.