How to get last node created in neo4j?

匿名 (未验证) 提交于 2019-12-03 00:57:01

问题:

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.

回答1:

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 


回答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 


回答3:

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;



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!