Table of Contents
JanusGraph can be queried from a Java application with Apache TinkerPop’s Gremlin Driver. While it is possible to embed JanusGraph as a library inside a Java application and then directly connect to the backend, this section assumes that the application connects to JanusGraph Server. For information on how to embed JanusGraph, see the JanusGraph Examples projects.
This section only covers how applications can connect to JanusGraph Server. Refer to Chapter 6, Gremlin Query Language for an introduction to Gremlin and pointers to further resources.
To get started with JanusGraph in Java:
-
Create an application with Maven:
mvn archetype:generate -DgroupId=com.mycompany.project -DartifactId=gremlin-example -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
-
Add dependencies on
janusgraph-core
andgremlin-driver
to thepom.xml
file:... <dependencies> <dependency> <groupId>org.janusgraph</groupId> <artifactId>janusgraph-core</artifactId> <version>0.3.2</version> </dependency> <dependency> <groupId>org.apache.tinkerpop</groupId> <artifactId>gremlin-driver</artifactId> <version>3.3.3</version> </dependency> ... </dependencies> ...
-
Add two configuration files,
conf/remote-graph.properties
andconf/remote-objects.yaml
:conf/remote-graph.properties.
gremlin.remote.remoteConnectionClass=org.apache.tinkerpop.gremlin.driver.remote.DriverRemoteConnection gremlin.remote.driver.clusterFile=conf/remote-objects.yaml gremlin.remote.driver.sourceName=g
conf/remote-objects.yaml.
hosts: [localhost] port: 8182 serializer: { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV1d0, config: { ioRegistries: [org.janusgraph.graphdb.tinkerpop.JanusGraphIoRegistry] }}
-
Create a
GraphTraversalSource
which is the basis for all Gremlin traversals:Graph graph = EmptyGraph.instance(); GraphTraversalSource g = graph.traversal().withRemote("conf/remote-graph.properties"); // Reuse 'g' across the application // and close it on shut-down to close open connections with g.close()
-
Execute a simple traversal:
Object herculesAge = g.V().has("name", "hercules").values("age").next(); System.out.println("Hercules is " + herculesAge + " years old.");
next()
is a terminal step that submits the traversal to the Gremlin Server and returns a single result. Other terminal steps can be found in TinkerPop’s reference documentation.
JanusGraph specific types and predicates can be used directly from a Java application through the dependency janusgraph-core
.