paginationgremlinamazon-neptunetinkerpop3gremlin-java

UnsupportedOperationException in gremlin "by step with range" for more than one element


g.V().hasLabel('employee').fold().as("emp", "count")
.select("emp", "count")
.by(range(local, 0, 2).elementMap())
.by(count(local));

The above query is working fine when the range interval is 1 (OR) total number of return vertex is 1.

If it has more than one vertex or the range interval is increased, getting the UnsupportedOperationException exception. How to solve?

The same query works without elementMap(), however, it's needed in application just vertex id is not helpful


Solution

  • The UnsupportedOperation exception is because you are creating essentially a list of vertices when the range yields more than one result. The full error is actually going to be something like:

    {
      "requestId": "c98008d3-104e-4972-9d9c-c78186646cba",
      "code": "UnsupportedOperationException",
      "detailedMessage": "java.util.LinkedList cannot be cast to org.apache.tinkerpop.gremlin.structure.Element"
    }
    

    Which gives us a clue. The query expected an element, like a vertex or an edge but instead got a list of vertices.

    When the range is from 0 to 2, the result will be of the form:

    {'emp': [v[3741], v[3742]], 'count': 7}```
    

    You will need to do something like

     by(range(local, 0, 2).unfold().elementMap().fold())
    

    for the query to work correctly.

    Note that the query can be rewritten using project:

    g.V().hasLabel('employee').fold().
      project("emp", "count").
        by(range(local, 0, 2).unfold().elementMap().fold()).
        by(count(local))