-
Notifications
You must be signed in to change notification settings - Fork 238
Using Gremlin through Java
One of the exciting developments that occurred in Java 1.6+ was the creation of a collection of interfaces that allow developers to tie other languages to the Java virtual machine (JSR 223). In this way, these languages, through a standard set of methods, can be used within any Java 1.6+ application. Thus, its possible to capitalize on the features of another language when building a Java application. For Java applications that make use of graphs, Gremlin is a prime candidate for inclusion.
The reference implementation of JSR 223 deployed with Java 1.6+ is Mozilla’s JavaScript implementation known as Rhino. Other popular implementations include Jython, JRuby, and Groovy. For an excellent reference to other implementations of JSR 223, please see https://scripting.dev.java.net.
Finally, you can learn more about JSR 223 from the articles below.
- O’Conner, J., Scripting for the Java Platform, July 2006.
- Wu, C., Build Your Own Language for Java, April 2006.
While its possible to use Gremlin via the GremlinEvaluator
class, it is not recommended. Gremlin instead provides two classes that should be communicated with directly when using the Gremlin virtual machine from within a Java application.
GremlinScriptEngine implements ScriptEngine
GremlinScriptEngineFactory implements ScriptEngineFactory
The common way in which to use Gremlin through these interfaces is as follows. First add a text file named javax.script.ScriptEngineFactory
to your META-INF/services
directory (ScriptEngineFactory
is a service provider). In that file, add the line com.tinkerpop.gremlin.GremlinScriptEngineFactory
. Now, the GremlinScriptEngineFactory
is available to the ScriptEngineManager
.
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("gremlin");
engine.getBindings(ScriptContext.ENGINE_SCOPE).put("$name", "gremlin");
engine.getBindings(ScriptContext.ENGINE_SCOPE).get("$name");
...
Iterable results = (Iterable) engine.eval("./outE/inV[@name=$name]");
String script = "$i := 0\n" +
"repeat 10\n" +
" $i := $i + 1\n" +
"end\n";
engine.eval(script)
engine.eval(new FileReader("script.grm"));
-
ENGINE_SCOPE: Engine scope variables/bindings are visible during the lifetime of a single
ScriptEngine
and a set of variables is maintained for each engine. This is equivalent to theGremlinEvaluator
’sVariableLibrary
. -
GLOBAL_SCOPE: Global scope variables/bindings are visible to all engines created by same
ScriptEngineManager
. This is aSimpleBindings
that allow variousScriptEngine
’s created from the same manager to communicate with one another through a “blackboard”. For example, global scope bindings in a Jython engine can be used by a Gremlin engine and vice versa.