cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Auto Increment Ids

akaur
Node Link

Hello,

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:'test@gmail.com'})-[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

2 REPLIES 2

clem
Graph Steward

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.

MATCH(n)
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.

TL;DR:
See: Neo4j Docs: Cypher Schema

CREATE CONSTRAINT ON (e:Event) ASSERT e.id IS UNIQUE;
CREATE INDEX ON :Event(id);
MATCH (e:Event) SET e.id = 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 e.id=apoc.create.uuid()", {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: