具有根节点计数器的树的 Neo4j 唯一 ID?

Neo4j unique IDs by tree with root node counter?

是否在根节点上使用带有计数器的树,在创建新节点时引用和递增,这是一种在 Neo4j 中管理唯一 ID 的可行方法?在上一个关于本论坛性能的问题中 (Neo4j merge performance VS create/set), the approach was described, and it occurred to me it may suggest a methodology for unique ID management without having to extend the Neo4j database (and support that extension). However, I noticed this approach has not been mentioned in other discussions on best practice for unique ID management (Best practice for unique IDs in Neo4J and other databases?)。

任何人都可以帮助验证或拒绝这种方法吗?

谢谢!

您可以只创建一个单例节点(在我的示例中我会给它标签 IdCounter)来保存 "next-valid ID counter" 值。它不需要成为任何 "tree" 的一部分,也不需要它有任何关系。

创建单例时,使用要使用的第一个 id 值对其进行初始化。例如:

CREATE (:IdCounter {nextId: 1});

下面是创建新节点时如何使用它的简单示例。

MATCH (c:IdCounter)
CREATE (x {id: c.nextId})
SET c.nextId = c.nextId + 1
RETURN x;

由于所有 Cypher 查询都是事务性的,如果由于任何原因没有创建节点,那么 nextId 增量也不会完成,因此您永远不会在分配的 ID 号中出现任何间隙.

但是,为了避免重复使用相同的 ID 号,您必须仔细编写查询以确保无论何时创建新节点(使用 CREATECREATE UNIQUE, 或 MERGE).