Wolfgang Fahl
Wolfgang Fahl

Reputation: 15769

GroupCount order by

The Unit test code from the simplegraph-core testsuite below displays the region count of airports but it is not ordered as I would have expected.

The result starts with:

NZ-BOP=  3
MZ-A=  1
MZ-B=  1
IN-TN=  5
MZ-N=  1
PW-004=  1
MZ-I=  2
BS-FP=  1
IN-TR=  1
MZ-T=  1
BJ-AQ=  1
GB-ENG= 27

I looked into

and searched for "GroupCount" in questions tagged gremlin to no avail

What is necessary to fix the ordering?

Unit Test see also https://github.com/BITPlan/com.bitplan.simplegraph/blob/master/simplegraph-core/src/test/java/com/bitplan/simplegraph/core/TestTinkerPop3.java

  @Test
  public void testSortedGroupCount() throws Exception {
    Graph graph = getAirRoutes();
    GraphTraversalSource g = graph.traversal();
    Map<Object, Long> counts = g.V().hasLabel("airport").groupCount()
        .by("region").order().by(Order.decr).next();
    assertEquals(1473, counts.size());
    for (Object key : counts.keySet()) {
      System.out.println(String.format("%s=%3d", key, counts.get(key)));
    }
  }

Upvotes: 5

Views: 2415

Answers (2)

Thiago Mata
Thiago Mata

Reputation: 2959

Using the Gremlin language only, you can do it using the unfold method. This may be useful if you need to run your query by the REST API.

g.V()
  .hasLabel("airport")
  .values("region")
  .groupCount()
  .unfold()
  .order()
  .by(values)

Upvotes: 0

stephen mallette
stephen mallette

Reputation: 46206

You need to order the values with local scoping:

g.V().hasLabel("airport").
  groupCount().
    by("region").
  order(local).
    by(values, Order.decr)

With local scoping you order within the current traverser (i.e. order the contents of each Map in the traversal).

  @Test
  public void testSortedGroupCount() throws Exception {
    Graph graph = getAirRoutes();
    GraphTraversalSource g = graph.traversal();
    Map<Object, Long> counts = g.V().hasLabel("airport").groupCount()
        .by("region").order(Scope.local).by(Column.values,Order.decr).next();
    // https://stackoverflow.com/a/49361250/1497139
    assertEquals(1473, counts.size());
    assertEquals("LinkedHashMap",counts.getClass().getSimpleName());
    debug=true;
    if (debug)
      for (Object key : counts.keySet()) {
        System.out.println(String.format("%s=%3d", key, counts.get(key)));
      }

  }

will then show:

US-AK=149
AU-QLD= 50
CA-ON= 46
CA-QC= 44
PF-U-A= 30
US-CA= 29

Upvotes: 7

Related Questions