Diego Gallegos
Diego Gallegos

Reputation: 1752

Neo4j: One to one relationship update

Currently I have two label types:

A User works in an organization. I am trying to update this relationship when the organization changes. I came up with a solution that doesn't satisfy me. First I delete the current relationship with the previous node and then I create the relationship again with the new organization. This is how it logically works in RDBMS but on graph databases should be more easily.

       MATCH (user:User)
       WHERE id(user) = $id
       SET user = $props

       WITH user
       OPTIONAL MATCH (user)-[ro:WORKS_IN]->(organization:Organization)
       DELETE ro

       WITH user
       MATCH (organization:Organization {name: 'Ebay'})
       CREATE (user)-[:WORKS_IN]->(organization)

       RETURN user , organization

I need to come up with a more elegant solution to this problem.

Upvotes: 2

Views: 336

Answers (2)

InverseFalcon
InverseFalcon

Reputation: 30397

Honestly I don't think there's very much here you can change to make this less verbose. The most I can think of right now is leaving off the variable and type from the :WORKS_IN relationship pattern (but only if it's okay to remove all :WORKS_IN relationships from a :User node, assuming they are all :Organization nodes at the other end:

   MATCH (user:User)
   WHERE id(user) = $id
   SET user = $props

   WITH user
   OPTIONAL MATCH (user)-[ro:WORKS_IN]->()
   DELETE ro

   WITH user
   MATCH (organization:Organization {name: 'Ebay'})
   CREATE (user)-[:WORKS_IN]->(organization)

   RETURN user , organization

Upvotes: 1

Bruno Peres
Bruno Peres

Reputation: 16365

You can install APOC procedures and use the graph refactoring procedure apoc.refactor.to to change the end node. The docs says:

call apoc.refactor.to(rel, endNode): redirect relationship to use new end-node.

Upvotes: 0

Related Questions