Neo4J: Renaming property keys
Asked Answered
B

3

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

Bayberry answered 19/2, 2015 at 22:38 Comment(0)
A
31

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
Attila answered 19/2, 2015 at 22:52 Comment(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.Meeks
A
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

Auguste answered 11/11, 2022 at 8:57 Comment(0)
C
0

And also, just for addition, you can use:

SET c.name = c.title, c.title = null

instead of

SET c.name = c.title
REMOVE c.title

People have different views and usages on queries, just use whatever suits you.

Cali answered 10/9, 2023 at 12:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.