Redis Command: SET

Summary

Command NameSET
UsageSet string value
Group string
ACL Category@write
@string
@fast
Time ComplexityO(1)
FlagWRITE
DENYOOM
Arity-3

Signature

SET <key> <value> [ NX | XX ] [ GET ] [ EX <second> | PX <millisecond> | EAT <unix_timestamp_in_second> | PXAT <unix_timestamp_in_millisecond> | KEEPTTL ]

All the options other than the <key> and <value> are optional. We can just pass the <key> and <value> and the command will work fine.

Here is a simple signature of the SET command, without complex options-

SET <key> <value>

Usage

Set the string value of a key. The key is created if it does not exist already.

Notes

  • If the key already exists, then no matter what the type of the existing data is, it will be overwritten by SET command.
  • When a value is set(without any expiration time) for an existing key, then the existing TTL will be removed(if any TTL is already set).

Arguments

Here is the description of what each part of the SET command means in the above signature-

ParameterParameter GroupDescriptionNameTypeOptional
<key>Name of the keykeykey
<value>Value that needs to be stored for the keyvaluestring
NXconditionOnly save the value if the key does not exist.nxpure-tokenTrue
XXconditionOnly save value if the key already exists.xxpure-tokenTrue
GETGet/return the old value. This follows there rule and return type of the GET command.getpure-tokenTrue
EX <second>expirationExpire time duration in secondssecondsintegerTrue
PX <millisecond>expirationExpire time duration in millisecondsmillisecondsintegerTrue
EAT <unix_timestamp_in_second>expirationUnix timestamp in second for key expireunix-time-secondsunix-timeTrue
PXAT <unix_timestamp_in_millisecond>expirationUnix timestamp in milliseconds for key expireunix-time-millisecondsunix-timeTrue
KEEPTTLexpirationKeep already set TTL for the keykeepttlpure-tokenTrue

Notes

  • The KEEPTTL option is available for Redis version >= 6.0.

Return Value

Return valueCase for the return valueType
OKIf the value is set properlyconst (OK)
nilIf the value is not set for some reasonnull
some previous valueIf GET option is provided and a value already existedstring

Examples

Here are a few examples of the SET command usage-

# Set value for a key
127.0.0.1:6379> set firstkey "abcdef"
OK

127.0.0.1:6379> get firstkey
"abcdef"

# Set value for the same key again. The new value is set for the key
127.0.0.1:6379> set firstkey defghi
OK

127.0.0.1:6379> get firstkey
"defghi"

# Use "XX" option to set value only if the key already exists
127.0.0.1:6379> set secondkey "000000000000" XX
(nil)

# second key is not set in this case as it was not preexisting
127.0.0.1:6379> get secondkey
(nil)

# Use "NX" option to set value if the key does not exist
127.0.0.1:6379> set secondkey "000000000000" NX
OK

# secondkey is set as it was not pre-existing
127.0.0.1:6379> get secondkey
"000000000000"

# Use "NX" for an existing key, that returns nil
127.0.0.1:6379> set firstkey "work idea" NX
(nil)

127.0.0.1:6379> get firstkey
"defghi"

# Pass the "GET" option to get the previous value.
# If the value was not set previously then we get nil
127.0.0.1:6379> set thirdkey 1111111111 GET
(nil)

# Pass "GET" to fetch the previous value before setting new value
127.0.0.1:6379> set thirdkey 99999999 GET
"1111111111"

# Set expire time in seconds using "EX" option (other expire duration related options work the same way)
127.0.0.1:6379> set fourthkey "some value for expire" EX 120
OK

127.0.0.1:6379> ttl fourthkey
(integer) 115

# Set expire time
127.0.0.1:6379> set mykey "some val" ex 360
OK

127.0.0.1:6379> ttl mykey
(integer) 357

# setting already existing key will remove the TTL if there is any
127.0.0.1:6379> set mykey "changed value"
OK

# TTL was removed as the value was set the second time without any expire time
127.0.0.1:6379> ttl mykey
(integer) -1


# Set value with expire time - the following commands are for checking "KEEPTTL" option
127.0.0.1:6379> set user:10 "John Doe" ex 360
OK

127.0.0.1:6379> ttl user:10
(integer) 354

# Set value for the same key, and pass "KEEPTTL" option. This will keep the TTL that was associated with the key
127.0.0.1:6379> set user:10 "Some user" keepttl
OK

# Lets check the TTL. The TTL still exists because of usign the "KEEPTTL" option
127.0.0.1:6379> ttl user:10
(integer) 326

Notes

  • Setting the same key value multiple times, will set the value to the last set value. Every time a value is set for a key, it will replace/overwrite the existing value(if already set).
  • Setting a key/value without any expire time will remove the previously set expire time(if there was any expire time set).

Code Implementations

Here are the usage examples of the Redis SET command in Golang, NodeJS, PHP, and Python programming languages.

// Redis SET command example in Golang

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/redis/go-redis/v9"
)

var rdb *redis.Client
var ctx context.Context
var colorRed = "33[31m"
var styleReset = "33[0m"

func init() {
	rdb = redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Username: "default",
		Password: "",
		DB:       0,
	})

	ctx = context.Background()
}

