Skip to main content

SET

Syntax

SET key value [NX | XX] [GET] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds]

Module

generic

Categories

slow write

Description

Set the value of a key, considering the value's type. If the key already exists, it is overwritten.

Options

  • NX - Only set if the key does not exist.
  • XX - Only set if the key exists.
  • GET - Return the old value stored at key, or nil if the value does not exist.
  • EX - Expire the key after the specified number of seconds (positive integer).
  • PX - Expire the key after the specified number of milliseconds (positive integer).
  • EXAT - Expire at the exact time in unix seconds (positive integer).
  • PXAT - Expire at the exat time in unix milliseconds (positive integer).

Examples

The embedded API organizes the SET command options into constants wrapped in interfaces.


SetWriteOption

  • SETNX - Only set if the key does not exist.
  • SETXX - Only set if the key exists.

SetExOption

  • SETEX - Expire the key after the specified number of seconds.
  • SETPX - Expire the key after the specified number of milliseconds.
  • SETEXAT - Expire at the exact time in unix seconds.
  • SETPXAT - Expire at the exact time in unix milliseconds.

The API provides a struct called SETOptions that wraps these options in a convenient object.

type SETOptions struct {        
WriteOpt SetWriteOption
ExpireOpt SetExOption
ExpireTime int
Get bool
}

Set a value at a key:

db, err := sugardb.NewSugarDB()
if err != nil {
log.Fatal(err)
}
ok, err := db.Set("name", "SugarDB", db.SETOptions{})

Set a value only if the key does not exist:

db, err := sugardb.NewSugarDB()
if err != nil {
log.Fatal(err)
}
ok, err := db.Set("name", "SugarDB", db.SETOptions{WriteOpt: db.SETNX})

Set a value if key already exists and get the previous value:

db, err := sugardb.NewSugarDB()
if err != nil {
log.Fatal(err)
}
previousValue, err := db.Set("name", "SugarDB", db.SetOptions{WriteOpt: db.SETXX, Get: true})

Set a value if the key already exists, return the previous value, and expire after 10 seconds:

db, err := sugardb.NewSugarDB()
if err != nil {
log.Fatal(err)
}
previousValue, err := db.Set("name", "SugarDB", db.SetOptions{WriteOpt: db.SETXX, ExpireOpt: db.SETEX, ExpireTime 10, Get: true})