Updated on 2025-09-04 GMT+08:00

Connecting to a GeminiDB Cassandra Instance Using Go

This section describes how to connect to a GeminiDB Cassandra instance using Go.

Prerequisites

Procedure

  1. Obtain the private IP address and port number of the GeminiDB Cassandra instance.

    For details about how to obtain the private IP address and port number, see Viewing the IP Address and Port Number of a GeminiDB Cassandra Instance.

  2. Log in to the ECS. For details, see Logging In to an ECS in Getting Started with Elastic Cloud Server.
  3. Edit the code for connecting to the GeminiDB Cassandra instance.

    import (
        "os"
    )
    // Default LoadBalancingPolicy RoundRobinHostPolicy
    cluster := gocql.NewCluster("192.168.1.1", "192.168.1.2", "192.168.1.3")
    
    // There will be security risks if the username and password used for authentication are directly written into code. Store the username and password in ciphertext in the configuration file or environment variables.
    // In this example, the username and password are stored in the environment variables. Before running this example, set environment variables EXAMPLE_USERNAME_ENV and EXAMPLE_PASSWORD_ENV as needed.
    username = os.Getenv("EXAMPLE_USERNAME_ENV"),
    password = os.Getenv("EXAMPLE_PASSWORD_ENV"),
    cluster.Authenticator = gocql.PasswordAuthenticator{
    		Username: username,
    		Password: password
     }
    cluster.Keyspace = "ks1"
    // connect to the cluster
    session, err := cluster.CreateSession()
    if err != nil {
        log.Fatal(err)
    }
    defer session.Close()

  4. Run sample code to check whether the result is normal.

Executing Write and Read Operations

Create a session query. Query parameters cannot be used in other statements and cannot be modified after the query starts.

Use Query.Exec if you need to read the query results after a query is executed:

 err := session.Query(`INSERT INTO tweet (timeline, id, text) VALUES (?, ?, ?)`,
        "me", gocql.TimeUUID(), "hello world").WithContext(ctx).Exec()

Use Query.Scan to read one row:

 err := session.Query(`SELECT id, text FROM tweet WHERE timeline = ? LIMIT 1`,
        "me").WithContext(ctx).Consistency(gocql.One).Scan(&id, &text)

Use Iter.Scanner to read multiple rows:

scanner := session.Query(`SELECT id, text FROM tweet WHERE timeline = ?`,
    "me").WithContext(ctx).Iter().Scanner()
 for scanner.Next() {
    var (
        id gocql.UUID
        text string
    )
    err = scanner.Scan(&id, &text)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Tweet:", id, text)
 }
 // scanner.Err() closes the iterator, so scanner nor iter should be used afterwards.
 if err := scanner.Err(); err != nil {
    log.Fatal(err)
 }

Executing Multiple Queries Concurrently

It is safe to share a session in multiple goroutines. You can execute concurrent queries using multiple worker goroutines.

results := make(chan error, 2)
go func() {
    results <- session.Query(`INSERT INTO tweet (timeline, id, text) VALUES (?, ?, ?)`,
        "me", gocql.TimeUUID(), "hello world 1").Exec()
}()
go func() {
    results <- session.Query(`INSERT INTO tweet (timeline, id, text) VALUES (?, ?, ?)`,
        "me", gocql.TimeUUID(), "hello world 2").Exec()
}()