Search code examples
gremlin

Getting values of a path with two different edges


I'm looking for a pattern.

I'm working on this query:

g.V().has('objid','7615388501660').as('location')
    .in('enhabits').as('population')
    .out('isInFaction').as('faction')
    .in('isInFaction').out('isOfSpecies').as('species')
    .path().by('name')

and I get this back:

    "labels": [
      ["location"],
      ["population"],
      ["faction"],
      [],
      ["species"]
    ],
    "objects": [
      "Plara",
      "Se Bemon",
      "Se",
      "Se Bemon",
      "Wan"
    ]

but there is an extra step [] that I feel is the wrong approach. It also traverses through all of the populations in that faction, not just the one I want. What I want is each record of the location, population, faction, species in a list. Or, in another way, for each population in that location, I want that population, it's faction, it's species.


Solution

  • You can often flatten these backtracking type of use cases by introducing a union step into the query. Something along the lines of :

    g.V().has('objid','7615388501660').as('location').
      in('enhabits').as('population').
      local(
        union(
          out('isInFaction').as('faction'),
          out('isOfSpecies').as('species')).
        fold()).
      path().
          by(unfold().values('name').fold())