Go Cassandra – CRUD Example

Go Cassandra – CRUD Example

Using GoCQL driver, Go application connects with Cassandra database. In this example we will be creating CRUD application with the help of Go and Cassandra. To run this example you should have Cassandra instance running on your machine.  

Create keyspace and table in Cassandra

Create emps table in database using cql client. In this example, we have created Code2Succeed as a keyspace however you can use any other name.

CREATE KEYSPACE Code2Succeed
  WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };
  
  
CREATE TABLE emps (
  empid text PRIMARY KEY,
  first_name text,
  last_name text,
  age int
);

Install GoCQL driver

To get GoCQL, use following command to install GoCQL driver

go get github.com/gocql/gocql

Database connection

We are going to create simple console application. So open any text editor and create a file db.go with Emp Struct and following methods
init() – contains code to establish connection with Cassandra database.
main() – contains code to run the application.

package main

import (
	"fmt"

	"github.com/gocql/gocql"
)

var Session *gocql.Session

type Emp struct {
	id        string
	firstName string
	lastName  string
	age       int
}

func init() {
	var err error

	cluster := gocql.NewCluster("127.0.0.1")
	cluster.Keyspace = "code2succeed"
	Session, err = cluster.CreateSession()
	if err != nil {
		panic(err)
	}
	fmt.Println("cassandra init done")
}

func main() {

}

Create Employee

Create function createEmp to create a new row in emps table

func createEmp(emp Emp) {
	fmt.Println(" **** Creating new emp ****\n", emp)
	if err := Session.Query("INSERT INTO emps(empid, first_name, last_name, age) VALUES(?, ?, ?, ?)",
		emp.id, emp.firstName, emp.lastName, emp.age).Exec(); err != nil {
		fmt.Println("Error while inserting Emp")
		fmt.Println(err)
	}
}

Get All Employees

function to get All employees from database. We are using iterator with mapScan() to get all employees.

func getEmps() []Emp {
	fmt.Println("Getting all Employees")
	var emps []Emp
	m := map[string]interface{}{}

	iter := Session.Query("SELECT * FROM emps").Iter()
	for iter.MapScan(m) {
		emps = append(emps, Emp{
			id:        m["empid"].(string),
			firstName: m["first_name"].(string),
			lastName:  m["last_name"].(string),
			age:       m["age"].(int),
		})
		m = map[string]interface{}{}
	}

	return emps
}

Update a Employee

Update a employee based on empid.

func updateEmp(emp Emp) {
	fmt.Printf("Updating Emp with id = %s\n", emp.id)
	if err := Session.Query("UPDATE emps SET first_name = ?, last_name = ?, age = ? WHERE empid = ?",
		emp.firstName, emp.lastName, emp.age, emp.id).Exec(); err != nil {
		fmt.Println("Error while updating Emp")
		fmt.Println(err)
	}
}

Delete a Employee

Delete employee using empid.

func deleteEmp(id string) {
	fmt.Printf("Deleting Emp with id = %s\n", id)
	if err := Session.Query("DELETE FROM emps WHERE empid = ?", id).Exec(); err != nil {
		fmt.Println("Error while deleting Emp")
		fmt.Println(err)
	}
}

Main method to run the application

func main() {
	emp1 := Emp{"E-1", "Anupam", "Raj", 20}
	emp2 := Emp{"E-2", "Rahul", "Anand", 30}
	createEmp(emp1)
	fmt.Println(getEmps())
	createEmp(emp2)
	fmt.Println(getEmps())
	emp3 := Emp{"E-1", "Rahul", "Anand", 30}
	updateEmp(emp3)
	fmt.Println(getEmps())
	deleteEmp("E-2")
	fmt.Println(getEmps())
}

Output

cassandra init done
 **** Creating new emp ****
 {E-1 Anupam Raj 20}
Getting all Employees
[{E-1 Anupam Raj 20}]
 **** Creating new emp ****
 {E-2 Rahul Anand 30}
Getting all Employees
[{E-2 Rahul Anand 30} {E-1 Anupam Raj 20}]
Updating Emp with id = E-1
Getting all Employees
[{E-2 Rahul Anand 30} {E-1 Rahul Anand 30}]
Deleting Emp with id = E-2
Getting all Employees
[{E-1 Rahul Anand 30}]

 

Download complete code Go Cassandra – CRUD Example

Stay tuned for more tutorials and examples !

 

 

One thought on “Go Cassandra – CRUD Example

  1. I think this is one of the most important info for me. And i am glad reading your article. But wanna remark on few general things, The web site style is ideal, the articles is really excellent D. Good job, cheers kkaaadbgbdfe

Leave a Reply

Your email address will not be published. Required fields are marked *