简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM