Reputation: 8423
I have the following Neo4J Cypher query:
MATCH (u:User {uid: $userId})
UNWIND $contextNames as contextName
MERGE (context:Context {name:contextName.name,by:u.uid,uid:contextName.uid})
ON CREATE SET context.timestamp=$timestamp
MERGE (context)-[:BY{timestamp:$timestamp}]->(u)
The last string always creates a new relation between the context
and the u
node. However, what if I just want to update it? How do I integrate this logic into the query above?
Do I have to add WITH context,u
before the MERGE
and then add rel:BY
into the query?
Or do MATCH (context)-[rel:BY....
and then update the rel
?
Just looking for the most efficient "best practices" way to do that.
Thanks!
Upvotes: 0
Views: 178
Reputation: 311
There are two possible situation which might occur:
context
and u
is already presentcontext
and u
is not yet present (this will happen when context
was just created by merge)When you run the following line
MERGE (context)-[:BY{timestamp:$timestamp}]->(u)
Neo4j will check if there is already a relation BY
in place between context
and u
with the given timestamp value. If yes, no new relation will be created. I guess that the timestamp is not a proper identifier for matching a relation, especially since you write that you want to update it. Therefore, I recommend to update the query in the following way:
MATCH (u:User {uid: $userId})
UNWIND $contextNames as contextName
MERGE (context:Context {name:contextName.name,by:u.uid,uid:contextName.uid})
ON CREATE SET context.timestamp=$timestamp
MERGE (context)-[by:BY]->(u)
SET by.timestamp=$timestamp
This way, a relation will be created if not already present. Either way, the timestamp will be set to the specified value.
Upvotes: 1