func main() {
	// Set value for 'firstkey'
	// Command: set firstkey "abcdef"
	// OK
	err := rdb.Set(ctx, "firstkey", "abcdef", 0).Err()

	if err != nil {
		fmt.Println(colorRed + "Can not set firstkey" + styleReset)
	}

	fmt.Println("Value of 'firstkey' is set to 'abcdef'")

	// Check value of 'firstkey'
	// Command: get firstkey
	// Result: "abcdef"
	firstKey, err := rdb.Get(ctx, "firstkey").Result()

	if err != nil {
		fmt.Println(colorRed + "Can not read 'firstkey'" + styleReset)
	}

	fmt.Printf("Value of 'firstkey' is: %sn", firstKey)

	// Set value of the same key(firstkey) again. The new value is set for the key
	// Command: set firstkey defghi
	// Result: OK
	err = rdb.Set(ctx, "firstkey", "defghi", 0).Err()

	if err != nil {
		fmt.Println(colorRed + "Can not set firstkey" + styleReset)
	}

	fmt.Println("Setting value of 'firstkey' to: 'defghi'")

	// Check value of 'firstkey'
	// Command: get firstkey
	// Result: "defghi"
	firstKey, err = rdb.Get(ctx, "firstkey").Result()

	if err != nil {
		fmt.Println(colorRed + "Can not read 'firstkey'" + styleReset)
	}

	fmt.Printf("Value of 'firstkey': %sn", firstKey)

	// # Use "XX" option to set value only if the key already exists
	// Command: set secondkey "000000000000" XX
	// Result: (nil)
	argsXX := redis.SetArgs{
		Mode: "xx",
	}
	err = rdb.SetArgs(ctx, "secondkey", "000000000000", argsXX).Err()

	if err != nil {
		fmt.Println("Can not set 'secondkey' with 'XX' as the key does not exist yet")
	} else {
		fmt.Println("'secondkey' value set to: 000000000000 with 'XX'")
	}

	// Second key is not set in this case as it was not preexisting
	// Command: get secondkey
	// Result: (nil)
	secondKey, err := rdb.Get(ctx, "secondkey").Result()

	if err != nil {
		fmt.Println(colorRed + "Can not read 'secondkey'" + styleReset)
	}

	fmt.Printf("Value of 'secondkey': %sn", secondKey)

	// Use "NX" option to set value if the key does not exist
	// Command: set secondkey "000000000000" NX
	// Result: OK
	argsNX := redis.SetArgs{
		Mode: "nx",
	}
	err = rdb.SetArgs(ctx, "secondkey", "000000000000", argsNX).Err()

	if err != nil {
		fmt.Println("Can not set 'secondkey' with 'NX' as the key does not exist yet")
	} else {
		fmt.Println("'secondkey' value set to: 000000000000 with 'NX'")
	}

	// Secondkey is set as it was not pre-existing
	// Command: get secondkey
	// Result: "000000000000"
	secondKey, err = rdb.Get(ctx, "secondkey").Result()

	if err != nil {
		fmt.Println(colorRed + "Can not read 'secondkey'" + styleReset)
	}

	fmt.Printf("Value of 'secondkey': %sn", secondKey)

	// # Use "NX" for an existing key, that returns nil
	// Command: set firstkey "work idea" NX
	// Result: (nil)
	argsNX = redis.SetArgs{
		Mode: "nx",
	}
	err = rdb.SetArgs(ctx, "firstkey", "work idea", argsNX).Err()

	if err != nil {
		fmt.Println(colorRed + "Can not set 'firstkey' with 'NX' as the key does not exist yet" + styleReset)
	} else {
		fmt.Println("'firstkey' value set to: 'work idea' with 'NX'")
	}

	// Command: get firstkey
	// Result: "defghi"
	firstKey, err = rdb.Get(ctx, "firstkey").Result()

	if err != nil {
		fmt.Println(colorRed + "Can not read 'firstkey'" + styleReset)
	}

	fmt.Printf("Value of 'firstkey': %sn", firstKey)

	// Pass the "GET" option to get the previous value.
	// If the value was not set previously then we get nil
	// Command: set thirdkey 1111111111 GET
	// Result: (nil)
	argsGET := redis.SetArgs{
		Get: true,
	}

	thirdKey, err := rdb.SetArgs(ctx, "thirdkey", "1111111111", argsGET).Result()

	if err != nil {
		fmt.Println(colorRed + "Can not set 'thirdkey' with 'GET' as the key does not exist yet" + styleReset)
	} else {
		fmt.Println("'thirdkey' value set to: '1111111111' with 'GET'")
	}

	fmt.Printf("Value of 'thirdkey' after using GET is: %sn", thirdKey)

	// Pass "GET" to fetch the previous value before setting new value
	// Command: set thirdkey 99999999 GET
	// Result: "1111111111"
	argsGET = redis.SetArgs{
		Get: true,
	}

	thirdKey, err = rdb.SetArgs(ctx, "thirdkey", "99999999", argsGET).Result()

	if err != nil {
		fmt.Println(colorRed + "Can not set 'thirdkey' with 'GET' as the key does not exist yet" + styleReset)
	} else {
		fmt.Println("'thirdkey' value set to: '99999999' with 'GET'")
	}

	fmt.Printf("Value of 'thirdkey' after using GET is: %sn", thirdKey)

	// Set expire time in seconds using "EX" option (other expire duration related options work the same way)
	// Command: set fourthkey "some value for expire" EX 10
	// Result: OK
	argTTL := redis.SetArgs{
		TTL: 10 * time.Second,
	}

	err = rdb.SetArgs(ctx, "fourthkey", "some value for expire", argTTL).Err()

	if err != nil {
		fmt.Println(colorRed + "Can not set 'thirdkey'" + styleReset)
	}

	// Sleep for 10 seconds
	fmt.Println("Waiting for 10 seconds...")
	time.Sleep(10 * time.Second)

	// Check vlaue of 'fourthkey
	fourthKey, _ := rdb.Get(ctx, "fourthkey").Result()

	fmt.Printf("Value of fourthkey after expire time is up: %sn", fourthKey)

	// Set key 'user:10' for KeepTTL testing
	argTTL = redis.SetArgs{
		TTL: 30 * time.Second,
	}

	err = rdb.SetArgs(ctx, "user:10", "user 10 name", argTTL).Err()

	if err != nil {
		fmt.Println(colorRed + "Can not set 'user:10'" + styleReset)
	}

	// Sleep for 10 seconds
	fmt.Println("Waiting for 10 seconds...")
	time.Sleep(10 * time.Second)

	// Set value for the same key, and pass "KEEPTTL" option. This will keep the TTL that was associated with the key
	// Command: set user:10 "Some user" keepttl
	// Result: OK
	argKeepTTL := redis.SetArgs{
		KeepTTL: true,
	}

	err = rdb.SetArgs(ctx, "user:10", "some changed name of user", argKeepTTL).Err()
	if err != nil {
		fmt.Println("unable to set 'user:10' value to 'some changed name of user'")
	}

	// Let's check the TTL. The TTL still exists because of usign the "KEEPTTL" option
	// Command: ttl user:10
	// Result: (integer) 326
	ttl, err := rdb.TTL(ctx, "user:10").Result()

	if err != nil {
		fmt.Println(colorRed + "Can not read TTL of user:10" + styleReset)
	}

	fmt.Printf("TTL of 'user:10': %sn", ttl)

}

Output:

Value of 'firstkey' is set to 'abcdef'
Value of 'firstkey' is: abcdef

Setting value of 'firstkey' to: 'defghi'
Value of 'firstkey': defghi

Can not set 'secondkey' with 'XX' as the key does not exist yet
Can not read 'secondkey'
Value of 'secondkey':

'secondkey' value set to: 000000000000 with 'NX'
Value of 'secondkey': 000000000000

Can not set 'firstkey' with 'NX' as the key does not exist yet
Value of 'firstkey': defghi

Can not set 'thirdkey' with 'GET' as the key does not exist yet
Value of 'thirdkey' after using GET is:
'thirdkey' value set to: '99999999' with 'GET'

Value of 'thirdkey' after using GET is: 1111111111

Waiting for 10 seconds...

Value of fourthkey after expire time is up: 
Waiting for 10 seconds...
TTL of 'user:10': 20s

Notes

  • The package used for this implementation is “go-redis“.
  • The “Set” method signature in the library is func (c cmdable) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) *StatusCmd. So we need to pass a context, then key and value, and then expiration time.
  • Pass 0 (zero) as the expiration time for specifying no expiration time.
  • For options like “NX“, “XX“, “GET“, “KEEPTTL” etc. we need to use the method “SetArgs“. Signature of this command is func (c cmdable) SetArgs(ctx context.Context, key string, value interface{}, a SetArgs) *StatusCmd. The last param last param accepts a options like {xx: true} or {keepttl: true} etc.
// Redis SET command example in JavaScript(NodeJS)

import { createClient } from 'redis';

// Create redis client
const redisClient = createClient({
    url: 'redis://default:@localhost:6379'
});

redisClient.on('error', err => console.log('Error while connecting to Redis', err));

// Connect Redis client
await redisClient.connect();

/**
 * Set value for a key
 * 
 * Command: set firstkey "abcdef"
 * Result: OK
 */ 
let commandResult = await redisClient.set('firstkey', 'abcdef');

console.log(`key: 'firstkey', value: 'abcdef' - set result: ${commandResult}`);


/**
 * Command: get firstkey
 * Result: "abcdef"
 */
commandResult = await redisClient.get('firstkey');

console.log(`'firstkey' get result: ${commandResult}`);


/**
 * Set value for the same key again. The new value is set for the key
 * 
 * Command: set firstkey defghi
 * Result: OK
 */
commandResult = await redisClient.set('firstkey', 'defghi');

console.log(`key: 'firstkey', value: 'abcdef' - set result: ${commandResult}`);


/**
 * Command: get firstkey
 * Result: "defghi"
 */
commandResult = await redisClient.get('firstkey');

console.log(`'firstkey' get result: ${commandResult}`);

/**
 * Use "XX" option to set value only if the key already exists
 * 
 * Command: set secondkey "000000000000" XX
 * Result: (nil)
 */
commandResult = await redisClient.set('secondkey', '000000000000', {XX: true});

console.log(`key: 'secondkey', value: '000000000000', including 'XX' - set result: ${commandResult}`);


