Is using a tree with a counter on the root node, to be referenced and incremented when creating new nodes, a viable way of managing unique IDs in Neo4j? In a previous question on performance on this forum (Neo4j merge performance VS create/set), the approach was described, and it occurred to me it may suggest a methodology for unique ID management without having to extend the Neo4j database (and support that extension). However, I noticed this approach has not been mentioned in other discussions on best practice for unique ID management (Best practice for unique IDs in Neo4J and other databases?).
Can anyone help validate or reject this approach?
Thanks!
You can just create a singleton node (I'll give it the label
IdCounter
in my example) to hold the "next-valid ID counter" value. There is no need for it be part of any "tree" or for it to have any relationships at all.When you create the singleton, initialize it with the first id value that you want to use. For example:
Here is a simple example of how to use it when creating a new node.
Since all Cypher queries are transactional, if the node creation did not happen for any reason, then the
nextId
increment would also not be done, so you should never end up with any gaps in assigned id numbers.However, to avoid re-using the same id number, you would have to write your queries carefully to ensure that the increment always happens whenever you create a new node (using
CREATE
,CREATE UNIQUE
, orMERGE
).