Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Gremlin query as a String and execute it in java without submitting it to the GremlinServer

I have a Gremlin query in the String format (for example "g.V()"). I want to execute this String without submitting it to the GremlinServer.

I use the below dependency:

<dependency>
    <groupId>org.apache.tinkerpop</groupId>
    <artifactId>gremlin-driver</artifactId>
    <version>3.3.1</version>
</dependency>

Is there any way?

like image 396
Fariba Hashemi Avatar asked Jan 24 '26 13:01

Fariba Hashemi


2 Answers

You can execute Gremlin string directly in GremlinGroovyScriptEngine or through the GremlinExecutor (which just passes the string to the GremlinGroovyScriptEngine but has some additional features to it). Simple pass the Gremlin string to the appropriate eval() method and get back a result from that script evaluation. That's basically what Gremlin Server does internally.

You will likely need the gremlin-groovy dependency rather than gremlin-driver.

like image 155
stephen mallette Avatar answered Jan 27 '26 04:01

stephen mallette


Adding a 'complete' example based on stephen answer+comment:

public static void main(String[] args) throws ScriptException, ExecutionException, InterruptedException {
    Graph graph = TinkerGraph.open();
    Configuration c = graph.configuration();
    GraphTraversalSource g = graph.traversal();

    // Creating graph
    Vertex marko = g.addV("person").property("name","marko").property("age",29).next();
    Vertex lop = g.addV("software").property("name","lop").property("lang","java").next();
    g.addE("created").from(marko).to(lop).property("weight",0.6d).iterate();
    g.io("test.xml").write().iterate(); // saving to file

    //standard query
    GraphTraversal<Vertex, Map<Object, Object>> javaQueryResult = g.V().hasLabel("person").valueMap();

    // preparing GremlinExecutor
    ConcurrentBindings b = new ConcurrentBindings();
    b.putIfAbsent("g", g);

    GremlinExecutor ge = GremlinExecutor.build().evaluationTimeout(15000L).globalBindings(b).create();

    CompletableFuture<Object> evalResult = ge.eval("g.V().hasLabel('person').valueMap()");
    GraphTraversal actualResult = (GraphTraversal) evalResult.get();
}

Simple debugging app to check how results evaluated from string compare to standard queries.

Using maven dependencies tinkergraph-gremlin gremlin-core gremlin-groovy, version 3.4.6

like image 44
GriffoGoes Avatar answered Jan 27 '26 04:01

GriffoGoes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!