Java

Updated at:

This topic describes how to use a Java programming environment to connect to and manage Graph Database (GDB) instances. This is a widely used method of managing GDB instances. After clients are connected to your GDB instances, the clients can provide services for a long period.

Prerequisites

The Graph Database (GDB) instance and the ECS instance must be in the same Virtual Private Cloud (VPC).

Install Maven

  1. Add a repository that contains the Maven package.

    wget http://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo\
    -O /etc/yum.repos.d/epel-apache-maven.repo
  2. Set the version number for the repository.

    sudo sed -i s/\$releasever/6/g /etc/yum.repos.d/epel-apache-maven.repo
  3. Download and install Maven.

    sudo yum install -y apache-maven

Install Java

  1. Install JDK 8.0.

    sudo yum install java-1.8.0-devel
  2. If multiple Java versions are installed on your ECS instance, you can set Java 8 as the default version.

    sudo /usr/sbin/alternatives --config java
    There are 4 programs which provide 'java'.
    Option    Command
    -----------------------------------------------
    *+ 1           java-1.8.0-openjdk.x86_64 (/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.191.b12-1.el7_6.x86_64/jre/bin/java)
     2           java-1.8.0-openjdk.x86_64 (/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.191.b12-0.el7_5.x86_64-debug/jre/bin/java)
     3           java-1.7.0-openjdk.x86_64 (/usr/lib/jvm/java-1.7.0-openjdk-1.7.0.191-2.6.15.4.el7_5.x86_64/jre/bin/java)
     4           /usr/lib/jvm/jre-1.6.0-openjdk.x86_64/bin/java

Write Java client code

  1. Create the gdb-gremlin-test directory.

    mkdir gdb-gremlin-test;
    cd gdb-gremlin-test
  2. Create a pom.xml file and add the following content.

    <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 http://maven.apache.org/maven-v4_0_0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.gdb.alibaba</groupId>
      <artifactId>GdbGremlinExample</artifactId>
      <packaging>jar</packaging>
      <version>1.0-SNAPSHOT</version>
      <name>GdbGremlinExample</name>
      <url>http://maven.apache.org</url>
      <dependencies>
        <dependency>
           <groupId>org.apache.tinkerpop</groupId>
           <artifactId>gremlin-driver</artifactId>
           <version>3.4.3</version>
        </dependency>
      </dependencies>
      <build>
         <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.0.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.3</version>
                <configuration>
                    <mainClass>com.gdb.alibaba.Test</mainClass>
                    <complianceLevel>1.8</complianceLevel>
                </configuration>
            </plugin>
        </plugins>
      </build>
    </project>
  3. Create a directory and a file.

    mkdir -p src/main/java/com/gdb/alibaba/;
    touch src/main/java/com/gdb/alibaba/Test.java
  4. Write a test program.

    package com.gdb.alibaba;
    import org.apache.tinkerpop.gremlin.driver.Cluster;
    import org.apache.tinkerpop.gremlin.driver.Client;
    import org.apache.tinkerpop.gremlin.driver.Result;
    import org.apache.tinkerpop.gremlin.driver.ResultSet;
    import java.util.List;
    import java.util.Map;
    import java.util.HashMap;
    import java.io.File;
    public class Test
    {
        public static void main( String[] args )
        {
          try {
            if(args.length != 1) {
                System.out.println("gdb-remote.yaml path needed");
                return;
            }
            String yaml = args[0];
    
            // 1. Initialize the client. The client includes a connection pool and is thread-safe to support concurrent multi-threaded operations.
            Cluster cluster = Cluster.build(new File(yaml)).create();
            Client client = cluster.connect().init();
    
            // 2. Send Gremlin requests to the GDB server. Customize the requests based on your business logic.
            String dsl = "g.addV(yourlabel).property(propertyKey, propertyValue)";
            Map<String,Object> parameters = new HashMap<>(3);
            parameters.put("yourlabel","area");
            parameters.put("propertyKey","wherence");
            parameters.put("propertyValue","shenzheng");
            ResultSet results = client.submit(dsl,parameters);
            List<Result> result = results.all().join();
            result.forEach(p -> System.out.println(p.getObject()));
    
            // 3. Close the client and cluster to release resources after all Gremlin requests are complete.
            client.close();
            cluster.close();
          } catch (Exception e) {
            System.out.println(e.getMessage());
          }
      }
    }
    Note

    The software development kit (SDK) client includes a connection pool and supports multi-threaded concurrency. For your application, you can maintain a single global client instead of creating a new client for each request. Close the client only after all Graph Database requests are complete or when the application exits.

  5. Create a gdb-remote.yaml file. This is the configuration file used to establish a connection between the Java client and the Graph Database instance. For more information about other configurations, see SDK usage.

    hosts: [ ${gdbHost} ]
    port: 8182
    username: ${username}
    password: ${password}
    serializer: {
      className: org.apache.tinkerpop.gremlin.driver.ser.GraphBinaryMessageSerializerV1,
      config: { serializeResultToString: false }
    }

    The following table describes the parameters.

    Parameter

    Description

    ${gdbHost}

    The endpoint of the GDB instance, for example, gds-bp*******************.graphdb.rds.aliyuncs.com.

    ${username}

    The database account for GDB.

    ${password}

    The password that corresponds to the GDB database account.

  6. Go to the gdb-gremlin-test home directory to compile and run the Java program.

    mvn compile exec:java  -Dexec.args="/home/apache-tinkerpop-gmlin-console-3.4.0/conf/gdb-remote.yaml"

    The following result is returned:

    v[ba8f60b7-0786-4014-a4e2-451f09b79878]

Explicitly configure the client

