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.titleComparison 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.releasedString 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.titleString 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.titleNull 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.diedLists
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.titleChallenges
Complete the queries to find the following data in the graph:
-
Directors of
Horrormovies 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
tmdbIdproperty (i.e. it is null).cypherMATCH (m:Movie) WHERE ??????? RETURN m.title -
People
bornin the 1950’s (1950 - 1959).cypherMATCH (p:Person) WHERE p.born.year ?????? RETURN p.name, p.born
Click to reveal the answers
-
Directors of
Horrormovies released in theyear2000.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
tmdbIdproperty (i.e. it is null).cypherMATCH (m:Movie) WHERE m.tmdbId IS NULL RETURN m.title -
People
bornin 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.