Go

Updated at:

This topic describes how to use the Go programming language to connect to and manage a Graph Database (GDB) instance. This method is commonly used for applications that run as persistent services.

Important
  • To run the following examples, ensure that your runtime environment can connect to your Graph Database (GDB) instance.

  • Your runtime environment must have Go installed. The examples in this topic use Go 1.12.

Prepare the environment

  1. Install the Go programming environment. For Linux, you can install the binary package directly.

  2. Install the Graph Database (GDB) software development kit (SDK).

    go get -u github.com/aliyun/alibabacloud-gdb-go-sdk/gdbclient
  3. Obtain the connection parameters for your GDB instance.

    On the Instance Management > Basic Information page, find the private endpoint and port. If you enabled public access for the instance, you can also use the public endpoint and port.

    # Private network
    host = "${gdbID}.graphdb.rds.aliyuncs.com"
    port = 8182
    # Public network
    host = "${gdbID}pub.graphdb.rds.aliyuncs.com"
    port = 3734
    Important

    Ensure that the IP address of your runtime environment is in the instance's whitelist.

    On the Instance Management > Account Management page, find your account information. If you forget your password, you can click the Reset Password button.

Sample program

The GDB SDK includes a demo program. The following code is taken from that demo.

  1. You can create a demo folder and add a test file.

    mkdir gdb_go_demo
    cd gdb_go_demo
    touch main.go
  2. Write the test code. To run the code, you must provide the connection parameters for your GDB instance as arguments.

    package main
    import (
        "flag"
        "log"
        goClient "github.com/aliyun/alibabacloud-gdb-go-sdk/gdbclient"
    )
    var (
        host, username, password string
        port                     int
    )
    func main() {
        flag.StringVar(&host, "host", "", "GDB Connection Host")
        flag.StringVar(&username, "username", "", "GDB username")
        flag.StringVar(&password, "password", "", "GDB password")
        flag.IntVar(&port, "port", 8182, "GDB Connection Port")
        flag.Parse()
        if host == "" || username == "" || password == "" {
            log.Fatal("No enough args provided. Please run:" +
                " go run main.go -host <gdb host> -username <username> -password <password> -port <gdb port>")
            return
        }
        settings := &goClient.Settings{
            Host:     host,
            Port:     port,
            Username: username,
            Password: password,
        }
        // Connect to GDB with authentication.
        client := goClient.NewClient(settings)
        // Send a script DSL with bindings to GDB.
        bindings := make(map[string]interface{})
        bindings["GDB___id"] = "gdb_vertex_test_id"
        bindings["GDB___label"] = "gdb_vertex_test_label"
        bindings["GDB___PK"] = "name"
        bindings["GDB___PV"] = "Jack"
        dsl := "g.addV(GDB___label).property(id, GDB___id).property(GDB___PK, GDB___PV)"
        results, err := client.SubmitScriptBound(dsl, bindings)
        if err != nil {
            log.Fatalf("Error while querying: %s\n", err.Error())
        }
        // Get the response. Adding a vertex should return a Vertex object.
        for _, result := range results {
            v := result.GetVertex()
            log.Printf("get vertex[id:%s, label:%s, propLen %d", v.Id(), v.Label(), len(v.Properties()))
            // Read the vertex property.
            for _, p := range v.VProperties() {
                log.Printf(" {PK: %s, PV: %s}", p.PKey(), p.PValue().(string))
            }
        }
        // Drop all vertices.
        _, err = client.SubmitScript("g.V().drop()")
        if err != nil {
            log.Fatalf("Error while querying: %s\n", err.Error())
        }
        client.Close()
    }

    This code creates a client to connect to GDB. It sends a Gremlin operation to add a vertex, prints the result, and then sends another operation to purge all data. For more information about client parameter configurations, such as connection pools and session support, see the demo code in the SDK package.

Run the test program

Replace the command-line parameters with your GDB connection parameters and run the test code. A successful run produces output similar to the following:

go run main.go -host ${host} -port ${port} -username ${username} -password ${password}
2019/12/23 14:22:49 get vertex[id:gdb_vertex_test_id, label:gdb_vertex_test_label, propLen 1
2019/12/23 14:22:49  {PK: name, PV: Jack}

About the GDB Go SDK

  • The GDB Go SDK is a Gremlin client developed and maintained by the Alibaba Cloud GDB team. You are encouraged to use it and submit merge requests (MRs).

  • The Go SDK does not currently support bytecode interaction with GDB. We recommend that you use script mode with templates for variable parameters to access GDB.

  • The Go SDK provides a session interface that supports multiple update operations within a single transaction. This ensures that all operations either succeed or fail together and prevents partial updates.