简体   繁体   中英

What is the difference between using/(not using) MATCH in a MERGE query in cypher?

When creating a probably existing node in neo4j, i'm getting confused about the use of MATCH . What would be the difference between these two cases?

1.- MERGE (n:Person { user_id: 1234 ,sex:'male'})

2.- MATCH (a:Person) WHERE a.user_id = 1234 AND a.sex = 'male' MERGE (n:Person { user_id: 1234 ,sex:'male'})

Actually even after reading the documentation I can't understand the usefullness of MATCH

MERGE is "get or create". If the pattern exists, get it (bind to the variables specified). If the pattern specified does not exist, then create it.

MATCH is just "get". If the pattern exists, bind to the variables specified. If the pattern does not exist, then nothing is bound to the variables.

Here are the differences between your 2 queries.

  • Query #1 will create a node with the specified label and properties if and only if such a node is not found.

  • Query #2 is basically a waste of time. It calls MATCH to look for a node with the specified label and properties, and only if it is found does it call MERGE (which would create the node if and only if it does not already exist). So, #2 ends up never making any changes. If the node already existed, it will continue to exist (since MERGE will discover it doesn't need to do anything). If it did not exist, it will remain nonexistent (since MERGE would not even be invoked).

Needless to say, one would never want to use MATCH and MERGE in the same way as #2. Here is a more typical example of MATCH and MERGE , which ensures that the SPOUSE_OF relationship exists between 2 people who are already in the DB:

MATCH (a:Person {user_id: 1234}), (b:Person {user_id: 5678})
MERGE (a)-[:SPOUSE_OF]->(b);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM