coderz
coderz

Reputation: 4999

Java GraphTraversal output Gremlin query

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.

Upvotes: 3

Views: 1498

Answers (2)

CodeTalker
CodeTalker

Reputation: 1791

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.

Upvotes: 2

Kelvin Lawrence
Kelvin Lawrence

Reputation: 14391

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

Upvotes: 5

Related Questions