/**
 * secondkey is not set in this case as it was not preexisting
 * 
 * Command: get secondkey
 * Result: (nil)
 */
commandResult = await redisClient.get('secondkey');

console.log(`'secondkey' get result: ${commandResult}`);

/**
 * Use "NX" option to set value if the key does not exist
 * 
 * Command: set secondkey "000000000000" NX
 * Result: OK
 */
commandResult = await redisClient.set('secondkey', '000000000000', {NX: true});

console.log(`key: 'secondkey', value: '000000000000', including 'NX' - set result: ${commandResult}`);


/**
 * secondkey is set as it was not pre-existing
 * 
 * Command: get secondkey
 * Result: "000000000000"
 */
commandResult = await redisClient.get('secondkey');

console.log(`'secondkey' get result: ${commandResult}`);


/**
 * Use "NX" for an existing key, that returns nil
 * 
 * Command: set firstkey "work idea" NX
 * Result: (nil)
 */
commandResult = await redisClient.set('firstkey', 'work idea', {NX: true});

console.log(`key: 'firstkey', value: 'work idea', including 'NX' - set result: ${commandResult}`);


/**
 * Command: get firstkey
 * Result: "defghi"
 */
commandResult = await redisClient.get('firstkey');

console.log(`'firstkey' get result: ${commandResult}`);


/**
 * Pass the "GET" option to get the previous value.
 * If the value was not set previously then we get nil
 * 
 * Command: set thirdkey 1111111111 GET
 * Result: (nil)
 */
commandResult = await redisClient.set('thirdkey', '1111111111', {GET: true});

console.log(`key: 'thirdkey', value: '1111111111', including 'GET' - set result: ${commandResult}`);


/**
 * Pass "GET" to fetch the previous value before setting new value
 * 
 * Command: set thirdkey 99999999 GET
 * Result: "1111111111"
 */
commandResult = await redisClient.set('thirdkey', '99999999', {GET: true});

console.log(`key: 'thirdkey', value: '99999999', including 'GET' - set result: ${commandResult}`);


/**
 * Set expire time in seconds using "EX" option (other expire duration related options work the same way)
 * 
 * Command: set fourthkey "some value for expire" EX 120
 * Result: OK
 */
commandResult = await redisClient.set('fourthkey', 'some value for expire', {EX: 120});

console.log(`key: 'fourthkey', value: 'some value for expire', including 'EX'=120 - set result: ${commandResult}`);


/**
 * Command: ttl fourthkey
 * Result: (integer) 120
 */
commandResult = await redisClient.ttl('fourthkey');

console.log("TTL of 'fourthkey': " + commandResult);

/**
 * Set expire time
 * 
 * Command: set mykey "some val" ex 360
 * Result: OK
 */
commandResult = await redisClient.set('mykey', 'some val', {EX: 360});

console.log(`key: 'mykey', value: 'some val', including 'EX'=360 - set result: ${commandResult}`);


/**
 * Command: ttl mykey
 * Result: (integer) 360
 */
commandResult = await redisClient.ttl('mykey');

console.log("TTL of 'mykey': " + commandResult);


/**
 * Setting already existing key will remove the TTL if there is any
 * 
 * Command: set mykey "changed value"
 * Result: OK
 */
commandResult = await redisClient.set('mykey', 'changed value');

console.log(`key: 'mykey', value: 'changed value' - set result: ${commandResult}`);


/**
 * TTL was removed as the value was set the second time without any expire time
 * 
 * Command: ttl mykey
 * Result: (integer) -1
 */
commandResult = await redisClient.ttl('mykey');

console.log("TTL of 'mykey': " + commandResult);


/**
 * Set value with expire time - the following commands are for checking "KEEPTTL" option
 * 
 * Command: set user:10 "John Doe" ex 360
 * Result: OK
 */
commandResult = await redisClient.set('user:10', 'John Doe', {EX: 360});

console.log(`key: 'user:10', value: 'John Doe', including 'EX'=360 - set result: ${commandResult}`);


/**
 * Command: ttl user:10
 * Result: (integer) 360
 */
commandResult = await redisClient.ttl('user:10');

console.log("TTL of 'user:10': " + commandResult);


/**
 * Set value for the same key, and pass "KEEPTTL" option. This will keep the TTL that was associated with the key
 * 
 * Command: set user:10 "Some user" keepttl
 * Result: OK
 */
commandResult = await redisClient.set('user:10', 'Some user', {KEEPTTL: true});

console.log(`key: 'user:10', value: 'Some user', including 'KEEPTTL' - set result: ${commandResult}`);

/**
 * Lets check the TTL. The TTL still exists because of usign the "KEEPTTL" option
 * 
 * Command: ttl user:10
 * Result: (integer) 360
 */
commandResult = await redisClient.ttl('user:10');

console.log("TTL of 'user:10': " + commandResult);


process.exit(0);

Output:

key: 'firstkey', value: 'abcdef' - set result: OK
'firstkey' get result: abcdef

key: 'firstkey', value: 'abcdef' - set result: OK
'firstkey' get result: defghi

key: 'secondkey', value: '000000000000', including 'XX' - set result: null
'secondkey' get result: null

key: 'secondkey', value: '000000000000', including 'NX' - set result: OK
'secondkey' get result: 000000000000

key: 'firstkey', value: 'work idea', including 'NX' - set result: null
'firstkey' get result: defghi

key: 'thirdkey', value: '1111111111', including 'GET' - set result: null

key: 'thirdkey', value: '99999999', including 'GET' - set result: 1111111111

key: 'fourthkey', value: 'some value for expire', including 'EX'=120 - set result: OK
TTL of 'fourthkey': 120

key: 'mykey', value: 'some val', including 'EX'=360 - set result: OK
TTL of 'mykey': 360

key: 'mykey', value: 'changed value' - set result: OK
TTL of 'mykey': -1

key: 'user:10', value: 'John Doe', including 'EX'=360 - set result: OK
TTL of 'user:10': 360

key: 'user:10', value: 'Some user', including 'KEEPTTL' - set result: OK
TTL of 'user:10': 360

Notes

  • The package used for this implementation is “redis“.
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.params.SetParams;

