Command: SET
Overview
The SET
command is used to store a key-value pair in the database. If the key already exists, the value is overwritten. It is a common operation to persist data in memory Database.
Command Name
SET
Description
Stores the given key with its associated value in the in-memory store.
If the key already exists, its value is replaced.
The key must be a valid string (as per key validation rules
), and exactly two arguments must be provided: a key and a value.
Syntax
SET <key> <value>
-
<key>
: A valid string identifier for the value. -
<value>
: A string value to be associated with the key.
Permissions
No special permissions are required. All clients connected to the database can use this command.
Input Examples
Store a simple string
localhost:9219> SET username john
Store numeric string value
localhost:9219> SET age 30
Output Examples
localhost:9219> SET username john
Ok
Example 2:
localhost:9219> SET age 30
Ok
Behavior on Error
The SET
command may return the following error responses:
Condition | Error Message |
---|---|
No arguments provided | InvalidArgumentError: Key and value must be provided |
Only one argument provided | InvalidArgumentError: Key and value must be provided |
Invalid key format | InvalidKeyError: <reason> |
Internal store error | <detailed error from store.Set> |
Missing value
localhost:9219> SET onlykey
InvalidArgumentError: Key and value must be provided
Invalid key
localhost:9219> SET /invalid key value
InvalidKeyError: key contains invalid characters
Use Cases
-
Store user profile data
SET username alice SET email alice@example.com
-
Temporary session data
SET session_abc123 active
-
Overwrite existing key
SET username alice SET username bob GET username // returns "bob"
JSON String
localhost:9219> SET user:123 '{"id":123,"name":"Alice","roles":["admin","editor"]}'
Ok
Output
localhost:9219> GET config
Ok {
"id": 123,
"name": "Alice",
"roles": [
"admin",
"editor"
]
}
Multiline String (escaped)
localhost:9219> SET message 'Hello,\nWelcome to our service!\nRegards,\nTeam'
Ok
Nested JSON
localhost:9219> SET config '{"logging":{"level":"debug","enabled":true},"max_conn":100}'
Ok
Output
localhost:9219> GET config
Ok {
"logging": {
"level": "debug",
"enabled": true
},
"max_conn": 100
}
Boolean Value (as string)
localhost:9219> SET feature_x_enabled true
Ok
Array-like String
localhost:9219> SET fruits '["apple", "banana", "mango"]'
Ok
Long String (truncated view)
localhost:9219> SET longtext 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
Ok
Key with Namespace Prefix
localhost:9219> SET session:user:456 "active"
Ok
Optional: GET Output Examples
If you subsequently run GET
on the above keys, the values will return as-is:
localhost:9219> GET user:123
Ok {
"id": 123,
"name": "Alice",
"roles": [
"admin",
"editor"
]
}