如何用Gremlin mergeV()实现无副作用Upsert并判断顶点是否新增
使用mergeV()实现CosmosDB Graph顶点Upsert并判断状态
要把原来的fold()/coalesce()/unfold()模式转换成mergeV()模式,核心是利用mergeV()的内置upsert能力,配合选项区分顶点是新增还是已存在,以下是适配后的查询及说明:
转换后的mergeV()查询语句
g.mergeV(['event', 'id', '1']) .option(onCreate, property('_created', true)) .project('vertex', 'exists') .by(identity()) .by( coalesce( has('_created').sideEffect(drop('_created')).constant(false), constant(true) ) )
关键映射说明
mergeV的匹配规则:
mergeV(['event', 'id', '1'])对应原查询中g.V().has('event','id','1')的匹配逻辑——指定以event标签、id=1作为顶点的唯一识别条件,自动完成“存在则匹配,不存在则创建”的upsert操作。状态区分逻辑:
- 通过
option(onCreate, property('_created', true))在新增顶点时添加一个临时属性_created作为标记; - 在
project阶段,通过coalesce判断顶点是否带有_created属性:- 存在该属性说明是新增顶点,返回
exists: false,同时用sideEffect(drop('_created'))清理临时属性; - 不存在则说明是已有的顶点,返回
exists: true。
- 存在该属性说明是新增顶点,返回
- 通过
扩展多属性匹配:
如果需要用多个属性作为匹配条件,只需扩展mergeV的输入列表即可,比如同时匹配id和type:g.mergeV(['event', 'id', '1', 'type', 'conference']) .option(onCreate, property('_created', true)) .project('vertex', 'exists') .by(identity()) .by( coalesce( has('_created').sideEffect(drop('_created')).constant(false), constant(true) ) )
内容的提问来源于stack exchange,提问作者Zhen_Lian
相关产品推荐
相关产品推荐

