22

I just got started on Neo & tried to look for prior questions on this topic. I need help to rename one of the property keys.

I created the following node:

CREATE (Commerce:Category {title:' Commerce', Property:'Category', Owner:'Magic Pie', Manager:'Simple Simon'})

Now want to rename title to name. Is there a way to do it? I don't want to delete the node as there are 100's of nodes with the property "title".

Dave Bennett
  • 10,996
  • 3
  • 30
  • 41
kkulkarn
  • 345
  • 3
  • 13

2 Answers2

30

Yes, you want to SET a new property name with the value of the old property title. And then REMOVE the old property title. Something like this...

MATCH (c:Category)
WHERE c.name IS NULL
SET c.name = c.title
REMOVE c.title

If you have MANY nodes, it is advisable to perform the operation in smaller batches. Here is an example of limiting the operation to 10k at a time.

MATCH (c:Category)
WHERE c.name IS NULL
WITH c
LIMIT 10000
SET c.name = c.title
REMOVE c.title
Dave Bennett
  • 10,996
  • 3
  • 30
  • 41
  • 1
    Fascinating fact, but when you pass a query to Neo4j, it loads everything into memory before it performs the operation. This is why the Neo4j browser melts down for a long time when you run monster queries. There is a `cypher shell program` you can get that apparently remedies that, but as mentioned above, it's due to lack of batching. – agm1984 Feb 26 '18 at 03:53
0

another solution would be using APOC functions:

MATCH (n) WHERE ID(n) = 1234
WITH *, collect(n) AS nodes  // nodes must be converted into a collection first
CALL apoc.refactor.rename.nodeProperty("oldKey ", "newKey", nodes)
// rename doesn't work if the key has strings ^ postfixed in it
YIELD batches, total, timeTaken, committedOperations
RETURN *

in the case you accidentially added strings at the end (it's possible during create) the property cannot be accessed via:

SET n.newKey = n.oldKey
REMOVE n.oldKey

then you must use:

SET n.newKey = n.`oldKey `
REMOVE n.`oldKey `

this works