public class Set {
    public static void main(String[] args) {
        // Create connection pool
        JedisPool pool = new JedisPool("localhost", 6379);

        try (Jedis jedis = pool.getResource()) {
            /**
             * Set value for a key
             *
             * Command: set firstkey "abcdef"
             * Result: OK
             */
            String commandResult = jedis.set("firstkey", "abcdef");

            System.out.println("Command: set firstkey "abcdef" | Result: " + commandResult);


            /**
             * Command: get firstkey
             * Result: "abcdef"
             */
            commandResult = jedis.get("firstkey");

            System.out.println("Command: get firstkey | Result: " + commandResult);


            /**
             * Set value for the same key again. The new value is set for the key
             *
             * Command: set firstkey defghi
             * Result: OK
             */
            commandResult = jedis.set("firstkey", "defghi");

            System.out.println("Command: set firstkey defghi | Result: " + commandResult);


            /**
             * Command: get firstkey
             * Result: "defghi"
             */
            commandResult = jedis.get("firstkey");

            System.out.println("Command: get firstkey | Result: " + commandResult);


            /**
             * Use "XX" option to set value only if the key already exists
             *
             * Command: set secondkey "000000000000" XX
             * Result: (nil)
             */
            commandResult = jedis.set("secondkey", "000000000000", SetParams.setParams().xx());

            System.out.println("Command: set secondkey "000000000000" XX | Result: " + commandResult);


            /**
             * secondkey is not set in this case as it was not preexisting
             *
             * Command: get secondkey
             * Result: (nil)
             */
            commandResult = jedis.get("secondkey");

            System.out.println("Command: get secondkey | Result: " + commandResult);


            /**
             * Use "NX" option to set value if the key does not exist
             *
             * Command: set secondkey "000000000000" NX
             * Result: OK
             */
            commandResult = jedis.set("secondkey", "000000000000", SetParams.setParams().nx());

            System.out.println("Command: set secondkey "000000000000" NX | Result: " + commandResult);


            /**
             * secondkey is set as it was not pre-existing
             *
             * Command: get secondkey
             * Result: "000000000000"
             */
            commandResult = jedis.get("secondkey");

            System.out.println("Command: get secondkey | Result: " + commandResult);


            /**
             * Use "NX" for an existing key, that returns nil
             *
             * Command: set firstkey "work idea" NX
             * Result: (nil)
             */
            commandResult = jedis.set("firstkey", "work idea", SetParams.setParams().nx());

            System.out.println("Command: set firstkey "work idea" NX | Result: " + commandResult);


            /**
             * Command: get firstkey
             * Result: "defghi"
             */
            commandResult = jedis.get("firstkey");

            System.out.println("Command: get firstkey | Result: " + commandResult);


            /**
             * Pass the "GET" option to get the previous value.
             * If the value was not set previously then we get nil
             *
             * Command: set thirdkey 1111111111 GET
             * Result: (nil)
             */
            commandResult = jedis.set("thirdkey", "1111111111", SetParams.setParams());

            System.out.println("Command: set thirdkey 1111111111 GET | Result: " + commandResult);


            /**
             * Pass "GET" to fetch the previous value before setting new value
             *
             * Command: set thirdkey 99999999 GET
             * Result: "1111111111"
             */
            commandResult = jedis.setGet("thirdkey", "99999999");

            System.out.println("Command: set thirdkey 99999999 GET | Result: " + commandResult);


            /**
             * Set expire time in seconds using "EX" option (other expire duration related options work the same way)
             *
             * Command: set fourthkey "some value for expire" EX 120
             * Result: OK
             */
            commandResult = jedis.set("fourthkey", "some value for expire", SetParams.setParams().ex(120));

            System.out.println("Command: set fourthkey "some value for expire" EX 120 | Result: " + commandResult);


            /**
             * Command: ttl fourthkey
             * Result: (integer) 120
             */
            long ttl = jedis.ttl("fourthkey");

            System.out.println("Command: ttl fourthkey | Result: " + ttl);


            /**
             * Set expire time
             *
             * Command: set mykey "some val" ex 360
             * Result: OK
             */
            commandResult = jedis.set("mykey", "some val", SetParams.setParams().ex(360));

            System.out.println("Command: set mykey "some val" ex 360 | Result: " + commandResult);


            /**
             * Command: ttl mykey
             * Result: (integer) 360
             */
            ttl = jedis.ttl("mykey");

            System.out.println("Command: ttl mykey | Result: " + ttl);


            /**
             * Setting already existing key will remove the TTL if there is any
             *
             * Command: set mykey "changed value"
             * Result: OK
             */
            commandResult = jedis.set("mykey", "changed value");

            System.out.println("Command: set mykey "changed value" | Result: " + commandResult);


            /**
             * TTL was removed as the value was set the second time without any expire time
             *
             * Command: ttl mykey
             * Result: (integer) -1
             */
            ttl = jedis.ttl("mykey");

            System.out.println("Command: ttl mykey | Result: " + ttl);


            /**
             * Set value with expire time - the following commands are for checking "KEEPTTL" option
             *
             * Command: set user:10 "John Doe" ex 360
             * Result: OK
             */
            commandResult = jedis.set("user:10", "John Doe", SetParams.setParams().ex(360));

            System.out.println("Command: set user:10 "John Doe" ex 360 | Result: " + commandResult);


            /**
             * Command: ttl user:10
             * Result: (integer) 360
             */
            ttl = jedis.ttl("user:10");

            System.out.println("Command: ttl user:10 | Result: " + ttl);


            /**
             * Set value for the same key, and pass "KEEPTTL" option. This will keep the TTL that was associated with the key
             *
             * Command: set user:10 "Some user" keepttl
             * Result: OK
             */
            commandResult = jedis.set("user:10", "Some user", SetParams.setParams().keepTtl());

            System.out.println("Command: set user:10 "Some user" keepttl | Result: " + commandResult);


            /**
             * Lets check the TTL. The TTL still exists because of usign the "KEEPTTL" option
             *
             * Command: ttl user:10
             * Result: (integer) 360
             */
            ttl = jedis.ttl("user:10");

            System.out.println("Command: ttl user:10 | Result: " + ttl);

        }

        pool.close();
    }
}

Output:

Command: set firstkey "abcdef" | Result: OK
Command: get firstkey | Result: abcdef

Command: set firstkey defghi | Result: OK
Command: get firstkey | Result: defghi

Command: set secondkey "000000000000" XX | Result: null
Command: get secondkey | Result: null

Command: set secondkey "000000000000" NX | Result: OK
Command: get secondkey | Result: 000000000000

Command: set firstkey "work idea" NX | Result: null
Command: get firstkey | Result: defghi

Command: set thirdkey 1111111111 GET | Result: OK

Command: set thirdkey 99999999 GET | Result: 1111111111

Command: set fourthkey "some value for expire" EX 120 | Result: OK
Command: ttl fourthkey | Result: 120

Command: set mykey "some val" ex 360 | Result: OK
Command: ttl mykey | Result: 360

Command: set mykey "changed value" | Result: OK
Command: ttl mykey | Result: -1

Command: set user:10 "John Doe" ex 360 | Result: OK
Command: ttl user:10 | Result: 360

Command: set user:10 "Some user" keepttl | Result: OK
Command: ttl user:10 | Result: 360

Notes

  • The package used for this implementation is “Jedis“.
// Redis SET command examples in C#

using StackExchange.Redis;

