Filtering Queries

The WHERE command allows you to filter the qeury results using different conditions. If you want to find a specific person, a query using WHERE is as follows:

MATCH (j:Person) WHERE j.name = ‘Jennifer’ RETURN j

You can have negation properties using WHERE NOT as well as boolean operators such as AND, OR, XOR, and NOT. You can also filter results by ranges of values as follows:

MATCH (p:Person) WHERE 3 <= p.yearsExp <= 7 RETURN p

exists()

You can use the exists() method to check if a property exists or not.

String Checks

You can use WHERE with STARTS WITH, CONTAINS, or ENDS WITH to check if certain expression exists in the strings. Here, you can use regular expressions to determine your checks, for example:

MATCH (p:Person) WHERE p.name =~ ‘Jo.*’ RETURN p.name

Check if value is in a list

You can use the IN command to check if a property value is a value in your special list.

MATCH (p:Person) WHERE p.yearsExp IN [1, 5, 6] RETURN p.name, p.yearsExp

Filtering on Patterns

For example, to find people that are friends of a target person who also works for Neo4j:

MATCH (p:Person)-[r:IS_FRIENDS_WITH]->(friend:Person)

WHERE exists((p)-[:WORKS_FOR]->(:Company {name: ‘Neo4j’}))

RETURN p, r, friend

You can also do OPTIONAL MATCH where you want to retrieve results from patterns even if they don’t match the pattern entirely.

Ryan

Ryan

Data Scientist

Leave a Reply