1
votes

I'm working on a gremlin query that navigates along several edges and eventually produces a String. Depending on the graph content, this traversal may be empty. In case that the traversal ends up being empty, I want to return a default value instead.

Here's what I am currently doing:

    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)

This query works, but it is fairly convoluted - all I want is a default if the traversal ends up not finding anything.

Does anybody have a better proposal? My only restriction is that it has to be done within gremlin itself, i.e. the result must be of type GraphTraversal.

1

1 Answers

6
votes

You can probably use coalesce() in some way:

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

If you have more complex logic in mind for determining if something is found or not then consider choose() step.