namespace Set
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
            IDatabase rdb = redis.GetDatabase();


            /**
             * Set value for a key
             *
             * Command: set firstkey "abcdef"
             * Result: OK
             */
            var setCommandResult = rdb.StringSet("firstkey", "abcdef");

            Console.WriteLine("Command: set firstkey "abcdef" | Result: " + setCommandResult);


            /**
             * Command: get firstkey
             * Result: "abcdef"
             */
            var getCommandResult = rdb.StringGet("firstkey");

            Console.WriteLine("Command: get firstkey | Result: " + getCommandResult);


            /**
             * Set value for the same key again. The new value is set for the key
             *
             * Command: set firstkey defghi
             * Result: OK
             */
            setCommandResult = rdb.StringSet("firstkey", "defghi");

            Console.WriteLine("Command: set firstkey defghi | Result: " + setCommandResult);


            /**
             * Command: get firstkey
             * Result: "defghi"
             */
            getCommandResult = rdb.StringGet("firstkey");

            Console.WriteLine("Command: get firstkey | Result: " + getCommandResult);


            /**
             * Use "XX" option to set value only if the key already exists
             *
             * Command: set secondkey "000000000000" XX
             * Result: (nil)
             */
            setCommandResult = rdb.StringSet("secondkey", "000000000000", when: When.Exists);

            Console.WriteLine("Command: set secondkey "000000000000" XX | Result: " + setCommandResult);


            /**
             * secondkey is not set in this case as it was not preexisting
             *
             * Command: get secondkey
             * Result: (nil)
             */
            getCommandResult = rdb.StringGet("secondkey");

            Console.WriteLine("Command: get secondkey | Result: " + getCommandResult);


            /**
             * Use "NX" option to set value if the key does not exist
             *
             * Command: set secondkey "000000000000" NX
             * Result: OK
             */
            setCommandResult = rdb.StringSet("secondkey", "000000000000", when: When.NotExists);

            Console.WriteLine("Command: set secondkey "000000000000" NX | Result: " + setCommandResult);


            /**
             * secondkey is set as it was not pre-existing
             *
             * Command: get secondkey
             * Result: "000000000000"
             */
            getCommandResult = rdb.StringGet("secondkey");

            Console.WriteLine("Command: get secondkey | Result: " + getCommandResult);


            /**
             * Use "NX" for an existing key, that returns nil
             *
             * Command: set firstkey "work idea" NX
             * Result: (nil)
             */
            setCommandResult = rdb.StringSet("firstkey", "work idea", when: When.NotExists);

            Console.WriteLine("Command: set firstkey "work idea" NX | Result: " + setCommandResult);


            /**
             * Command: get firstkey
             * Result: "defghi"
             */
            getCommandResult = rdb.StringGet("firstkey");

            Console.WriteLine("Command: get firstkey | Result: " + getCommandResult);


            /**
             * Pass the "GET" option to get the previous value.
             * If the value was not set previously then we get nil
             *
             * Command: set thirdkey 1111111111 GET
             * Result: (nil)
             */
            getCommandResult = rdb.StringSetAndGet("thirdkey", "1111111111");

            Console.WriteLine("Command: set thirdkey 1111111111 GET | Result: " + getCommandResult);


            /**
             * Pass "GET" to fetch the previous value before setting new value
             *
             * Command: set thirdkey 99999999 GET
             * Result: "1111111111"
             */
            getCommandResult = rdb.StringSetAndGet("thirdkey", "99999999");

            Console.WriteLine("Command: set thirdkey 99999999 GET | Result: " + getCommandResult);


            /**
             * Set expire time in seconds using "EX" option (other expire duration related options work the same way)
             *
             * Command: set fourthkey "some value for expire" EX 120
             * Result: OK
             */
            setCommandResult = rdb.StringSet("fourthkey", "some value for expire", new TimeSpan(0, 0, 120));

            Console.WriteLine("Command: set fourthkey "some value for expire" EX 120 | Result: " + setCommandResult);


            /**
             * Command: ttl fourthkey
             * Result: (integer) 120
             */
            var ttl = rdb.KeyTimeToLive("fourthkey");

            Console.WriteLine("Command: ttl fourthkey | Result: " + ttl);


            /**
             * Set expire time
             *
             * Command: set mykey "some val" ex 360
             * Result: OK
             */
            setCommandResult = rdb.StringSet("mykey", "some val", new TimeSpan(0, 0, 360));

            Console.WriteLine("Command: set mykey "some val" ex 360 | Result: " + setCommandResult);


            /**
             * Command: ttl mykey
             * Result: (integer) 360
             */
            ttl = rdb.KeyTimeToLive("mykey");

            Console.WriteLine("Command: ttl mykey | Result: " + ttl);


            /**
             * Setting already existing key will remove the TTL if there is any
             *
             * Command: set mykey "changed value"
             * Result: OK
             */
            setCommandResult = rdb.StringSet("mykey", "changed value");

            Console.WriteLine("Command: set mykey "changed value" | Result: " + setCommandResult);


            /**
             * TTL was removed as the value was set the second time without any expire time
             *
             * Command: ttl mykey
             * Result: (integer) -1
             */
            ttl = rdb.KeyTimeToLive("mykey");

            Console.WriteLine("Command: ttl mykey | Result: " + ttl);


            /**
             * Set value with expire time - the following commands are for checking "KEEPTTL" option
             *
             * Command: set user:10 "John Doe" ex 360
             * Result: OK
             */
            setCommandResult = rdb.StringSet("user:10", "John Doe", new TimeSpan(0, 0, 360));

            Console.WriteLine("Command: set user:10 "John Doe" ex 360 | Result: " + setCommandResult);


            /**
             * Command: ttl user:10
             * Result: (integer) 360
             */
            ttl = rdb.KeyTimeToLive("user:10");

            Console.WriteLine("Command: ttl user:10 | Result: " + ttl);


            /**
             * Set value for the same key, and pass "KEEPTTL" option. This will keep the TTL that was associated with the key
             *
             * Command: set user:10 "Some user" keepttl
             * Result: OK
             */
            setCommandResult = rdb.StringSet("user:10", "Some user", keepTtl: true);

            Console.WriteLine("Command: set user:10 "Some user" keepttl | Result: " + setCommandResult);


            /**
             * Lets check the TTL. The TTL still exists because of usign the "KEEPTTL" option
             *
             * Command: ttl user:10
             * Result: (integer) 360
             */
            ttl = rdb.KeyTimeToLive("user:10");

            Console.WriteLine("Command: ttl user:10 | Result: " + ttl);
        }
    }
}

Output:

Command: set firstkey "abcdef" | Result: True
Command: get firstkey | Result: abcdef

Command: set firstkey defghi | Result: True
Command: get firstkey | Result: defghi

Command: set secondkey "000000000000" XX | Result: False
Command: get secondkey | Result:

Command: set secondkey "000000000000" NX | Result: True
Command: get secondkey | Result: 000000000000

Command: set firstkey "work idea" NX | Result: False
Command: get firstkey | Result: defghi

Command: set thirdkey 1111111111 GET | Result:

Command: set thirdkey 99999999 GET | Result: 1111111111

Command: set fourthkey "some value for expire" EX 120 | Result: True
Command: ttl fourthkey | Result: 00:01:59.9940000

Command: set mykey "some val" ex 360 | Result: True
Command: ttl mykey | Result: 00:05:59.9990000

Command: set mykey "changed value" | Result: True
Command: ttl mykey | Result:

Command: set user:10 "John Doe" ex 360 | Result: True
Command: ttl user:10 | Result: 00:05:59.9980000

Command: set user:10 "Some user" keepttl | Result: True
Command: ttl user:10 | Result: 00:05:59.9950000

Notes

  • Use the method “StringSet” of the package StackExchange.Redis for using the Redis SET command.
<?php
// Redis SET command example in PHP

require 'vendor/autoload.php';

// Connect to Redis
$redisClient = new PredisClient([
    'scheme' => 'tcp',
    'host'   => 'localhost',
    'port'   => 6379,
]);


/**
 * Set value for a key
 * 
 * Command: set firstkey "abcdef"
 * Result: OK
 */ 
$commandResult = $redisClient->set('firstkey', 'abcdef');

echo "key: 'firstkey', value: 'abcdef' - set result: " . $commandResult . "n";


/**
 * Command: get firstkey
 * Result: "abcdef"
 */
$commandResult = $redisClient->get('firstkey');

echo "'firstkey' get result: " . $commandResult . "n";


/**
 * Set value for the same key again. The new value is set for the key
 * 
 * Command: set firstkey defghi
 * Result: OK
 */
$commandResult = $redisClient->set('firstkey', 'defghi');

echo "key: 'firstkey', value: 'abcdef' - set result: " . $commandResult . "n";


/**
 * Command: get firstkey
 * Result: "defghi"
 */
$commandResult = $redisClient->get('firstkey');

echo "'firstkey' get result: " . $commandResult . "n";

/**
 * Use "XX" option to set value only if the key already exists
 * 
 * Command: set secondkey "000000000000" XX
 * Result: (nil)
 */
$commandResult = $redisClient->set('secondkey', '000000000000', 'XX');

echo "key: 'secondkey', value: '000000000000', including 'XX' - set result: " . $commandResult . "n";


/**
 * secondkey is not set in this case as it was not preexisting
 * 
 * Command: get secondkey
 * Result: (nil)
 */
$commandResult = $redisClient->get('secondkey');

echo "'secondkey' get result: " . $commandResult . "n";

/**
 * Use "NX" option to set value if the key does not exist
 * 
 * Command: set secondkey "000000000000" NX
 * Result: OK
 */
$commandResult = $redisClient->set('secondkey', '000000000000', 'NX');

