Sovos
Sovos

Reputation: 3390

neo4j cypher: how to change the type of a relationship

I can't find a way to change a relationship type in Cypher. Is this operation possible at all? If not: what's the best way achieve this result?

Upvotes: 33

Views: 20279

Answers (7)

Zac Coleman
Zac Coleman

Reputation: 13

The previous accepted answer is correct, but the usage SET r2 = r where r2 and r are both references to relationships is deprecated. The new usage is SET r2 = properties(r), so the following solution should be used.

MATCH (n:User {name:"foo"})-[r:REL]->(m:User {name:"bar"})
CREATE (n)-[r2:NEWREL]->(m)
// copy properties, if necessary
SET r2 = properties(r)
WITH r
DELETE r

Upvotes: 0

CAW
CAW

Reputation: 49

I'm using Neo4j 4.2.5 recently.

I use APOC apoc.refactor.setType to set the relationship types.

Read the documentation and install the plugin.

https://neo4j.com/labs/apoc/4.2/introduction/

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

I would simply delete the relationship and create a new one:

MATCH (a) - [r:OLD_RELATION] -> (b)
DELETE r
CREATE (a) - [:NEW_RELATION] -> (b)

Upvotes: 1

jpop
jpop

Reputation: 59

I use the following when modifying it.

match (from:Label1 { prop: 1 })-[r:RELATIONSHIP]->(to:Label2 { prop: 2 })
with from, r, to
create (from)-[:NEW_RELATIONSHIP]->(to)
with r
delete r

Upvotes: 0

Michael Hunger
Michael Hunger

Reputation: 41676

Unfortunately there is no direct change of rel-type possible at the moment.

You can do:

MATCH (n:User {name:"foo"})-[r:REL]->(m:User {name:"bar"})
CREATE (n)-[r2:NEWREL]->(m)
// copy properties, if necessary
SET r2 = r
WITH r
DELETE r

Upvotes: 74

LoveTW
LoveTW

Reputation: 3832

The answer from Michael Hunger is correct but it still need with in this cypher query. WITH can be used when you want to switch different operation in one cypher query. http://docs.neo4j.org/chunked/stable/query-with.html

MATCH (n:User {name:"foo"})-[r:REL]->(m:User {name:"bar"})
CREATE (n)-[r2:NEWREL]->(m)
SET r2 = r
WITH r
DELETE r

Upvotes: 14

jjaderberg
jjaderberg

Reputation: 9952

You can't, the type of a relationship is constitutive or essential, as opposed to node labels which are arbitrary bags to group nodes. (See this q/a for an analogy.) You have to create the new relationship, delete the old (and copy properties if there are any).

Upvotes: 5

Related Questions