Help Center/ Graph Engine Service/ devg/ Using Cypher JDBC Driver to Access GES
Updated on 2022-11-14 GMT+08:00

Using Cypher JDBC Driver to Access GES

Introduction

The Cypher JDBC Driver is designed for GES. It is developed based on Neo4j JDBC Driver and provides a method of using JDBC to access GES and perform cypher queries.

The driver greatly reduces the CPU and memory usage for returning a large amount of data requested by high-concurrent cypher queries to avoid JVM caching of a complete request body. The driver parses a response body into streaming data instead obtaining an entire body and then parsing it.

Configuring Dependencies

Import the project and configure the Maven project parameters. Add the following dependency to the POM file:

<dependency>
      <groupId>com.huawei.ges</groupId>
      <artifactId>cypher-jdbc-driver</artifactId>
      <version>1.1.0</version>
 </dependency>

Parameters

Table 1 getConnection parameters

Type

Description

url

URL of the GES Cypher API. This is the first parameter of DriverManager.getConnection. Prefix the value with jdbc:ges:http(s) so that the JDBC driver can identify the URL.

prop

Properties object, including configurations required for connecting to GES APIs. For details, see Table 2.

Table 2 Properties parameters

Type

Description

X-Auth-Token

Token obtained through IAM authentication.

parse-json

Whether to convert data to vertices and edges. false (default value): Vertices and edges in the return body are in map format. true: Vertices and edges are returned in GesElement format.

Example

package org.example;
 
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
 
public class App 
{
    static String ip = "${ip}";
    static int port = 80;
    static String projectId = "${projectId}";
    static String graphName = "${graphName}";
    static String token = "${x_auth_token}";
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Class.forName("com.huawei.ges.jdbc.Driver").newInstance();
        String url = "jdbc:ges:http://{{graph_ip}}:{{graph_port}}/ges/v1.0/{{project_id}}/graphs/{{graph_name}}/action?action_id=execute-cypher-query";
        url = url.replace("{{graph_ip}}", ip).replace("{{graph_port}}",port + "").replace("{{project_id}}", projectId).replace("{{graph_name}}", graphName);
        Properties prop = new Properties();
        prop.setProperty("X-Auth-Token", token);
        prop.setProperty("deserializer-type","lazy");
        prop.setProperty("parse-json","true");
        prop.setProperty("limit","10000");
        try(Connection conn = DriverManager.getConnection(url,prop)){
            String query = "match (m) return m limit 1000";
            try(PreparedStatement stmt = conn.prepareStatement(query)){
                try(ResultSet rs = stmt.executeQuery()){
                    Object o = null;
                    while(rs.next()) {
                        o = rs.getObject("m");
                        processVertex(o);
                    }
                }
            }
        } catch (SQLException e) {
            // here process exception.
            // ...
        }
    }
}

Authentication

You can use the token or the AK/SK to complete authentication for GES Cypher JDBC Driver.

  • If you use the token, refer to Using Parameters and Usage Example to complete the authentication.
  • For AK/SK authentication, you need to specify the AK/SK using the GES service plane SDK.

    For details about how to import the service plane SDK dependency, see Importing a Project. For details about how to configure GraphInfo, see Initializing the Client of the GES Service Plane. You need to enter the obtained AK/SK and the region name.

    The following is an example for AK/SK authentication:
    import com.huawei.ges.jdbc.io.model.GesElement;
    import com.huawei.graph.sdk.GraphInfo;
    import com.huawei.graph.sdk.exception.GraphSdkException;
    import com.huawei.graph.sdk.utils.HttpRestClient;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.Properties;
    import java.util.Map;
    
    public class CypherJDBCClientByAKSK {
    
        private static final Logger logger = LoggerFactory.getLogger("CypherJDBCClientByAKSK");
        private static String ip = "";
        private static int port = 80;
        private static String projectId = "";
        private static String graphName = "";
        String accessKey = "here is access key";
        String secretKey = "here is secret key";
        String regionName = "cn-north-4";
        public static GraphInfo getGraphInfo() {
            // Initialize the GraphInfo object in a way it is required (this example is just for reference).
            GraphInfo info = getGraphInfoByYourSelf();
           // Specify the AK/SK.
            info.setAccessKey(accessKey);    
            info.setSecretKey(secretKey);   
          // Specify the region name.
            info.setRegionName(regionName);
            return info;
        }
    
        public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, GraphSdkException {
    
            GraphInfo info = getGraphInfo();
    
            Map<String, String> iamHeader = HttpRestClient.getIamSignHeaders(info);
            Class.forName("com.huawei.ges.jdbc.Driver").newInstance();
            String url = "jdbc:ges:http://{{graph_ip}}:{{graph_port}}/ges/v1.0/{{project_id}}/graphs/{{graph_name}}/action?action_id=execute-cypher-query";
            url = url.replace("{{graph_ip}}", ip).replace("{{graph_port}}", port + "").replace("{{project_id}}", projectId).replace("{{graph_name}}", graphName);
            doCypherQuery(url, iamHeader);
        }
    
        public static void doCypherQuery(String url, Map<String, String> iamHeaders) {
            Properties prop = new Properties();
            for (Map.Entry<String, String> pair : iamHeaders.entrySet()) {
                prop.setProperty(pair.getKey(), pair.getValue());
            }
            prop.setProperty("deserializer-type", "lazy");
            prop.setProperty("parse-json", "true");
            prop.setProperty("limit", "10000");
            try (Connection conn = DriverManager.getConnection(url, prop)) {
                String query = "match (m) return m limit 1";
                try (PreparedStatement stmt = conn.prepareStatement(query)) {
                    try (ResultSet rs = stmt.executeQuery()) {
                        Object o = null;
                        while (rs.next()) {
                            GesElement.GesVertex vertex = (GesElement.GesVertex) rs.getObject("m");
                            System.out.println(vertex.getId());
                            System.out.println(vertex.getLabels());
                            System.out.println(vertex.getProperties());
                        }
                    }
                }
            } catch (SQLException e) {
                logger.info("Execute SQL query error.");
            }
        }
    }