shawn wang
shawn wang

Reputation: 35

neo4j generate unique id for existing node

I had the graphical database created a while ago and I found that my Person nodes does not have an ID. Is it possible to generate an unique id for the existing nodes? I see when I use neo4j browser, there is an auto generated ID for graph view but the ID is not in the database.

Let me know if a Cypher query can do something like this:

MATCH (p:Person) 
WHERE NOT p.id
SET p.id = AUTO_GEN_ID
RETURN p

so the new nodes would be modified?

Upvotes: 4

Views: 4895

Answers (2)

cybersam
cybersam

Reputation: 66999

All nodes have an automatically-generated "native ID" (that can be obtained via the ID function), but that native ID can be re-used for another node if the original node is deleted. To avoid confusion, it is best practice to add your own property (e.g., id, or uuid) if you need a unique ID.

You can use apoc.create.uuid to create a UUID. For example:

MATCH (p:Person) 
WHERE NOT EXISTS(p.id)
SET p.id = apoc.create.uuid()
RETURN p

The APOC library can also automatically assign a UUID to a given property when a node with a specified label is created.

Neo4j 5.x+

apoc.create.uuid() was deprecated in Neo4j 5.0, and replaced by the Cypher function randomUUID()

Upvotes: 4

freezing_
freezing_

Reputation: 1044

You can pass and 'unique' id via the language that you are using, just lookup uuid for you technology.

to be 100% sure that the codes are unique you have to pre-generate them or have counter that is thread-safe.

Upvotes: 1

Related Questions