SET
Syntax
SET key value [NX | XX] [GET] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds]
Module
genericCategories
slow writeDescription
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
- Go (Embedded)
- CLI
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})
Set a value at a key:
> SET name SugarDB
Set a value only if the key does not exist:
> SET name SugarDB NX
Set a value if key already exists and get the previous value:
> SET name SugarDB XX GET
Set a value if the key already exists, return the previous value, and expire after 10 seconds:
> SET name SugarDB XX GET EX 10