Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.
12-16-2020 09:45 AM
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
12-16-2020 11:01 AM
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.
12-16-2020 01:29 PM
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:
All the sessions of the conference are now available online