'Is MERGE safe to use when creating a new relationship in Cypher ( Neo4j )?

I am about to migrate all users to have permissions. New users have permissions, but previous doesn't. How to migrate data using a single query?

MATCH (u:Users)
MERGE (u)-[:HAS_PERMISSIONS]->(p:Permissions)
ON CREATE SET p.read = true, p.write = true, p.createdAt = timestamp()
RETURN u

Is this safe? What would be the best way to create permissions for all existing users?

Note: This is just an example problem, I am not actually implementing permissions.



Solution 1:[1]

MERGE means create this relationship when not found and ignore/skip when it exists. So merge will not create a new relationship if that user already has a relationship :HAS_PERMISSIONS

For example:

CREATE (u1:Users {name: 'test1'})
CREATE (u2:Users {name: 'test2'})
CREATE (p:Permissions {read: true, write: false})
CREATE (u1)-[:HAS_PERMISSIONS]->(p)

Then when you run your query, it will only create u2 with a permission to read/write and u1 will still have read access only and not write.

WARNING: your query will create a new instances of node Permissions rather than using a single permissions read/write node. So if you have 10k users with read/write permissions, your graph will have 10k Permissions nodes.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1