我正在尝试掌握 Gremlin。彻底阅读文档后,我似乎仍然在概念上苦苦挣扎。
我正在创建一个基本的新闻源,遵循此处 Neo4j 文档中的模型:
http://neo4j.com/docs/snapshot/cypher-cookbook-newsfeed.html
我实际上使用的是 titandb,但我遵循与上面所示相同的原则/模式。
到目前为止,我已经创建了一个 user
顶点图,它们通过 friend
边连接。
我可以添加一个新的 post
顶点并通过 posted
边将其连接到 user
顶点,如下所示:
def activity = graph.addVertex(T.label, "post");
activity.property("post_id", post_id);
activity.property("time", time);
activity.property("body", body);
def g = graph.traversal();
def user = g.V().hasLabel("user").has("userid", userid).next();
user.addEdge("posted", activity, "time", time);
但是,我需要能够在单个 Gremlin 脚本中执行以下操作:
- 如上所述创建新的
post
顶点。 - 删除
user
和任何当前连接的post
顶点之间的旧posted
边。但仅当当前存在帖子时。 - 使用新的
posted
边将新的post
顶点附加到user
。 - 最后,如果之前有一个
post
顶点,则通过next
边将其附加到新添加的post
顶点。最终为每位用户创建长长的帖子流。
我一直在玩弄,通过反复试验,现在似乎已经有几个小时了,但似乎无法理解它。
如有任何帮助,我们将不胜感激。
最佳答案
另一种方式(使用单次遍历):
用单个用户创建初始图:
gremlin> g = TinkerGraph.open().traversal()
==>graphtraversalsource[tinkergraph[vertices:0 edges:0], standard]
gremlin> g.addV("user").property("userid", 123)
==>v[0]
添加第一个帖子:
gremlin> g.V().has("user", "userid", 123).as("user"). /* find the user */
addV("post").as("p").property("post_id", 1). /* add a new post */
property("time", System.currentTimeMillis()).
property("body", "bla bla").
addE("posted").from("user").as("e"). /* connect user and post */
property("time", System.currentTimeMillis()).
outV(). /* traverse to user */
outE("posted").where(neq("e")).as("o"). /* traverse to any pre-existing posted edge */
inV(). /* traverse to pre-existing post */
addE("next").to("p"). /* connect it with the new post */
select("o").drop() /* drop the old posted edge */
gremlin> // check
gremlin> g.V().not(inE()).repeat(union(outE("posted").inV(), inE("next").outV())).until(__.not(union(outE("posted"), inE("next")))).path().by(label)
==>[user, posted, post]
添加另一个帖子(相同的查询):
gremlin> g.V().has("user", "userid", 123).as("user").
addV("post").as("p").property("post_id", 1).
property("time", System.currentTimeMillis()).
property("body", "bla bla").
addE("posted").from("user").as("e").
property("time", System.currentTimeMillis()).
outV().
outE("posted").where(neq("e")).as("o").
inV().
addE("next").to("p").
select("o").drop()
gremlin> // check
gremlin> g.V().not(inE()).repeat(union(outE("posted").inV(), inE("next").outV())).until(__.not(union(outE("posted"), inE("next")))).path().by(label)
==>[user, posted, post, next, post]
关于titan - 如何在两个当前连接的顶点之间插入一个顶点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39987363/