Using key/value pairs

To save a key/value pair, use the Txn.Set() method:

  1. err := db.Update(func(txn *badger.Txn) error {
  2. err := txn.Set([]byte("answer"), []byte("42"))
  3. return err
  4. })

Key/Value pair can also be saved by first creating Entry, then setting this Entry using Txn.SetEntry(). Entry also exposes methods to set properties on it.

  1. err := db.Update(func(txn *badger.Txn) error {
  2. e := badger.NewEntry([]byte("answer"), []byte("42"))
  3. err := txn.SetEntry(e)
  4. return err
  5. })

This will set the value of the "answer" key to "42". To retrieve this value, we can use the Txn.Get() method:

  1. err := db.View(func(txn *badger.Txn) error {
  2. item, err := txn.Get([]byte("answer"))
  3. handle(err)
  4. var valNot, valCopy []byte
  5. err := item.Value(func(val []byte) error {
  6. // This func with val would only be called if item.Value encounters no error.
  7. // Accessing val here is valid.
  8. fmt.Printf("The answer is: %s\n", val)
  9. // Copying or parsing val is valid.
  10. valCopy = append([]byte{}, val...)
  11. // Assigning val slice to another variable is NOT OK.
  12. valNot = val // Do not do this.
  13. return nil
  14. })
  15. handle(err)
  16. // DO NOT access val here. It is the most common cause of bugs.
  17. fmt.Printf("NEVER do this. %s\n", valNot)
  18. // You must copy it to use it outside item.Value(...).
  19. fmt.Printf("The answer is: %s\n", valCopy)
  20. // Alternatively, you could also use item.ValueCopy().
  21. valCopy, err = item.ValueCopy(nil)
  22. handle(err)
  23. fmt.Printf("The answer is: %s\n", valCopy)
  24. return nil
  25. })

Txn.Get() returns ErrKeyNotFound if the value is not found.

Please note that values returned from Get() are only valid while the transaction is open. If you need to use a value outside of the transaction then you must use copy() to copy it to another byte slice.

Use the Txn.Delete() method to delete a key.