Database Reference
In-Depth Information
Working with the WHERE clause
WHERE
, as the name suggests, is used to filter the given set of results.
Let's consider our movie dataset and take an example where we need to fetch all relation-
ships that have some value of attribute
Role
, so our Cypher query would be:
MATCH (n)-[r]-() where r.Role is NOT NULL return n,r;
Another example would be where we want a count of relationships for a particular node,
which does have a value of attribute
Role
:
MATCH (n)-[r]-() where r.Role is NOT NULL return n,count(r);
We could also consider an example where we want only those nodes that have
count
(r)
is greater than 1:
MATCH (n)-[r]-() WITH n, count(r) AS countRel
WHERE countRel>1 return n,countRel;
See the usage of the
WITH
clause in the preceding statement, which is used to introduce the
aggregate function
count(r)
for counting the relationships for all nodes within our data-
base.
WITH
is like the event horizon—it is a barrier between a plan and the finished execution of
that plan. Apart from the aggregate functions,
WITH
can also be used to chain together two
reading query parts. For example, let's assume that we need to get the count of
Movie
for
all
Artist
that are related to
Movie
by
ACTED_IN
relationship, but we should consider
only for those
Artist
that are linked to movies by the
DIRECTED
relationship:
MATCH (m:Movie)<-[r:ACTED_IN]-(a:Artist)-[d:DIRECTED]->(m)
WITH a
MATCH (a)-[:ACTED_IN]->(m1:Movie)
WITH a,count( DISTINCT m1) as TotalMovies
return a.Name as Artist,TotalMovies;
In the preceding query, we have chained two reading query parts: the first one does the fil-
tering and gets the
Artist
that are related to
Movie
by
DIRECTED
and
ACTED_IN
re-
lationships, and the second one counts the movies of the selected
Artist
that are related