Opening a database
The top-level object in Badger is a DB
. It represents multiple files on disk in specific directories, which contain the data for a single database.
To open your database, use the badger.Open()
function, with the appropriate options. The Dir
and ValueDir
options are mandatory and must be specified by the client. They can be set to the same value to simplify things.
package main
import (
"log"
badger "github.com/dgraph-io/badger/v2"
)
func main() {
// Open the Badger database located in the /tmp/badger directory.
// It will be created if it doesn't exist.
db, err := badger.Open(badger.DefaultOptions("/tmp/badger"))
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Your code here…
}
Please note that Badger obtains a lock on the directories so multiple processes cannot open the same database at the same time.
In-Memory Mode/Diskless Mode
By default, Badger ensures all the data is persisted to the disk. It also supports a pure in-memory mode. When Badger is running in in-memory mode, all the data is stored in the memory. Reads and writes are much faster in in-memory mode, but all the data stored in Badger will be lost in case of a crash or close. To open badger in in-memory mode, set the InMemory
option.
opt := badger.DefaultOptions("").WithInMemory(true)