echo "key: 'secondkey', value: '000000000000', including 'NX' - set result: " . $commandResult . "n";


/**
 * secondkey is set as it was not pre-existing
 * 
 * Command: get secondkey
 * Result: "000000000000"
 */
$commandResult = $redisClient->get('secondkey');

echo "'secondkey' get result: " . $commandResult . "n";


/**
 * Use "NX" for an existing key, that returns nil
 * 
 * Command: set firstkey "work idea" NX
 * Result: (nil)
 */
$commandResult = $redisClient->set('firstkey', 'work idea', 'NX');

echo "key: 'firstkey', value: 'work idea', including 'NX' - set result: " . $commandResult . "n";


/**
 * Command: get firstkey
 * Result: "defghi"
 */
$commandResult = $redisClient->get('firstkey');

echo "'firstkey' get result: " . $commandResult . "n";


/**
 * Pass the "GET" option to get the previous value.
 * If the value was not set previously then we get nil
 * 
 * Command: set thirdkey 1111111111 GET
 * Result: (nil)
 */
$commandResult = $redisClient->set('thirdkey', '1111111111', 'GET');

echo "key: 'thirdkey', value: '1111111111', including 'GET' - set result: " . $commandResult . "n";


/**
 * Pass "GET" to fetch the previous value before setting new value
 * 
 * Command: set thirdkey 99999999 GET
 * Result: "1111111111"
 */
$commandResult = $redisClient->set('thirdkey', '99999999', 'GET');

echo "key: 'thirdkey', value: '99999999', including 'GET' - set result: " . $commandResult . "n";


/**
 * Set expire time in seconds using "EX" option (other expire duration related options work the same way)
 * 
 * Command: set fourthkey "some value for expire" EX 120
 * Result: OK
 */
$commandResult = $redisClient->set('fourthkey', 'some value for expire', 'EX', 120);

echo "key: 'fourthkey', value: 'some value for expire', including 'EX'=120 - set result: " . $commandResult . "n";


/**
 * Command: ttl fourthkey
 * Result: (integer) 120
 */
$commandResult = $redisClient->ttl('fourthkey');

echo "TTL of 'fourthkey': " . $commandResult . "n";

/**
 * Set expire time
 * 
 * Command: set mykey "some val" ex 360
 * Result: OK
 */
$commandResult = $redisClient->set('mykey', 'some val', 'EX', 360);

echo "key: 'mykey', value: 'some val', including 'EX'=360 - set result: " . $commandResult . "n";


/**
 * Command: ttl mykey
 * Result: (integer) 360
 */
$commandResult = $redisClient->ttl('mykey');

echo "TTL of 'mykey': " . $commandResult . "n";


/**
 * Setting already existing key will remove the TTL if there is any
 * 
 * Command: set mykey "changed value"
 * Result: OK
 */
$commandResult = $redisClient->set('mykey', 'changed value');

echo "key: 'mykey', value: 'changed value' - set result: " . $commandResult . "n";


/**
 * TTL was removed as the value was set the second time without any expire time
 * 
 * Command: ttl mykey
 * Result: (integer) -1
 */
$commandResult = $redisClient->ttl('mykey');

echo "TTL of 'mykey': " . $commandResult . "n";


/**
 * Set value with expire time - the following commands are for checking "KEEPTTL" option
 * 
 * Command: set user:10 "John Doe" ex 360
 * Result: OK
 */
$commandResult = $redisClient->set('user:10', 'John Doe', 'EX', 360);

echo "key: 'user:10', value: 'John Doe', including 'EX'=360 - set result: " . $commandResult . "n";


/**
 * Command: ttl user:10
 * Result: (integer) 360
 */
$commandResult = $redisClient->ttl('user:10');

echo "TTL of 'user:10': " . $commandResult . "n";


/**
 * Set value for the same key, and pass "KEEPTTL" option. This will keep the TTL that was associated with the key
 * 
 * Command: set user:10 "Some user" keepttl
 * Result: OK
 */
$commandResult = $redisClient->set('user:10', 'Some user', 'KEEPTTL');

echo "key: 'user:10', value: 'Some user', including 'KEEPTTL' - set result: " . $commandResult . "n";

/**
 * Lets check the TTL. The TTL still exists because of usign the "KEEPTTL" option
 * 
 * Command: ttl user:10
 * Result: (integer) 360
 */
$commandResult = $redisClient->ttl('user:10');

echo "TTL of 'user:10': " . $commandResult . "n";

Output:

key: 'firstkey', value: 'abcdef' - set result: OK
'firstkey' get result: abcdef

key: 'firstkey', value: 'abcdef' - set result: OK
'firstkey' get result: defghi

key: 'secondkey', value: '000000000000', including 'XX' - set result:
'secondkey' get result:

key: 'secondkey', value: '000000000000', including 'NX' - set result: OK
'secondkey' get result: 000000000000

key: 'firstkey', value: 'work idea', including 'NX' - set result:
'firstkey' get result: defghi

key: 'thirdkey', value: '1111111111', including 'GET' - set result:

key: 'thirdkey', value: '99999999', including 'GET' - set result: 1111111111

key: 'fourthkey', value: 'some value for expire', including 'EX'=120 - set result: OK
TTL of 'fourthkey': 120

key: 'mykey', value: 'some val', including 'EX'=360 - set result: OK
TTL of 'mykey': 360

key: 'mykey', value: 'changed value' - set result: OK
TTL of 'mykey': -1

key: 'user:10', value: 'John Doe', including 'EX'=360 - set result: OK
TTL of 'user:10': 

360key: 'user:10', value: 'Some user', including 'KEEPTTL' - set result: OK
TTL of 'user:10': 360

Notes

  • The package used for this implementation is “Predis“.
# Redis SET command example in Python

import redis

# Create Redis client
redisClient = redis.Redis(host='localhost', port=6379, username='default', password='', decode_responses=True)

# Set value for a key
# Command: set firstkey "abcdef"
# Result: OK
commandResult = redisClient.set('firstkey', 'abcdef')

print("key: 'firstkey', value: 'abcdef' - set result: {}".format(commandResult))

# Command: get firstkey
# Result: "abcdef"
commandResult = redisClient.get('firstkey')

print("'firstkey' get result: {}".format(commandResult))


# Set value for the same key again. The new value is set for the key
# Command: set firstkey defghi
# Result: OK
commandResult = redisClient.set('firstkey', 'defghi')

print("key: 'firstkey', value: 'abcdef' - set result: {}".format(commandResult))


# Command: get firstkey
# Result: "defghi"
commandResult = redisClient.get('firstkey')

print("'firstkey' get result: {}".format(commandResult))


# Use "XX" option to set value only if the key already exists
# Command: set secondkey "000000000000" XX
# Result: (nil)
commandResult = redisClient.set('secondkey', '000000000000', xx = True)

print("key: 'secondkey', value: '000000000000', including 'XX' - set result: {}".format(commandResult))


# secondkey is not set in this case as it was not preexisting
# Command: get secondkey
# Result: (nil)
commandResult = redisClient.get('secondkey')

print("'secondkey' get result: {}".format(commandResult))


# Use "NX" option to set value if the key does not exist
# Command: set secondkey "000000000000" NX
# Result: OK
commandResult = redisClient.set('secondkey', '000000000000', nx=True)

print("key: 'secondkey', value: '000000000000', including 'NX' - set result: {}".format(commandResult))


# secondkey is set as it was not pre-existing
# Command: get secondkey
# Result: "000000000000"
commandResult = redisClient.get('secondkey')

print("'secondkey' get result: {}".format(commandResult))


# Use "NX" for an existing key, that returns nil
# Command: set firstkey "work idea" NX
# Result: (nil)
commandResult = redisClient.set('firstkey', 'work idea', nx=True)

