Auto Increment Ids


I am trying to auto generate unique ids. Right now I am using this query:

MERGE (i:UserIds {value:"userid"}) ON CREATE SET i.user_id = 1 ON MATCH SET i.user_id = i.user_id + 1
CREATE (u:User {userid:i.user_id, Name:'XYZ', Email:''})-[h:has]->(v:User_access{Password:'xx'})
return u,h,v

but the problem is that I am not able to reuse previously deleted ids.
Also I have tried with apoc procedures, still I am facing the same issue.

Any help would be appreciated. Thanks

The built-in id does what you want. BUT it's somewhat dangerous if you save the id somewhere. So, you might be better off doing what you are doing.

RETURN id(n) // The id() function returns the internal Neo4J id.  It gets reused when nodes get deleted.
  1. Why do you want to reuse auto-generated IDs!?
  2. There is not an efficient mechanism for finding unused numbers in an index, so if you're trying to ensure sequential IDs for some other purpose, you should probably do that other thing a different way.... what is that other thing you're trying to do?

Here's two great posts about auto-generating IDs, that dive pretty deep, and offer some suggestions. IMO, don't use the built-in id. It is not stable, and can change, and can cause severe problems in queries where you need to delete anything.

See: Neo4j Docs: Cypher Schema

MATCH (e:Event) SET = id(e);

See: apoc.create.uuid and apog.trigger

You could potentially use apoc.trigger to auto-generate a UUID on create, if it is really necessary, but it's better to generate in your script when you use a CREATE statement.

CALL apoc.trigger.add('create-event-gen-id',"UNWIND {createdNodes} AS e set", {phase:'after'});

My answer on here includes code-samples to auto-generate UUIDs, and make them unique:

This discussion includes many different approaches to the problem: