Gremlin Java

Updated at:

Lindorm Graph Engine is compatible with the Apache TinkerPop Gremlin protocol. You can submit Gremlin queries from Java applications by using the official gremlin-driver, with support for YAML-based or code-based connections, parameter binding, and timeout configuration.

Prerequisites

  • Lindorm Graph Engine has been activated and the whitelist has been configured.

  • The graph Schema has been initialized. If not, see Graph Schema Definition.

  • JDK 8+ and Maven 3.6+ have been installed locally.

Maven dependency

Add the gremlin-driver dependency to the project's pom.xml. Lindorm Graph Engine is compatible with TinkerPop 3.7 and later. We recommend using 3.8.x:

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

Connection methods

Lindorm Graph Engine supports two connection methods: loading from a YAML configuration file, or constructing a Cluster object directly in code. For production environments, use a YAML file to decouple connection parameters from the code.

Method 1: YAML configuration

Create remote.yaml:

hosts: [instance-name-proxy-graph-vpc.lindorm.aliyuncs.com]
port: 16032
username: account
password: password
path: /gremlin/subgraph-name
connectionPool: {
  maxSize: 16,
  minSize: 16,
  maxInProcessPerConnection: 4,
  maxContentLength: ${yourExpectedSize}
}
serializer: { className: org.apache.tinkerpop.gremlin.util.ser.GraphBinaryMessageSerializerV1, config: { serializeResultToString: false }}

Main field descriptions:

  • ${yourExpectedSize}: Defaults to 65536. Increase this value if your result set exceeds the default frame length and triggers a Max frame length of 65536 has been exceeded  error.

  • maxSize and minSize: The client connection pool supports multi-threaded concurrent access. Set both parameters to the same value, equal to or greater than the number of client threads. This helps avoid Timed out while waiting for an available host  errors.

  • Serialization protocol (use the GraphBinaryMessageSerializerV1 serialization protocol whenever possible):

    • GraphBinaryMessageSerializerV1: Returns ReferenceVertex and ReferenceEdge without properties during serialization. Offers better performance.

    • GraphSONMessageSerializerV3d0: Returns DetachedVertex and DetachedEdge with all properties during serialization. This incurs significant overhead when vertices have many properties.

Load this configuration in Java code and create a Cluster:

import org.apache.tinkerpop.gremlin.driver.Client;
import org.apache.tinkerpop.gremlin.driver.Cluster;

Cluster cluster = Cluster.open("config/remote.yaml");
Client client = cluster.connect();
client.init();

// ... execute operations ...

client.close();
cluster.close();

Method 2: Construct Cluster in code

import org.apache.tinkerpop.gremlin.driver.Client;
import org.apache.tinkerpop.gremlin.driver.Cluster;

Cluster cluster = Cluster.build("ld-xx-proxy-graph-pub.lindorm.aliyuncs.com")
        .port(16032)
        .serializer(Serializers.GRAPHBINARY_V1)
        .maxConnectionPoolSize(32)
        .minConnectionPoolSize(32)
        .credentials("root", "xx")
        .path("/gremlin/default")
        .create();
Client client = cluster.connect();
client.init();

// ... execute operations ...

client.close();
cluster.close();

Parameter binding and timeout settings

Use RequestOptions.addParameter to bind variables in query statements. This avoids string concatenation and improves security.

import org.apache.tinkerpop.gremlin.driver.RequestOptions;
import org.apache.tinkerpop.gremlin.driver.Result;
import org.apache.tinkerpop.gremlin.driver.ResultSet;

String dsl = "g.V(G___id).hasLabel(G___label)";
RequestOptions.Builder options = RequestOptions.build().timeout(30000);
options.addParameter("G___id", "marko");
options.addParameter("G___label", "person");

ResultSet resultSet = client.submit(dsl, options.create());
List<Result> results = resultSet.all().join();
for (Result r : results) {
    System.out.println(r.getObject());
}
// Perform client close and other operations
Note

For bound variable names, we recommend the format of the G___ prefix plus the field name (such as G___id and G___label). You can reference the variable name directly in the DSL without quotation marks.

Complete example

