Search code examples
gremlintinkerpop

How sort vertices by edge values in Gremlin


Given the air-routes graph, say I want to get all possible one-stopover routes, like so:

[home] --distance--> [stopover] --distance--> [destination]

where [home], [stopover] and [destination] are airport nodes that each have a property 'code' that represent an airport code; and distance is an integer weight given to each edge connecting two airport nodes.

How could I write a query that gets me the airport codes for [home], [stopover] and [destination] such that the results are sorted as follows:

  1. [home] airport codes are sorted alphabetically.
  2. For each group of [home] airport, the [stopover] airport codes are sorted by the distance between [home] and [stopover] (ascending).
  3. After sorting 1 and 2, [destination] airport codes are sorted by the distance between [stopover] and [destination].

(Note: it doesn't matter if [home] and [destination] are the same airport)


Solution

  • One way you could do this is through group with nested by modulation.

    g.V().
      group().
        by('code').
        by(
          outE('route').
          order().by('dist').
          inV().
          group().
            by('code').
            by(
              outE('route').
              order().by('dist').
              inV().
              values('code').fold())).
      unfold()
    

    The result is something like:

    1.  {'SHH': {'WAA': ['KTS', 'SHH', 'OME'], 'OME': ['TLA', 'WMO', 'KTS', 'GLV', 'ELI', 'TNC', 'WAA', 'WBB', 'SHH', 'SKK', 'KKA', 'UNK', 'SVA', 'OTZ', 'GAM', 'ANC']}}
    2.  {'KWN': {'BET': ['WNA', 'KWT', 'ATT', 'KUK', 'TLT', 'EEK', 'WTL', 'KKH', 'KWN', 'KLG', 'MLL', 'KWK', 'PQS', 'CYF', 'KPN', 'NME', 'OOK', 'GNU', 'VAK', 'SCM', 'HPB', 'EMK', 'ANC'], 'EEK': ['KWN', 'BET'], 'TOG': ['KWN']}}
    
    3.  {'NUI': {'SCC': ['NUI', 'BTI', 'BRW', 'FAI', 'ANC'], 'BRW': ['ATK', 'AIN', 'NUI', 'PIZ', 'SCC', 'FAI', 'ANC']}}
    
    4.  {'PSG': {'JNU': ['HNH', 'GST', 'HNS', 'SGY', 'SIT', 'KAE', 'PSG', 'YAK', 'KTN', 'ANC', 'SEA'], 'WRG': ['PSG', 'KTN']}}
    
    5.  {'PIP': {'UGB': ['PTH']}}
    .
    .
    .