Search code examples
gremlinjanusgraphamazon-neptune

Gremlin order on Map results


I have the below query:

g.V('1')
    .union(
        out('R1')
            .project('timestamp', 'data')
                .by('completionDate')
                .by(valueMap().by(unfold()))
        out('R2')
            .project('timestamp', 'data')
                .by('endDate')
                .by(valueMap().by(unfold()))
        )

How can I order the UNION results by timestamp? I've tried using ".order().by('timestamp')" but this only works on traversals and UNION returns a MAP object.


Solution

  • Here are a couple of ways to approach it. First, you could just use your code as-is and then order() by the "timestamp":

    g.V('1').
      union(out('R1').
              project('timestamp', 'data').
                by('completionDate').
                by(valueMap().by(unfold())),
            out('R2').
              project('timestamp', 'data').
                by('endDate').
                by(valueMap().by(unfold()))).
      order().by(select('timestamp'))
    

    Note the difference is to select() the key from the Map that you want to sort on. Versions after 3.4.5 will work more as you expect and you can simply do by('timestamp') for a Map as well as an Element.

    I think that a more readable approach however would be to go with this approach:

    g.V('1').
      out('R1','R2').
      project('timestamp', 'data').
        by(coalesce(values('endDate'), values('completionDate'))).
        by(valueMap().by(unfold())).
      order().by(select('timestamp'))
    

    You might need to enhance the by(coalesce(...)) depending on the nature of your schema, but hopefully you get the idea of what I'm trying to do there.