代码之家  ›  专栏  ›  技术社区  ›  Martin Häusler

如何在gremlin中为空遍历添加默认值?

  •  0
  • Martin Häusler  · 技术社区  · 7 年前

    我正在处理一个小精灵查询,它沿着多条边导航,最终生成一个 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)
    

    作品 ,但它相当复杂-如果遍历最终没有找到任何内容,我只需要一个默认值。

    有人有更好的建议吗?我唯一的限制是它必须在gremlin内部完成,即结果必须是类型 GraphTraversal .

    1 回复  |  直到 7 年前
        1
  •  6
  •   stephen mallette    7 年前

    你可以用 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
    

    choose()