print("key: 'firstkey', value: 'work idea', including 'NX' - set result: {}".format(commandResult))


# Command: get firstkey
# Result: "defghi"
commandResult = redisClient.get('firstkey')

print("'firstkey' get result: {}".format(commandResult))


# Pass the "GET" option to get the previous value.
# If the value was not set previously then we get nil
# Command: set thirdkey 1111111111 GET
# Result: (nil)
commandResult = redisClient.set('thirdkey', '1111111111', get=True)

print("key: 'thirdkey', value: '1111111111', including 'GET' - set result: {}".format(commandResult))


# Pass "GET" to fetch the previous value before setting new value
# Command: set thirdkey 99999999 GET
# Result: "1111111111"
commandResult = redisClient.set('thirdkey', '99999999', get=True)

print("key: 'thirdkey', value: '99999999', including 'GET' - set result: {}".format(commandResult))


# Set expire time in seconds using "EX" option (other expire duration related options work the same way)
# Command: set fourthkey "some value for expire" EX 120
# Result: OK
commandResult = redisClient.set('fourthkey', 'some value for expire', ex=120)

print("key: 'fourthkey', value: 'some value for expire', including 'EX'=120 - set result: {}".format(commandResult))


# Command: ttl fourthkey
# Result: (integer) 120
commandResult = redisClient.ttl('fourthkey')

print("TTL of 'fourthkey': {}".format(commandResult))


# Set expire time
# Command: set mykey "some val" ex 360
# Result: OK
commandResult = redisClient.set('mykey', 'some val', ex=360)

print("key: 'mykey', value: 'some val', including 'EX'=360 - set result: {}".format(commandResult))


# Command: ttl mykey
# Result: (integer) 360
commandResult = redisClient.ttl('mykey')

print("TTL of 'mykey': {}".format(commandResult)) 


# Setting already existing key will remove the TTL if there is any
# Command: set mykey "changed value"
# Result: OK
commandResult = redisClient.set('mykey', 'changed value')

print("key: 'mykey', value: 'changed value' - set result: {}".format(commandResult))


# TTL was removed as the value was set the second time without any expire time
# Command: ttl mykey
# Result: (integer) -1
commandResult = redisClient.ttl('mykey')

print("TTL of 'mykey': {}".format(commandResult)) 


# Set value with expire time - the following commands are for checking "KEEPTTL" option
# Command: set user:10 "John Doe" ex 360
# Result: OK
commandResult = redisClient.set('user:10', 'John Doe', ex=360)

print("key: 'user:10', value: 'John Doe', including 'EX'=360 - set result: {}".format(commandResult)) 


# Command: ttl user:10
# Result: (integer) 360
commandResult = redisClient.ttl('user:10')

print("TTL of 'user:10': {}".format(commandResult)) 


# Set value for the same key, and pass "KEEPTTL" option. This will keep the TTL that was associated with the key
# Command: set user:10 "Some user" keepttl
# Result: OK
commandResult = redisClient.set('user:10', 'Some user', keepttl=True)

print("key: 'user:10', value: 'Some user', including 'KEEPTTL' - set result: {}".format(commandResult)) 


# Lets check the TTL. The TTL still exists because of usign the "KEEPTTL" option
# Command: ttl user:10
# Result: (integer) 360
commandResult = redisClient.ttl('user:10')

print("TTL of 'user:10': {}".format(commandResult))

Output:

import redis

# Create Redis client
redisClient = redis.Redis(host='localhost', port=6379, username='default', password='', decode_responses=True)

# Set value for a key
# Command: set firstkey "abcdef"
# Result: OK
commandResult = redisClient.set('firstkey', 'abcdef')

print("key: 'firstkey', value: 'abcdef' - set result: {}".format(commandResult))

# Command: get firstkey
# Result: "abcdef"
commandResult = redisClient.get('firstkey')

print("'firstkey' get result: {}".format(commandResult))


# Set value for the same key again. The new value is set for the key
# Command: set firstkey defghi
# Result: OK
commandResult = redisClient.set('firstkey', 'defghi')

print("key: 'firstkey', value: 'abcdef' - set result: {}".format(commandResult))


# Command: get firstkey
# Result: "defghi"
commandResult = redisClient.get('firstkey')

print("'firstkey' get result: {}".format(commandResult))


# Use "XX" option to set value only if the key already exists
# Command: set secondkey "000000000000" XX
# Result: (nil)
commandResult = redisClient.set('secondkey', '000000000000', xx = True)

print("key: 'secondkey', value: '000000000000', including 'XX' - set result: {}".format(commandResult))


# secondkey is not set in this case as it was not preexisting
# Command: get secondkey
# Result: (nil)
commandResult = redisClient.get('secondkey')

print("'secondkey' get result: {}".format(commandResult))


# Use "NX" option to set value if the key does not exist
# Command: set secondkey "000000000000" NX
# Result: OK
commandResult = redisClient.set('secondkey', '000000000000', nx=True)

print("key: 'secondkey', value: '000000000000', including 'NX' - set result: {}".format(commandResult))


# secondkey is set as it was not pre-existing
# Command: get secondkey
# Result: "000000000000"
commandResult = redisClient.get('secondkey')

print("'secondkey' get result: {}".format(commandResult))


# Use "NX" for an existing key, that returns nil
# Command: set firstkey "work idea" NX
# Result: (nil)
commandResult = redisClient.set('firstkey', 'work idea', nx=True)

print("key: 'firstkey', value: 'work idea', including 'NX' - set result: {}".format(commandResult))


# Command: get firstkey
# Result: "defghi"
commandResult = redisClient.get('firstkey')

print("'firstkey' get result: {}".format(commandResult))


# Pass the "GET" option to get the previous value.
# If the value was not set previously then we get nil
# Command: set thirdkey 1111111111 GET
# Result: (nil)
commandResult = redisClient.set('thirdkey', '1111111111', get=True)

print("key: 'thirdkey', value: '1111111111', including 'GET' - set result: {}".format(commandResult))


# Pass "GET" to fetch the previous value before setting new value
# Command: set thirdkey 99999999 GET
# Result: "1111111111"
commandResult = redisClient.set('thirdkey', '99999999', get=True)

print("key: 'thirdkey', value: '99999999', including 'GET' - set result: {}".format(commandResult))


# Set expire time in seconds using "EX" option (other expire duration related options work the same way)
# Command: set fourthkey "some value for expire" EX 120
# Result: OK
commandResult = redisClient.set('fourthkey', 'some value for expire', ex=120)

print("key: 'fourthkey', value: 'some value for expire', including 'EX'=120 - set result: {}".format(commandResult))


# Command: ttl fourthkey
# Result: (integer) 120
commandResult = redisClient.ttl('fourthkey')

print("TTL of 'fourthkey': {}".format(commandResult))


# Set expire time
# Command: set mykey "some val" ex 360
# Result: OK
commandResult = redisClient.set('mykey', 'some val', ex=360)

print("key: 'mykey', value: 'some val', including 'EX'=360 - set result: {}".format(commandResult))


# Command: ttl mykey
# Result: (integer) 360
commandResult = redisClient.ttl('mykey')

print("TTL of 'mykey': {}".format(commandResult)) 


# Setting already existing key will remove the TTL if there is any
# Command: set mykey "changed value"
# Result: OK
commandResult = redisClient.set('mykey', 'changed value')

print("key: 'mykey', value: 'changed value' - set result: {}".format(commandResult))


# TTL was removed as the value was set the second time without any expire time
# Command: ttl mykey
# Result: (integer) -1
commandResult = redisClient.ttl('mykey')

print("TTL of 'mykey': {}".format(commandResult)) 


# Set value with expire time - the following commands are for checking "KEEPTTL" option
# Command: set user:10 "John Doe" ex 360
# Result: OK
commandResult = redisClient.set('user:10', 'John Doe', ex=360)

