在Neo4j中生成友好的id序列 [英] Generating friendly id sequence in Neo4j

查看:99
本文介绍了在Neo4j中生成友好的id序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆关系,我想为子对象创建一个友好的ID,以便我可以拥有更友好的URL.

I have a bunch of relationships where I would like to create a friendly id for the child objects so that I can have friendlier URLs.

每次我为特定的父对象创建一个子对象时,我都希望自动包含一个友好ID,该ID会顺序递增.因此,第一个孩子将具有友好的ID 1,第二个孩子将具有友好的ID 2,依此类推.如果孩子被删除,我不想重复使用ID.使事情变得复杂的是,我想为此建立许多这样的关系.

Every time I create a child object for a particular parent object I would like to automatically include a friendly id which increments sequentially. So the first child would have friendly id 1, the second would have friendly id 2, etc. I don't want to reuse id's if children are deleted. To complicate matters, there are many such relationships that I would like to do this for.

当前,我正在父节点上缓存某些状态,并在创建子节点时使用它来填充友好ID:

Currently I'm caching some state on the parent node and using that to populate the friendly id when creating children:

CREATE (o:Foo {name: 'parent', nextChildId: 1})

MATCH (o:Foo)
WHERE o.name = 'parent'
CREATE (o)-[:HAS]->(c:Child {name: 'child1', friendlyId: o.nextChildId})
SET o.nextChildId = o.nextChildId + 1

MATCH (o:Foo)
WHERE o.name = 'parent'
CREATE (o)-[:HAS]->(c:Child {name: 'child2', friendlyId: o.nextChildId})
SET o.nextChildId = o.nextChildId + 1

问题在于,由于两个客户端可以尝试同时创建两个子代,因此两个子代最终可能具有相同的友好ID.我不确定如何防止这种情况的发生.

The problem is that there is a chance that two children will end up with the same friendly id since two clients could try and create children at the same time. I'm not sure how to prevent this from happening.

推荐答案

对于其他希望做到这一点的人,我从Neo4j Google小组获得了解决方法.诀窍是通过删除不存在的属性在节点上创建锁.这样可以序列化对节点的访问,并防止多个子节点获得相同的ID.

For anyone else that is looking to do this, I got a workaround from the Neo4j Google group. The trick is to create a lock on the node by removing a non-existent property. This serializes access to the node and prevents multiple children from getting the same id.

CREATE (o:Foo {name: 'parent', nextChildId: 1})

MATCH (o:Foo)
WHERE o.name = 'parent'
REMOVE o.lock  // non-existent property
CREATE (o)-[:HAS]->(c:Child {name: 'child1', friendlyId: o.nextChildId})
SET o.nextChildId = o.nextChildId + 1

这篇关于在Neo4j中生成友好的id序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