问题
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.
回答1:
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
回答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.
来源:https://stackoverflow.com/questions/61664660/java-graphtraversal-output-gremlin-query