33

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?

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Sovos
  • 3,330
  • 7
  • 25
  • 36
  • 6
    If you use the [apoc procedures plugin](https://neo4j-contrib.github.io/neo4j-apoc-procedures/) you can simply use `call apoc.refactor.setType(rel, 'NEW-TYPE')` to easily change the relationship type. It automatically does what you would have to manually do otherwise (as per the answers). – ADTC May 30 '16 at 07:06

6 Answers6

73

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
Hendy Irawan
  • 20,498
  • 11
  • 103
  • 114
Michael Hunger
  • 41,339
  • 3
  • 57
  • 80
  • 3
    brilliant! (added the `WITH` otherwise the query was failing) – Sovos Mar 27 '14 at 07:21
  • Excellent answer. But, this only deletes relationship & return `ID` of that relationship & doesn't show updated relationship until `WITH` clause is added to it, as commented above & answered by @LoveTW. I'll give you `+1` for **fastest answer**. – OO7 Nov 25 '14 at 13:27
14

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
LoveTW
  • 3,746
  • 12
  • 42
  • 52
5

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).

Community
  • 1
  • 1
jjaderberg
  • 9,844
  • 34
  • 34
1

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

MATCH (a) - [r:OLD_RELATION] -> (b)
DELETE r
CREATE (a) - [:NEW_RELATION] -> (b)
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
1

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/

CAW
  • 49
  • 1
  • 8
0

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
jpop
  • 59
  • 7