How do I get the latest node created in neo4j?

So, I know when you created the nodes neo4j has a UUID for each node. I know you can access a specific node by this UUID by accessing the ID. For example:

START n=node(144) RETURN n;

How can I create the last node that was created? I know I can show all the nodes and then run the same command in anotehr request with the corresponding ID, but is there a way to do this quickly? Can I order nodes by id and limit by 1? Is there an easier way? Anyway, I didn't figure out how to do this with a simple cypher query.

+3


source to share


3 answers


Whenever a new node is not guaranteed to always have a higher id than all previously created nodes,

So the best way is to set the created_at property, which preserves the current timestamp when the node is created. You can use the timestamp () function to keep the current time stamp



Then

Match (n)
Return n
Order by n.created_at desc
Limit 1

      

+4


source


Please be aware that Neo4j's internal node id is not a UUID. It is also not guaranteed that a new node will always have a higher ID than all previously created nodes. The node id is equal to (multiplied by some constant) the offset of the location of the node in the repository file. Due to the use of space, the new node may get a lower ID.

BIG WARNING: Don't make any assumptions on node ids.

Depending on your requirements, you can organize all the nodes in a linked list. There is one "magic" node that has a specific label, for example. References

which always refers to the last node created:

CREATE (entryPoint:Reference {to:'latest'}) // create reference node

      



When a node is created from your domain, there are several things you need to take:

  • remove the relationship latest

    if existing
  • create node
  • connect the new node to the previous node
  • create link link

...

MATCH (entryPoint:Reference {to:'latest'})-[r:latest]->(latestNode)
CREATE (domainNode:Person {name:'Foo'}),   // create your domain node
(domainNode)-[:previous]->(latestNode),    // build up a linked list based on creation timepoint
(entryPoint)-[:latest]->(domainNode)  // connect to reference node
DELETE r   //delete old reference link

      

+2


source


I finally found the answer. The ID () function will return the neo4j id for node:

Match (n) Return n Order by ID(n) desc Limit 1;

-1


source







All Articles