WHERE
You can filter the results of a query using the WHERE
clause.
Tom Hanks movies released in 2013:
MATCH (p:Person)-[:ACTED_IN]->(m:Movie)
WHERE p.name = "Tom Hanks"
AND m.year = 2013
RETURN m.title
Comparison operators
Cypher supports operators in the WHERE
clause, including:
-
Comparison operators:
=
,<>
- equal, not equal<
,>
- less than, greater than⇐
,>=
- less than or equal to, greater than or equal to -
Strings -
CONTAINS
,STARTS WITH
,ENDS WITH
-
Binary operators -
AND
,OR
,XOR
,NOT
-
Null values -
IS NULL
,IS NOT NULL
-
List membership -
IN
Testing ranges
Using comparison and binary operators, you can test for ranges.
Tom Hanks movies released between 2005 and 2010:
MATCH (p:Person)-[:ACTED_IN]->(m:Movie)
WHERE p.name = "Tom Hanks"
AND 2005 <= m.year <= 2010
RETURN m.title, m.released
String operators
There are specific operators for strings, allowing you to filter based on the contents of a string.
Movies staring someone with "Robert" in their name:
MATCH (p:Person)-[:ACTED_IN]->(m:Movie)
WHERE p.name CONTAINS "Robert"
RETURN p.name, m.title
String operators
You can also use STARTS WITH
and ENDS WITH
.
Movies staring someone called "Robert":
MATCH (p:Person)-[:ACTED_IN]->(m:Movie)
WHERE p.name STARTS WITH "Robert"
RETURN p.name, m.title
Null values
Properties that are not set are null
in Neo4j.
You can IS NULL
and IS NOT NULL
to filter based on null values.
This query finds people who are over 100 years old and still alive:
MATCH (p:Person)
WHERE p.died IS NULL
AND p.born.year <= 1925
RETURN p.name, p.born, p.died
Lists
You can use the IN
operator to test if a value is in a list.
The Movie
nodes contain list of languages
spoken in the movie.
Movies in French:
MATCH (m:Movie)
WHERE "French" IN m.languages
RETURN m.title
Challenges
Complete the queries to find the following data in the graph:
-
Directors of
Horror
movies released in the year2000
.cypherMATCH (d:Director)-[:DIRECTED]->(m:Movie)-[:IN_GENRE]->(g:Genre) WHERE ?????? AND ?????? RETURN d.name
-
All movies that do not have a
tmdbId
property (i.e. it is null).cypherMATCH (m:Movie) WHERE ??????? RETURN m.title
-
People
born
in the 1950’s (1950 - 1959).cypherMATCH (p:Person) WHERE p.born.year ?????? RETURN p.name, p.born
Click to reveal the answers
-
Directors of
Horror
movies released in theyear
2000
.cypherMATCH (d:Director)-[:DIRECTED]->(m:Movie)-[:IN_GENRE]->(g:Genre) WHERE m.year = 2000 AND g.name = "Horror" RETURN d.name
-
Movies that do not have a
tmdbId
property (i.e. it is null).cypherMATCH (m:Movie) WHERE m.tmdbId IS NULL RETURN m.title
-
People
born
in the 1950’s (1950 - 1959).cypherMATCH (p:Person) WHERE 1950 <= p.born.year <= 1959 RETURN p.name, p.born
Next
Summary
In this lesson, you learned how to filter results using the WHERE
clause.