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.

  1. package main
  2. import (
  3. "log"
  4. badger "github.com/dgraph-io/badger/v2"
  5. )
  6. func main() {
  7. // Open the Badger database located in the /tmp/badger directory.
  8. // It will be created if it doesn't exist.
  9. db, err := badger.Open(badger.DefaultOptions("/tmp/badger"))
  10. if err != nil {
  11. log.Fatal(err)
  12. }
  13. defer db.Close()
  14. // Your code here…
  15. }

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.

  1. opt := badger.DefaultOptions("").WithInMemory(true)