3

How to output Gremlin query from a Java GraphTraversal object? The default output (graphTraversal.toString()) looks like [HasStep([~label.eq(brand), name.eq(Nike), status.within([VALID])])] which is not easy to read.

coderz
  • 4,847
  • 11
  • 47
  • 70

2 Answers2

6

Gremlin provides the GroovyTranslator class to help with that. Here is an example.

// Simple traversal we can use for testing a few things
Traversal t = 
  g.V().has("airport","region","US-TX").
        local(values("code","city").
        fold());


// Generate the text form of the query from a Traversal
String query;
query = GroovyTranslator.of("g").
        translate(t.asAdmin().getBytecode());

System.out.println("\nResults from GroovyTranslator on a traversal");
System.out.println(query);

This is taken from a set of examples located here: https://github.com/krlawrence/graph/blob/master/sample-code/RemoteWriteText.java

Kelvin Lawrence
  • 14,674
  • 2
  • 16
  • 38
2

You can use getByteCode() method on a DefaultGraphTraversal to get output gremlin query.

For example, consider the following graph

 Graph graph = TinkerGraph.open();
        Vertex a = graph.addVertex(label, "person", "name", "Alex", "Age", "23");
        Vertex b = graph.addVertex(label, "person", "name", "Jennifer", "Age", "20");
        Vertex c = graph.addVertex(label, "person", "name", "Sophia", "Age", "22");
        a.addEdge("friends_with", b);
        a.addEdge("friends_with", c);

Get a graph Traversal as following:

        GraphTraversalSource gts = graph.traversal();
        GraphTraversal graphTraversal = 
        gts.V().has("name","Alex").outE("friends_with").inV().has("age", P.lt(20));

Now you can get your traversal as a String as:

 String traversalAsString = graphTraversal.asAdmin().getBytecode().toString();

It gives you output as:

[[], [V(), has(name, Alex), outE(friends_with), inV(), has(age, lt(20))]]

It is much more readable, almost like the one you have provided as the query. You can now modify/parse the string to get the actual query if you want like replacing [,], adding joining them with . like in actual query.

CodeTalker
  • 1,683
  • 2
  • 21
  • 31
  • While somewhat useful, there are no out of the box tools available that process that "toString" bytecode format. The `GroovyTranslator` approach will give you an actual Gremlin query back as a string. That query could then be pasted as-is into the Gremlin Console etc. – Kelvin Lawrence Feb 24 '23 at 16:56