Introductory tutorial to Badger

Introduction

Badger in its official documentation says

BadgerDB is an embeddable, persistent and fast key-value (KV) database written in pure Go

Badger is a good story in the life of Go programming language given that more and more infrastructural services are increasingly written in Go. Though there are many other in-memory DBs written in Go ex: BoltDB which now is archived and no active development ongoing, badger stands out in every way. It is even simple to work with if you get through the initial hiccups, staying true to Go's philosophy of simplicity.

Badger in its documentation and also in the introductory blog speaks about the design choices and the reasons for writing badger so I wouldn't venture into summarizing that great article.

What I would like to focus on is how to use this library to create an in-memory db for my application, to be even more specific I will focus on how to insert and fetch the records from the DB.

Complete code for this tutorial is available on github

Create a DB

badger.DB object can be created like so

db, err := badger.Open(badger.DefaultOptions("/tmp/badge"))
if err != nil {
    err = fmt.Errorf("error when opening the badger db: %w", err)
    log.Fatal(err)
}
defer db.Close()

Write to the DB

key := "key"
value := "value"
txn := db.NewTransaction(true)
txn.Set([]byte(key), []byte(value))
txn.Commit()

Read from the DB

txn := db.NewTransaction(false)
item, err := txn.Get([]byte(key))
if err != nil {
    err = fmt.Errorf("error when getting the value: %w", err)
    log.Fatal(err)
}
var v []byte
item.Value(func(val []byte) error {
    v = val
    return nil
})
fmt.Printf("Key: %s\t Value: %s\n", key, string(v))

Summary

Badger is a promising new database give it a try and do comment or react below if you found this article useful.

No Comments Yet