Gremlin - 如果顶点不存在,则仅添加顶点 [英] Gremlin - only add a vertex if it doesn't exist

查看:28
本文介绍了Gremlin - 如果顶点不存在,则仅添加顶点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组用户名(例如 ['abc','def','ghi'])要添加到图表中的用户"标签下.

I have an array of usernames (eg. ['abc','def','ghi']) to be added under 'user' label in the graph.

现在我首先要检查用户名是否已经存在 (gV().hasLabel('user').has('username','def')) 然后只添加那些'user' 标签下的 username 属性不匹配.

Now I first want to check if the username already exists (g.V().hasLabel('user').has('username','def')) and then add only those for which the username property doesn't match under 'user' label.

此外,这可以在单个 gremlin 查询或 groovy 脚本中完成吗?

Also, can this be done in a single gremlin query or groovy script?

我正在使用 Titan 图数据库、tinkerpop3 和 gremlin REST 服务器.

I am using titan graph database, tinkerpop3 and gremlin REST server.

推荐答案

使用脚本",您始终可以将多行/命令脚本传递给服务器进行处理,以完成您想要完成的任务.然后通过使用变量、if/then 语句等的普通编程技术回答这个问题:

With "scripts" you can always pass a multi-line/command script to the server for processing to get what you want done. This question is then answered with normal programming techniques using variables, if/then statements, etc:

t = g.V().has('person','name','bill')
t.hasNext() ? t.next() : g.addV('person').property('name','bill').next()

或者也许:

g.V().has('person','name','bill').tryNext().orElseGet{
    g.addV('person').property('name','bill').next()}

但这些都是 groovy 脚本,最终 TinkerPop 建议避免使用脚本和闭包,以支持纯遍历.在单次遍历中处理获取或创建"的一般方法是做这样的事情:

But these are groovy scripts and ultimately TinkerPop recommends avoiding scripts and closures in favor of a pure traversal. The general way to handle a "get or create" in a single traversal is to do something like this:

gremlin> g.V().has('person','name','bill').fold().
......1>   coalesce(unfold(), 
......2>            addV('person').property('name','bill'))
==>v[18]

另请参阅此StackOverflow 问题,了解有关 upsert/获取或创建"模式的更多信息.

Also see this StackOverflow question for more information on upsert/"get or create" patterns.

这篇关于Gremlin - 如果顶点不存在,则仅添加顶点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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