我知道我应该避免在 neo4j 中使用内部 id,但是有没有办法访问 neo4j 中节点的内部 id 并根据此内部 id 返回所有节点?
我试过这个:
match (n) where id(n)=123 return n;
Run Code Online (Sandbox Code Playgroud)
这将返回内部 id=123 的节点,但是如何根据内部 id 获取数据库中存在的所有节点?
想象一下:
CREATE (:SomeLabel {myId:123})-[:someRelationshipType]->(:SomeLabel {myId:456})
Run Code Online (Sandbox Code Playgroud)
这将创建一个两个节点,它们之间存在关系。关系类型为someRelationshipType。
那么,如果您执行以下查询会发生什么?
MATCH
(s:SomeLabel)-[rel:someRelationshipType]->(target:SomeLabel)
RETURN
ID(s), // Built-in Neo4j function to retrieve the internal node id
s.myId, // Access the property myId that you created above
LABELS(s), // Lists all labels for the start node
ID(rel), // Built-in Neo4j function to retrieve the internal relationship id
TYPE(rel), // Built-in Neo4j function to retrieve the relationship type
ID(target), // Built-in Neo4j function to retrieve the internal node id
target.myId // Access the property myId that you created above
Run Code Online (Sandbox Code Playgroud)
查询的输出类似于:
ID(root) | root.myId | LABELS(root) | ID(rel) | TYPE(rel) | ID(target) | target.myId
-----------------------------------------------------------------------------------------------
192 | 123 | SomeLabel | 271 | someRelationshipType | 193 | 456
Run Code Online (Sandbox Code Playgroud)
这显示了一些有趣的事情。首先,有几个内置函数会返回您自己没有提供的值。该ID()函数返回节点或关系的内部 ID。这是一个生成的 id,你不能控制自己,它完全由数据库处理(它甚至可能被重用,所以你不能真正依赖这些值)。每个节点都有一个内部 id并且它在整个数据库中是唯一的,因此您永远找不到具有相同内部 id 的多个节点。
但是,在上面的查询中还有一个名为 的属性myId。可以有多个节点实际上具有该属性的相同值,因为它是我们自己创建的属性。确保这些属性包含唯一值的唯一方法是使用UNIQUE-constraint(请参阅此处的文档)。
可以使用以下语法设置唯一约束:
CREATE CONSTRAINT ON (n:SomeLabel) ASSERT n.myId IS UNIQUE
Run Code Online (Sandbox Code Playgroud)
作为原始MATCH-query一部分的其他函数是:
LABELS- 返回属于节点的所有标签的列表TYPE - 返回创建节点时指定的关系类型。最后要注意的是,如果您想获取图中的所有节点,可以使用以下查询:
MATCH (n) RETURN n;
Run Code Online (Sandbox Code Playgroud)
但是,请注意 - 如果图很大,检索所有节点很可能是一个痛苦/昂贵的操作。