4

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

START n=node(144) RETURN n;

How would I get the last node that was created? I know I could show all nodes and then run the same command in anotehr query 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 a simpler way? Either way I have not figured out how to do so through a simple cypher query.

WildBill
  • 9,143
  • 15
  • 63
  • 87

3 Answers3

5

Every time not guaranteed that a new node always has a larger id than all previously created nodes,

So Better way is to set created_at property which stores current time-stamp while creating node. You can use timestamp() function to store current time stamp

Then,

Match (n)
Return n
Order by n.created_at desc
Limit 1
Satish Shinde
  • 2,878
  • 1
  • 24
  • 41
2

Please be aware that Neo4j's internal node id is not a UUID. Nor is it guaranteed that a new node always has a larger id than all previously created nodes. The node id is (multiplied with some constant) the offset of the node's location within a store file. Due to space reclaiming a new node might get a lower id number.

BIG FAT WARNING: Do not take any assumption on node ids.

Depending on your requirements you could organize all nodes into a linked list. There is one "magic" node having a specific label, e.g. References that has always a relationship to the latest created node:

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

When a node from your domain is created, you need to take multiple actions:

  1. remove the latest relationships if existing
  2. create your node
  3. connect your new node to the previously latest node
  4. create the reference 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
Stefan Armbruster
  • 39,465
  • 6
  • 87
  • 97
0

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

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

WildBill
  • 9,143
  • 15
  • 63
  • 87