The following example demonstrates how to create a standalone Maven project, connect to Lindorm Graph Engine, and execute Gremlin queries. It includes four steps: initializing the project, configuring dependencies, writing the main class, and compiling and running.

Initialize the project directory

mkdir lindorm-graph-java-demo
cd lindorm-graph-java-demo
mkdir -p config
mkdir -p src/main/java/com/aliyun/lindorm/demo

Create config/remote.yaml

hosts: [instance-name-proxy-graph-vpc.lindorm.aliyuncs.com]
port: 16032
username: account
password: password
path: /gremlin/subgraph-name
connectionPool: {
  maxSize: 16,
  minSize: 16,
  maxInProcessPerConnection: 4,
  maxContentLength: ${yourExpectedSize}
}
serializer: { className: org.apache.tinkerpop.gremlin.util.ser.GraphBinaryMessageSerializerV1, config: { serializeResultToString: false }}

Create pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.aliyun.lindorm</groupId>
    <artifactId>lindorm-graph-java-demo</artifactId>
    <version>1.0.0</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <slf4j.version>2.0.17</slf4j.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>jcl-over-slf4j</artifactId>
                <version>${slf4j.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.apache.tinkerpop</groupId>
            <artifactId>gremlin-driver</artifactId>
            <version>3.8.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.13.0</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.5.3</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <createDependencyReducedPom>false</createDependencyReducedPom>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.aliyun.lindorm.demo.LindormGraphExampleDemo</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

Write LindormGraphExampleDemo.java

Create LindormGraphExampleDemo.java in the src/main/java/com/example/ directory:

package com.aliyun.lindorm.demo;

import org.apache.tinkerpop.gremlin.driver.Client;
import org.apache.tinkerpop.gremlin.driver.Cluster;
import org.apache.tinkerpop.gremlin.driver.Result;
import org.apache.tinkerpop.gremlin.driver.ResultSet;
import org.apache.tinkerpop.gremlin.driver.RequestOptions;
import org.apache.tinkerpop.gremlin.util.ser.Serializers;
import org.yaml.snakeyaml.Yaml;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * Graph database Java client example (corresponds to example_client.py)
 * 1. Call /schema/mgmt/apply to initialize the Schema (including vector properties)
 * 2. Insert vertices (person with 128-dim vector, software) and edges (knows, created)
 * 3. Query vertices, traverse the graph, and perform vector search
 */
public class LindormGraphExampleDemo {

    private static final int REQUEST_TIMEOUT_MS = 30000;
    private static final int VECTOR_DIM = 128;
    private static final Random RANDOM = new Random();

    // ========== Schema JSON ==========
    // If you do not use vectors, remove the embedding vector column
    private static final String SCHEMA_JSON =
            "{\"vertexLabels\":["
            + "{\"label\":\"person\",\"properties\":["
            +   "{\"name\":\"name\",\"dataType\":\"STRING\"},"
            +   "{\"name\":\"age\",\"dataType\":\"INT\"},"
            +   "{\"name\":\"city\",\"dataType\":\"STRING\"},"
            +   "{\"name\":\"embedding\",\"dataType\":\"VECTOR_FLOAT\","
            +     "\"vectorMeta\":{\"dimension\":128,\"distanceMethod\":\"EUCLIDEAN\","
            +     "\"indexType\":\"HNSW\",\"indexParams\":{\"M\":\"24\",\"EF_CONSTRUCT\":\"200\"}}}"
            + "]},"
            + "{\"label\":\"software\",\"properties\":["
            +   "{\"name\":\"name\",\"dataType\":\"STRING\"},"
            +   "{\"name\":\"lang\",\"dataType\":\"STRING\"},"
            +   "{\"name\":\"price\",\"dataType\":\"INT\"}"
            + "]}"
            + "],\"edgeLabels\":["
            + "{\"label\":\"knows\",\"properties\":["
            +   "{\"name\":\"date\",\"dataType\":\"STRING\"},"
            +   "{\"name\":\"weight\",\"dataType\":\"DOUBLE\"}"
            + "]},"
            + "{\"label\":\"created\",\"properties\":["
            +   "{\"name\":\"date\",\"dataType\":\"STRING\"},"
            +   "{\"name\":\"weight\",\"dataType\":\"DOUBLE\"}"
            + "]}"
            + "],\"connections\":["
            + "{\"edgeLabel\":\"knows\",\"outVertex\":\"person\",\"inVertex\":\"person\"},"
            + "{\"edgeLabel\":\"created\",\"outVertex\":\"person\",\"inVertex\":\"software\"}"
            + "]}";

    // ========== Gremlin DSL ==========
    private static final String ADD_PERSON_DSL =
            "g.addV(G___label).property(id, G___id)"
            + ".property('name', G___name)"
            + ".property('age', G___age)"
            + ".property('city', G___city)"
            + ".property('embedding', G___embedding)";

    private static final String ADD_SOFTWARE_DSL =
            "g.addV(G___label).property(id, G___id)"
            + ".property('name', G___name)"
            + ".property('lang', G___lang)"
            + ".property('price', G___price)";

    private static final String ADD_EDGE_DSL =
            "g.V(G___fromId).hasLabel(G___fromLabel).addE(G___edgeLabel).to(__.V(G___toId).hasLabel(G___toLabel))"
            + ".property('date', G___date)"
            + ".property('weight', G___weight)";

    private static final String QUERY_VERTEX_DSL =
            "g.V(G___id).hasLabel(G___label).valueMap(true)";

    private static final String QUERY_NEIGHBORS_DSL =
            "g.V(G___id).hasLabel(G___label).out(G___edgeLabel).valueMap(true)";

    private static final String VECTOR_SEARCH_DSL =
            "g.V().hasLabel(G___label).hasVector(G___prop, G___vector, G___topK).valueMap(true)";

    // ========== main ==========

    public static void main(String[] args) throws Exception {
        String yamlPath = args.length > 0 ? args[0] : "config/remote.yaml";
        Config config = loadConfig(yamlPath);

        // 1. Initialize Schema
        printSection("1. Initialize Schema");
        applySchema(config);

        // 2. Create Gremlin client
        Cluster cluster = null;

        Client client = null;
        try {
            // The client contains a connection pool, is thread-safe, and supports multi-threaded concurrency
            cluster = Cluster.build(new File(yamlPath)).create();
//            cluster = Cluster.build("ld-xx-proxy-graph-pub.lindorm.aliyuncs.com")
//                    .port(16032)
//                    .serializer(Serializers.GRAPHBINARY_V1)
//                    .maxConnectionPoolSize(32)
//                    .minConnectionPoolSize(32)
//                    .credentials("root", "xx")
//                    .path("/gremlin/default")
//                    .create();

            client = cluster.connect().init();

            // 3. Insert data
            // Wait for the Schema (including the vector index) to be built on the server side to avoid the index not being ready during subsequent insert/search
            Thread.sleep(10000);

            printSection("2. Insert vertices and edges");

            System.out.println("\n--- Add person vertices ---");
            addPersons(client);

            System.out.println("\n--- Add software vertices ---");
            addSoftwares(client);

            System.out.println("\n--- Add edges ---");
            addEdges(client);

            // 4. Query
            printSection("3. Query");

            System.out.println("\n--- Query vertex marko ---");
            queryVertex(client, "marko", "person");

            System.out.println("\n--- People that marko knows ---");
            queryNeighbors(client, "marko", "person", "knows");

            System.out.println("\n--- Software created by marko ---");
            queryNeighbors(client, "marko", "person", "created");

            System.out.println("\n--- Vector search top 3 ---");
            queryVectorSearch(client, "person", "embedding", 3);

        } finally {
            if (client != null) client.close();
            if (cluster != null) cluster.close();
        }

        System.out.println("\nDone!");
    }

    // ========== 1. Schema initialization ==========

    private static void applySchema(Config config) throws Exception {
        String url = config.schemaBaseUrl()
                + "/schema/mgmt/apply?db=" + URLEncoder.encode(config.dbName, "UTF-8");
        String result = httpPost(url, SCHEMA_JSON, config);
        System.out.println("Schema initialization: " + result);
    }

    // ========== 2. Insert data ==========

    private static void addPersons(Client client) {
        String[][] persons = {
            {"marko", "marko", "29", "Beijing"},
            {"vadas", "vadas", "27", "Hongkong"},
            {"josh",  "josh",  "32", "Beijing"},
            {"peter", "peter", "35", "Shanghai"},
        };

        for (String[] p : persons) {
            Map<String, Object> bindings = new HashMap<>();
            bindings.put("G___label", "person");
            bindings.put("G___id", p[0]);
            bindings.put("G___name", p[1]);
            bindings.put("G___age", Integer.parseInt(p[2]));
            bindings.put("G___city", p[3]);
            bindings.put("G___embedding", randomVector(VECTOR_DIM));
            List<Result> results = execute(client, ADD_PERSON_DSL, bindings);
            System.out.println("Add vertex: " + p[0] + " -> " + results);
        }
    }

    private static void addSoftwares(Client client) {
        String[][] softwares = {
            {"lop",    "lop",    "java", "328"},
            {"ripple", "ripple", "java", "199"},
        };

        for (String[] s : softwares) {
            Map<String, Object> bindings = new HashMap<>();
            bindings.put("G___label", "software");
            bindings.put("G___id", s[0]);
            bindings.put("G___name", s[1]);
            bindings.put("G___lang", s[2]);
            bindings.put("G___price", Integer.parseInt(s[3]));
            List<Result> results = execute(client, ADD_SOFTWARE_DSL, bindings);
            System.out.println("Add vertex: " + s[0] + " -> " + results);
        }
    }

    private static void addEdges(Client client) {
        // {from, fromLabel, to, toLabel, edgeLabel, date, weight}
        String[][] edges = {
            {"marko", "person", "vadas",  "person",   "knows",   "20160110", "0.5"},
            {"marko", "person", "josh",   "person",   "knows",   "20130220", "1.0"},
            {"marko", "person", "lop",    "software", "created", "20171210", "0.4"},
            {"josh",  "person", "lop",    "software", "created", "20091111", "0.4"},
            {"josh",  "person", "ripple", "software", "created", "20171210", "1.0"},
            {"peter", "person", "lop",    "software", "created", "20170324", "0.2"},
        };

        for (String[] e : edges) {
            Map<String, Object> bindings = new HashMap<>();
            bindings.put("G___fromId", e[0]);
            bindings.put("G___fromLabel", e[1]);
            bindings.put("G___toId", e[2]);
            bindings.put("G___toLabel", e[3]);
            bindings.put("G___edgeLabel", e[4]);
            bindings.put("G___date", e[5]);
            bindings.put("G___weight", Double.parseDouble(e[6]));
            List<Result> results = execute(client, ADD_EDGE_DSL, bindings);
            System.out.println("Add edge: " + e[0] + " -[" + e[4] + "]-> " + e[2] + " -> " + results);
        }
    }

    // ========== 3. Query ==========

    private static void queryVertex(Client client, String vertexId, String label) {
        Map<String, Object> bindings = new HashMap<>();
        bindings.put("G___id", vertexId);
        bindings.put("G___label", label);
        List<Result> results = execute(client, QUERY_VERTEX_DSL, bindings);
        for (Result r : results) {
            System.out.println(r.getObject());
        }
    }

    private static void queryNeighbors(Client client, String vertexId, String label, String edgeLabel) {
        Map<String, Object> bindings = new HashMap<>();
        bindings.put("G___id", vertexId);
        bindings.put("G___label", label);
        bindings.put("G___edgeLabel", edgeLabel);
        List<Result> results = execute(client, QUERY_NEIGHBORS_DSL, bindings);
        for (Result r : results) {
            System.out.println(r.getObject());
        }
    }

    private static void queryVectorSearch(Client client, String label, String prop, int topK) {
        List<Float> queryVector = randomVector(VECTOR_DIM);
        Map<String, Object> bindings = new HashMap<>();
        bindings.put("G___label", label);
        bindings.put("G___prop", prop);
        bindings.put("G___vector", queryVector);
        bindings.put("G___topK", topK);
        List<Result> results = execute(client, VECTOR_SEARCH_DSL, bindings);
        for (Result r : results) {
            System.out.println(r.getObject());
        }
    }

    // ========== Utility methods ==========

    /** Execute a Gremlin DSL, passing bindings parameters via RequestOptions. */
    private static List<Result> execute(Client client, String dsl, Map<String, Object> bindings) {
        RequestOptions.Builder options = RequestOptions.build().timeout(REQUEST_TIMEOUT_MS);
        for (Map.Entry<String, Object> entry : bindings.entrySet()) {
            options.addParameter(entry.getKey(), entry.getValue());
        }
        ResultSet resultSet = client.submit(dsl, options.create());
        return resultSet.all().join();
    }

    /** Generate a random float vector. */
    private static List<Float> randomVector(int dim) {
        List<Float> vec = new ArrayList<>(dim);
        for (int i = 0; i < dim; i++) {
            vec.add(Math.round((RANDOM.nextFloat() * 2 - 1) * 1000000f) / 1000000f);
        }
        return vec;
    }

    /** Send a JSON POST request with Basic Auth. */
    private static String httpPost(String urlValue, String jsonBody, Config config) throws Exception {
        HttpURLConnection conn = (HttpURLConnection) new URL(urlValue).openConnection();
        conn.setRequestMethod("POST");
        setBasicAuth(conn, config);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setConnectTimeout(10000);
        conn.setReadTimeout(30000);
        conn.setDoOutput(true);
        try (OutputStream out = conn.getOutputStream()) {
            out.write(jsonBody.getBytes(StandardCharsets.UTF_8));
        }
        int code = conn.getResponseCode();
        InputStream input = code >= 400 ? conn.getErrorStream() : conn.getInputStream();
        if (input == null) {
            return "HTTP " + code;
        }
        StringBuilder body = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                body.append(line);
            }
        }
        return "HTTP " + code + ": " + body;
    }

    /** Set the HTTP Basic Auth request header. */
    private static void setBasicAuth(HttpURLConnection conn, Config config) {
        conn.setRequestProperty("Authorization", "Basic " + Base64.getEncoder()
                .encodeToString((config.username + ":" + config.password).getBytes(StandardCharsets.UTF_8)));
    }

    /** Load the connection configuration from a Gremlin remote.yaml file. */
    private static Config loadConfig(String path) throws Exception {
        Map<?, ?> yaml;
        try (InputStream in = new FileInputStream(path)) {
            yaml = (Map<?, ?>) new Yaml().load(in);
        }
        Config config = new Config();
        config.remoteYamlPath = path;
        if (yaml.get("hosts") != null) {
            Object hosts = yaml.get("hosts");
            config.host = hosts instanceof List && !((List<?>) hosts).isEmpty()
                    ? String.valueOf(((List<?>) hosts).get(0))
                    : String.valueOf(hosts);
        }
        if (yaml.get("port") != null) {
            config.gremlinPort = Integer.parseInt(String.valueOf(yaml.get("port")));
        }
        if (yaml.get("username") != null) {
            config.username = String.valueOf(yaml.get("username"));
        }
        if (yaml.get("password") != null) {
            config.password = String.valueOf(yaml.get("password"));
        }
        if (yaml.get("path") != null) {
            String value = String.valueOf(yaml.get("path"));
            config.dbName = value.substring(value.lastIndexOf('/') + 1);
        }
        return config;
    }

    private static void printSection(String title) {
        String line = new String(new char[50]).replace('\0', '=');
        System.out.println("\n" + line);
        System.out.println(title);
        System.out.println(line);
    }

    /** Runtime configuration. */
    private static class Config {
        String remoteYamlPath;
        String host = "127.0.0.1";
        int gremlinPort = 8182;
        String dbName = "default";
        String username = "admin";
        String password = "admin";

        String schemaBaseUrl() {
            return "http://" + host + ":" + gremlinPort;
        }
    }
}

Compile and run

Run the following commands in the project root directory to package and run:

mvn clean package -DskipTests
java -jar target/lindorm-graph-java-demo-1.0.0.jar config/remote.yaml