Search code examples
neo4jcypher

When to use WHERE in Cypher Neo4j?


I was going through docs and a 2-month-old youtube video on neo4j for beginners. I want to find a user from the database using his name. So here are two way of doing this:

Docs way: MATCH (u:USER {name:"abcd"}) RETURN u.

Youtube video way: MATCH (u:USER} WHERE u.name = "abcd" RETURN u

Both ways do the job but I am confused about which one to use when or not. May anyone tell me when to use which one and what the fundamental difference is in them? Are both methods safe to use?


Solution

  • Your fist query: MATCH (u:USER {name:"abcd"}) RETURN u is only good for simple specific cases, while the second query: MATCH (u:USER} WHERE u.name = "abcd" RETURN u is for the general case. If you have a case where you only want to match a node with a very simple condition, like name = "abcd", both will work.

    For more complicated conditions use WHERE. For example:

    MATCH (u:USER)
    WHERE (u.name = "abcd" AND u.age > 27) OR (u.name = "abcde" AND u.age > 28)
    RETURN u
    

    Inside a WHERE clause you can use boolean operators like AND, OR, XOR, and NOT. you can also use IN and CONTAINS

    For more information, check out the documentation