Gremlin查询关联边不存在时如何返回指定顶点与边结果
Gremlin可选边查询缺失返回问题解决方案
问题根因
你原有查询中使用的outE()属于过滤型遍历步骤,只要匹配不到对应的边,就会直接丢弃当前整条遍历路径,所以当PRODUCES边不存在时,整个查询就没有结果返回。
你之前尝试的optional改写思路是对的,只是逻辑拆分有问题,需要把仅在可选边存在时才执行的遍历逻辑全部包裹在optional步骤内,必选逻辑保留在外部。
正确改写代码
janusGraph.traversal().V() .has("isActive", "true") .hasLabel("ENTITY").`as`("input_entity") // 必选逻辑:查询input_entity对应的状态 .outE("HAS_STATE").`as`("input_entity_state_edge").inV().hasLabel("ENTITY_STATE").`as`("input_entity_state") // 必选逻辑:查询input_entity关联的处理任务 .select<String>("input_entity").outE("PROCESSED_BY").`as`("processed_by") .inV().`as`("job") // 必选逻辑:查询任务对应的状态 .outE("HAS_STATE").`as`("job_state_edge").inV().hasLabel("JOB_STATE").`as`("job_state") // 可选逻辑:仅当PRODUCES边存在时,才查询后续关联的产出、输出实体等信息 .optional<Any>( select<String>("job").outE("PRODUCES").`as`("produces") .select<String>("input_entity").outE("CONNECTS_TO").`as`("connects_to") .inV().hasLabel("ENTITY").has("entityName", TextP.startingWith(rootNamespace)) .`as`("output_entity").outE("HAS_STATE") .`as`("output_entity_state_edge").inV().hasLabel("ENTITY_STATE").`as`("output_entity_state") ) // 所有字段查询,未匹配到的可选字段自动返回null .select<String>("input_entity","output_entity","processed_by","produces","job","job_state","input_entity_state","output_entity_state","input_entity_state_edge","output_entity_state_edge","job_state_edge","connects_to") .by(elementMap<Element, Any>()).toList()
实现说明
optional()步骤在匹配不到遍历路径时,不会终止当前主路径,仅不会对内部定义的别名(如produces、output_entity等)赋值- 最终
select时,未赋值的别名会自动返回null值,保证必选字段input_entity、processed_by等可以正常返回 - 如果你需要给可选字段自定义默认值而非返回null,可以将
optional替换为coalesce步骤,示例:.coalesce(outE("PRODUCES").`as`("produces"), constant(null).`as`("produces"))
内容的提问来源于stack exchange,提问作者anup agrawal
相关产品推荐
相关产品推荐

