Gremlin查询报错:如何在foo与bar顶点间添加符合条件的边?
解决Gremlin多值属性匹配时的边创建问题
问题背景
示例图定义:
g.addV("foo").property("x", "a") g.addV("bar").property(set, "y", "a").property(set, "y", "b").property(set, "y", "c")
需求:当bar顶点的y属性集合包含foo顶点的x属性值时,在两者间添加contains边。原查询触发报错:Multiple properties exist for the provided key, use Vertex.properties(y)
报错原因
原查询中使用by("y")直接引用多值属性,而eq步骤仅支持单值比较,无法处理集合类型的属性值,因此抛出该错误。
解决方案
提供三种可行的查询写法:
写法一:使用within进行集合包含判断
g.V().hasLabel("bar").as("bar") .V().hasLabel("foo").as("foo") .where(select("foo").values("x").within(select("bar").values("y"))) .addE("contains").from("bar").to("foo").iterate()
within步骤会直接检查foo的x值是否存在于bar的y属性集合中,适配多值属性的判断逻辑。
写法二:展开多值属性后做单值匹配
g.V().hasLabel("bar").as("bar") .V().hasLabel("foo").as("foo") .where("foo", eq("bar")).by("x").by(values("y").unfold()) .addE("contains").from("bar").to("foo").iterate()
通过values("y").unfold()把bar的多值y属性拆分为单个值,再和foo的x值做eq匹配,让原有的比较逻辑适配多值场景。
写法三:直接调用集合contains方法
g.V().hasLabel("bar").as("bar") .V().hasLabel("foo").as("foo") .where(select("bar").values("y").contains(select("foo").values("x"))) .addE("contains").from("bar").to("foo").iterate()
利用Gremlin对集合的原生支持,直接判断bar的y属性集合是否包含foo的x值,逻辑直观易懂。
验证效果
执行上述任一查询后,可通过以下语句验证边是否成功创建:
g.E().hasLabel("contains").outV().valueMap().inV().valueMap()
返回结果会显示连接bar(y包含a)和foo(x为a)顶点的contains边。
内容的提问来源于stack exchange,提问作者navgeet
相关产品推荐
相关产品推荐

