如何访问Gremlin中使用coalesce创建的顶点(含关联边场景)
问题解答
问题描述
- 如何访问Gremlin中使用
coalesce创建的顶点? - 如何访问Gremlin中使用
coalesce并伴随创建边时生成的顶点?
在提供的查询中存在以下情况:
- 当
country顶点已存在时,该顶点会被传递到下一步(添加state的逻辑); - 当创建新顶点时,
coalesce返回的是新创建的边,导致在coalesce外部尝试用as()和select()访问新顶点时,出现错误「Edge cannot be cast to Vertex」。
原查询代码:
g.V().hasLabel('country').has('name', 'Japan').fold() .coalesce(__.unfold(), __.addV('country').property('name', 'Japan')).as('country') // 添加state .coalesce(outE('has').inV().hasLabel('state').has('name', 'B'), __.addV('state').as('s').property('name', 'B').addE('has').from('country').select('s')).as('state') // 添加city/town .coalesce(outE('has').inV().hasLabel('city_town').has('name', 'F'), __.addV('city_town').property('name', 'F').addE('has').from('state')).as('city_town')
解决方案
问题核心是coalesce的两个分支必须返回相同类型的元素,否则后续步骤会因类型不匹配报错。你的查询中,coalesce第一个分支返回顶点,但第二个分支执行addE后返回的是边对象,导致类型不一致。
修复后的查询
调整第二个分支的逻辑,确保coalesce始终返回顶点:
g.V().hasLabel('country').has('name', 'Japan').fold() .coalesce(__.unfold(), __.addV('country').property('name', 'Japan')).as('country') // 添加state .coalesce( outE('has').inV().hasLabel('state').has('name', 'B'), __.addV('state').property('name', 'B').as('s').addE('has').from('country').select('s') ).as('state') // 添加city/town .coalesce( outE('has').inV().hasLabel('city_town').has('name', 'F'), __.addV('city_town').property('name', 'F').as('ct').addE('has').from('state').select('ct') ).as('city_town')
关键说明
- 在创建新顶点和边的分支中,先用
as()标记新创建的顶点,执行addE后通过select()回到该顶点,确保coalesce的这个分支最终返回顶点而非边; - 这样
coalesce的两个分支(已存在的顶点、新创建的顶点)都返回Vertex类型,后续的as()和select()操作就不会出现类型转换错误; - 若需在查询末尾返回所有匹配/创建的顶点,可在最后添加
select('country', 'state', 'city_town')获取顶点集合。
内容的提问来源于stack exchange,提问作者Thirumal
相关产品推荐
相关产品推荐