print("key: 'user:10', value: 'John Doe', including 'EX'=360 - set result: {}".format(commandResult)) 


# Command: ttl user:10
# Result: (integer) 360
commandResult = redisClient.ttl('user:10')

print("TTL of 'user:10': {}".format(commandResult)) 


# Set value for the same key, and pass "KEEPTTL" option. This will keep the TTL that was associated with the key
# Command: set user:10 "Some user" keepttl
# Result: OK
commandResult = redisClient.set('user:10', 'Some user', keepttl=True)

print("key: 'user:10', value: 'Some user', including 'KEEPTTL' - set result: {}".format(commandResult)) 


# Lets check the TTL. The TTL still exists because of usign the "KEEPTTL" option
# Command: ttl user:10
# Result: (integer) 360
commandResult = redisClient.ttl('user:10')

print("TTL of 'user:10': {}".format(commandResult))

Notes

  • The package used for this implementation is “redis“.
# Redis SET command example in Ruby

require 'redis'

redis = Redis.new(host: "localhost", port: 6379)


# Set value for a key
# Command: set firstkey "abcdef"
# Result: OK
commandResult = redis.set('firstkey', 'abcdef')

print("Command: set firstkey "abcdef" | Result: ", commandResult, "n")


# Command: get firstkey
# Result: "abcdef"
commandResult = redis.get('firstkey')

print("Command: get firstkey | Result: ", commandResult, "n")


# Set value for the same key again. The new value is set for the key
# Command: set firstkey defghi
# Result: OK
commandResult = redis.set('firstkey', 'defghi')

print("Command: set firstkey defghi | Result: ", commandResult, "n")


# Command: get firstkey
# Result: "defghi"
commandResult = redis.get('firstkey')

print("Command: get firstkey | Result: ", commandResult, "n")


# Use "XX" option to set value only if the key already exists
# Command: set secondkey "000000000000" XX
# Result: (nil)
commandResult = redis.set('secondkey', '000000000000', xx: true)

print("Command: set secondkey "000000000000" XX | Result: ", commandResult, "n")


# secondkey is not set in this case as it was not preexisting
# Command: get secondkey
# Result: (nil)
commandResult = redis.get('secondkey')

print("Command: get secondkey | Result: ", commandResult, "n")


# Use "NX" option to set value if the key does not exist
# Command: set secondkey "000000000000" NX
# Result: OK
commandResult = redis.set('secondkey', '000000000000', nx: true)

print("Command: set secondkey "000000000000" NX | Result: ", commandResult, "n")


# secondkey is set as it was not pre-existing
# Command: get secondkey
# Result: "000000000000"
commandResult = redis.get('secondkey')

print("Command: get secondkey | Result: ", commandResult, "n")


# Use "NX" for an existing key, that returns nil
# Command: set firstkey "work idea" NX
# Result: (nil)
commandResult = redis.set('firstkey', 'work idea', nx:true)

print("Command: set firstkey "work idea" NX | Result: ", commandResult, "n")


# Command: get firstkey
# Result: "defghi"
commandResult = redis.get('firstkey')

print("Command: get firstkey | Result: ", commandResult, "n")


# Pass the "GET" option to get the previous value.
# If the value was not set previously then we get nil
# Command: set thirdkey 1111111111 GET
# Result: (nil)
commandResult = redis.set('thirdkey', '1111111111', get: true)

print("Command: set thirdkey 1111111111 GET | Result: ", commandResult, "n")


# Pass "GET" to fetch the previous value before setting new value
# Command: set thirdkey 99999999 GET
# Result: "1111111111"
commandResult = redis.set('thirdkey', '99999999', get: true)

print("Command: set thirdkey 99999999 GET | Result: ", commandResult, "n")


# Set expire time in seconds using "EX" option (other expire duration related options work the same way)
# Command: set fourthkey "some value for expire" EX 120
# Result: OK
commandResult = redis.set('fourthkey', 'some value for expire', ex: 120)

print("Command: set fourthkey "some value for expire" EX 120 | Result: ", commandResult, "n")


# Command: ttl fourthkey
# Result: (integer) 120
commandResult = redis.ttl('fourthkey')

print("Command: ttl fourthkey | Result: ", commandResult, "n")


# Set expire time
# Command: set mykey "some val" ex 360
# Result: OK
commandResult = redis.set('mykey', 'some val', ex: 360)

print("Command: set mykey "some val" ex 360 | Result: ", commandResult, "n")


# Command: ttl mykey
# Result: (integer) 360
commandResult = redis.ttl('mykey')

print("Command: ttl mykey | Result ", commandResult, "n")


# Setting already existing key will remove the TTL if there is any
# Command: set mykey "changed value"
# Result: OK
commandResult = redis.set('mykey', 'changed value')

print("Command: set mykey "changed value" | Result: ", commandResult, "n")


# TTL was removed as the value was set the second time without any expire time
# Command: ttl mykey
# Result: (integer) -1
commandResult = redis.ttl('mykey')

print("Command: ttl mykey | Result: ", commandResult, "n")


# Set value with expire time - the following commands are for checking "KEEPTTL" option
# Command: set user:10 "John Doe" ex 360
# Result: OK
commandResult = redis.set('user:10', 'John Doe', ex: 360)

print("Command: set user:10 "John Doe" ex 360 | Result: ", commandResult, "n")


# Command: ttl user:10
# Result: (integer) 360
commandResult = redis.ttl('user:10')

print("Command: ttl user:10 | Result: ", commandResult, "n")


# Set value for the same key, and pass "KEEPTTL" option. This will keep the TTL that was associated with the key
# Command: set user:10 "Some user" keepttl
# Result: OK
commandResult = redis.set('user:10', 'Some user', keepttl: true)

print("Command: set user:10 "Some user" keepttl | Result: ", commandResult, "n")


# Lets check the TTL. The TTL still exists because of usign the "KEEPTTL" option
# Command: ttl user:10
# Result: (integer) 360
commandResult = redis.ttl('user:10')

print("Command: ttl user:10 | Result: ", commandResult, "n")

Output:

Command: set firstkey "abcdef" | Result: OK
Command: get firstkey | Result: abcdef

Command: set firstkey defghi | Result: OK
Command: get firstkey | Result: defghi

Command: set secondkey "000000000000" XX | Result: false
Command: get secondkey | Result: 

Command: set secondkey "000000000000" NX | Result: true
Command: get secondkey | Result: 000000000000

Command: set firstkey "work idea" NX | Result: false
Command: get firstkey | Result: defghi

Command: set thirdkey 1111111111 GET | Result: 

Command: set thirdkey 99999999 GET | Result: 1111111111

Command: set fourthkey "some value for expire" EX 120 | Result: OK
Command: ttl fourthkey | Result: 120

Command: set mykey "some val" ex 360 | Result: OK
Command: ttl mykey | Result 360

Command: set mykey "changed value" | Result: OK
Command: ttl mykey | Result: -1

Command: set user:10 "John Doe" ex 360 | Result: OK
Command: ttl user:10 | Result: 360

Command: set user:10 "Some user" keepttl | Result: OK
Command: ttl user:10 | Result: 360

Notes

  • We have to use the “set” method from the library.
  •  Signature of the “set” method is – def set(key, value, ex: nil, px: nil, exat: nil, pxat: nil, nx: nil, xx: nil, keepttl: nil, get: nil)
  • Here are the types of the params-
    • ex: Integer
    • px: Integer
    • exat: Integer
    • pxat: Integer
    • nx: Boolean
    • xx: Boolean
    • keepttl: Boolean
    • get: Boolean

Source Code

Use the following links to get the source code used in this article-

Related Commands

CommandDetails
MSET Command Details
MSETNX Command Details
MGET Command Details

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.