我正在处理一个沿多个边缘导航并最终生成String. 根据图形内容,此遍历可能为空。如果遍历最终为空,我想改为返回一个默认值。
这是我目前正在做的事情:
GraphTraversal<?, ?> traversal = g.traversal().V().
// ... fairly complex navigation here...
// eventually, we arrive at the target vertex and use its name
.values("name")
// as we don't know if the target vertex is present, lets add a default
.union(
identity(), // if we found something we want to keep it
constant("") // empty string is our default
)
// to make sure that we do not use the default if we have a value...
.order().by(s -> ((String)s).length(), Order.decr)
.limit(1)
Run Code Online (Sandbox Code Playgroud)
这个查询有效,但它相当复杂 - 如果遍历最终没有找到任何东西,我想要的只是一个默认值。
有人有更好的建议吗?我唯一的限制是它必须在 gremlin 本身内完成,即结果必须是 type GraphTraversal。
您可能可以coalesce()以某种方式使用:
gremlin> g.V().has('person','name','marko').coalesce(has('person','age',29),constant('nope'))
==>v[1]
gremlin> g.V().has('person','name','marko').coalesce(has('person','age',231),constant('nope'))
==>nope
Run Code Online (Sandbox Code Playgroud)
如果您有更复杂的逻辑来确定是否找到了某些东西,那么请考虑choose()步骤。