ScyllaDB is a high-performance NoSQL database compatible with Apache Cassandra. Using the Go language, you can interact with ScyllaDB through the gocql
driver, one of the most used clients for Cassandra/ScyllaDB in Go.
Prerequisites
- ScyllaDB running (locally or in a cluster)
- Go installed (version 1.18 or higher recommended)
- Go module initialized
Installing the gocql driver
First, add the gocql
package to your project:
go get github.com/gocql/gocql
Connecting to ScyllaDB
To connect to ScyllaDB, define a session with the cluster details:
package main
import (
"fmt"
"log"
"github.com/gocql/gocql"
)
func main() {
cluster := gocql.NewCluster("127.0.0.1")
cluster.Keyspace = "test"
cluster.Consistency = gocql.Quorum
session, err := cluster.CreateSession()
if err != nil {
log.Fatalf("Connection error: %v", err)
}
defer session.Close()
fmt.Println("Successfully connected to ScyllaDB")
}
Creating a table
err := session.Query(`
CREATE TABLE IF NOT EXISTS users (
id UUID PRIMARY KEY,
name text,
email text
)`).Exec()
if err != nil {
log.Fatal(err)
}
Inserting data
id := gocql.TimeUUID()
if err := session.Query(`
INSERT INTO users (id, name, email) VALUES (?, ?, ?)`,
id, "Mario Rossi", "mario@example.com").Exec(); err != nil {
log.Fatal(err)
}
Reading data
var name, email string
iter := session.Query(`
SELECT name, email FROM users WHERE id = ? LIMIT 1`,
id).Iter()
for iter.Scan(&name, &email) {
fmt.Printf("Name: %s, Email: %s\n", name, email)
}
if err := iter.Close(); err != nil {
log.Fatal(err)
}
Final considerations
ScyllaDB, thanks to its compatibility with Cassandra, allows the use of existing drivers like gocql
to build robust and scalable applications. It's important to follow best practices for table design and consistency management in queries.
For production environments, consider using advanced cluster configurations and replication management.