If you want to manage configurations centrally instead of using a separate GDB configuration file, you can explicitly configure the client using the API that the driver provides. The following sample code shows an example:

// 1. Initialize the client. The client includes a connection pool and is thread-safe to support concurrent multi-threaded operations.
// Cluster cluster = Cluster.build(new File(yaml)).create();
// Client client = cluster.connect().init();
// Explicitly configure the client.
Cluster.build(${gdbHost}).port(${gdbPort}).
    serializer(Serializers.GRAPHBINARY_V1D0).
    maxConnectionPoolSize(8).
    minConnectionPoolSize(8).
    maxContentLength(65536).
    credentials(${username}, ${password}).create();

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

The parameters in the example are as follows:

Parameter

Description

${gdbHost}

The endpoint of the GDB instance, for example, gds-bp*******************.graphdb.rds.aliyuncs.com.

${gdbPort}

The port number of the GDB instance, for example, 8182.

${username}

The database account for GDB.

${password}

The password that corresponds to the GDB database account.

The following are additional common client configuration parameters:

Parameter

Default value

Description

connectionPool.maxContentLength

65536

The maximum size of a message in bytes. If a request returns a large volume of data, increase the value of this parameter. Otherwise, an error may occur that indicates the result cannot be processed.

connectionPool.maxSize

8

The maximum number of connections in the connection pool. If you have a high number of concurrent requests, increase this value.

connectionPool.minSize

2

The minimum number of connections in the connection pool.

More sample DSL commands

The preceding examples in this topic use a parameterized method to add vertices with the dsl g.addV(yourlabel).property(propertyKey, propertyValue) statement and the map parameter. The following section provides more domain-specific language (DSL) examples that use the vertex and edge structures of a graph. For more information about the vertex and edge structures of a graph, see the TinkerPop documentation.

Note

The following DSL example requires refactoring to use parameterized invocation. For this demonstration, you can use a hard-coded approach:

// Hard-coded DSL:
dsl = "user_defined_dsl";
// For example: g.addV('sand131_id_5_99').property(id,'sand131_id_5_99').property('name','sand131_name_5_99')
ResultSet results = client.submit(dsl);
              |
              |
              v
// Parameterized script:
String dsl ="g.addV(vertex).property(id,vertex).property('name',vertex)";
Map<String, Object> parameters = new HashMap<>();
parameters.put("vertex","sand131_id_5_99"); // Specify the vertex parameter in the DSL statement.
ResultSet results = client.submit(dsl, parameters,timeoutInMillis);

The example steps are as follows:

  1. Delete vertices and edges with a specified label.

    g.E().hasLabel('gdb_sample_knows').drop()
    g.E().hasLabel('gdb_sample_created').drop()
    g.V().hasLabel('gdb_sample_person').drop()
    g.V().hasLabel('gdb_sample_software').drop()
  2. Add vertices and set their ID and property.

    g.addV('gdb_sample_person').property(id, 'gdb_sample_marko').property('age', 28).property('name', 'marko')
    g.addV('gdb_sample_person').property(id, 'gdb_sample_vadas').property('age', 27).property('name', 'vadas')
    g.addV('gdb_sample_person').property(id, 'gdb_sample_josh').property('age', 32).property('name', 'josh')
    g.addV('gdb_sample_person').property(id, 'gdb_sample_peter').property('age', 35).property('name', 'peter')
    g.addV('gdb_sample_software').property(id, 'gdb_sample_lop').property('lang', 'java').property('name', 'lop')
    g.addV('gdb_sample_software').property(id, 'gdb_sample_ripple').property('lang', 'java').property('name', 'ripple')
  3. Modify or add the age property.

    g.V('gdb_sample_marko').property('age', 29)
  4. Create a relationship and set the weight property.

    g.addE('gdb_sample_knows').from(V('gdb_sample_marko')).to(V('gdb_sample_vadas')).property('weight', 0.5f)
    g.addE('gdb_sample_knows').from(V('gdb_sample_marko')).to(V('gdb_sample_josh')).property('weight', 1.0f)
    g.addE('gdb_sample_created').from(V('gdb_sample_marko')).to(V('gdb_sample_lop')).property('weight', 0.4f)
    g.addE('gdb_sample_created').from(V('gdb_sample_josh')).to(V('gdb_sample_lop')).property('weight', 0.4f)
    g.addE('gdb_sample_created').from(V('gdb_sample_josh')).to(V('gdb_sample_ripple')).property('weight', 1.0f)
    g.addE('gdb_sample_created').from(V('gdb_sample_peter')).to(V('gdb_sample_lop')).property('weight', 0.2f)
  5. Query the number of all vertices or vertices with a specified label.

    g.V().count()
    g.V().hasLabel('gdb_sample_person').count()
  6. Query for vertices that represent people older than 29, sorted by `name` in descending order.

    g.V().hasLabel('gdb_sample_person').has('age', gt(29))
    g.V().hasLabel('gdb_sample_person').order().by('name', decr)
  7. Run an associated query, such as retrieving the people that Marko knows and the software created by the people that Marko knows.

    g.V('gdb_sample_marko').outE('gdb_sample_knows').inV().hasLabel('gdb_sample_person')
    g.V('gdb_sample_marko').outE('gdb_sample_knows').inV().hasLabel('gdb_sample_person').outE('gdb_sample_created').inV().hasLabel('gdb_sample_software')
  8. Delete relationships and vertices.

    g.V('gdb_sample_marko').outE('gdb_sample_knows').where(inV().has(id, 'gdb_sample_josh')).drop()
    g.V('gdb_sample_marko').drop()

You can also perform other tests. For more information about Gremlin query statements, see the TinkerPop Gremlin documentation.