Redis Command: GET

Summary

Command NameGET
UsageRetrieve string value
Group string
ACL Category@read
@string
@fast
Time ComplexityO(1)
FlagREADONLY
FAST
Arity2

Signature

GET <key>

Usage

Get/retrieve the string value that is set for the <key>. It only works if the saved value is of type string. This command returns nil if the does not exist.

Arguments

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

ArgumentDescriptionNameType
<key>Name of the key that we want to get value of.keykey

Return Value

Return valueCase for the return valueType
Value saved for the keyWhen the key exits, and the key has a valid value saved for it.string
(nil)When the key does not exist.null
errorWhen the saved value for the key is not a valid string.error

Examples

Here are a few examples of the GET command usage-

# Set a key/value
127.0.0.1:6379> set firstkey "some value"
OK

# Check the key/value
127.0.0.1:6379> get firstkey
"some value"

# Use same string as key name, but with different case
127.0.0.1:6379> set FirstKey "value changed"
OK

127.0.0.1:6379> get FirstKey
"value changed"

# Value of 'firstkey' stays the same
# as 'firstkey' and 'FirstKey' are 2 different keys
127.0.0.1:6379> get firstkey
"some value"

# Try getting a key that does not exist
127.0.0.1:6379> get somewrongkey
(nil)


# Let's check the get command for data other that string
# Create a list and push item
127.0.0.1:6379> lpush mylist "first item of list"
(integer) 1

# Try to get the value of "mylist" with "get" command. Should return an error
127.0.0.1:6379> get mylist
(error) WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • GET command works only for string type of data. Will not work for any other type like lists, hashes, sets, etc.
  • Key names are case-sensitive. The same key name string with different cases means different keys. Like, “firstkey“, “FirstKey” and “FiRsTkEy” are 3 different keys.

Code Implementations

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

package main

import (
	"context"
	"fmt"
	"log"

	"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 a key/value
	// Command: set firstkey "some value"
	// Result: OK
	err := rdb.Set(ctx, "firstkey", "some value", 0).Err()

	if err != nil {
		fmt.Println(colorRed + "Can not set firstkey" + styleReset)
	} else {
		fmt.Println("Set value of 'firstkey' to 'some value'")
	}

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

	if err != nil {
		log.Println("Can not read firstkey")
	}

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

	// Check the value of key wrongkey (which does not exist in database)
	// Command: get wrongkey
	// Result: nil
	wrongKey, err := rdb.Get(ctx, "wrongkey").Result()

	if err != nil {
		// This panic should be reached as "wrongkey does not exist"
		// panic("Can not read wrongkey")
		fmt.Println(colorRed + "Can not read 'wrongkey'" + styleReset)
	}

	fmt.Printf("Value of 'wrongkey' is: %sn", wrongKey)
}

Output:

Set value of 'firstkey' to 'some value'

Value of 'firstkey' is: some value

Can not read 'wrongkey'
Value of 'wrongkey' is:

Notes

  • The package used for this implementation is “go-redis“.
  • To get the value of a key we need to use the “Get” method of Redis client. The “Get” method accepts 2 parameters a context and the key name. Signature of the method is – Get(ctx context.Context, key string) *StringCmd. We can use the “Result()” method on the returned value, to get the result. Or we can use the “Err()” to get error.
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 of 'firstkey'
// Command: set firstkey "some value set by NodeJS"
// Result: OK
await redisClient.set('firstkey', 'some value set by NodeJS');

// Retrieve value of 'firstkey'
// Command: get firstkey
// Result: "some value set by NodeJS"
const firstKey = await redisClient.get('firstkey');

console.log("Value of 'firstkey': " + firstKey);

// Try to get value of a key that does not exist
// Command: get wrongkey
// Result: nil
const wrongKey = await redisClient.GET('wrongkey')

console.log("Value of 'wrongkey': " + wrongKey);

// Exit node process
process.exit(0);

Output:

Value of 'firstkey': some value set by NodeJS

Value of 'wrongkey': null

Notes

  • The package used for this implementation is “redis“.
  • To get value of a key we need to use “get” (or “GET“) function of the client. “get” and “GET” both function names will work. The “get” function accepts only one parameter- the key name.
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

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

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

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


            /**
             * Check the value of key firstkey
             *
             * Command: get firstkey
             * Result: "some value"
             */
            commandResult= jedis.get("firstkey");

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


            /**
             * Check the value of key wrongkey (which does not exist in database)
             *
             * Command: get wrongkey
             * Result: nil
             */
            commandResult = jedis.get("wrongkey");

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

        pool.close();
    }
}

Output:

Command: set firstkey "some value" | Result: OK
Command: get firstkey | Result: some value
Command: get wrongkey | Result: null

Notes

  • The package used for this implementation is “Jedis“.
  • Use “get” method for using the Redis GET command. The signature of this method is public String get(final String key), so it accepts a string key and returns a string.
using StackExchange.Redis;
using System;

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


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

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


            /**
             * Check the value of key firstkey
             *
             * Command: get firstkey
             * Result: "some value"
             */
            var getCommandResult = rdb.StringGet("firstkey");

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


            /**
             * Check the value of key wrongkey (which does not exist in database)
             *
             * Command: get wrongkey
             * Result: nil
             */
            getCommandResult = rdb.StringGet("wrongkey");

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

Output:

Command: set firstkey "some value" | Result: True

Command: get firstkey | Result: some value

Command: get wrongkey | Result:

Notes

  • We have used dotnet package “StackExchange.Redis”.
  • To use the GET command from Redis we have used the method “StringGet” from the package. The method signature is RedisValue StringGet(RedisKey key, CommandFlags flags = CommandFlags.None);
<?php
// Redis GET command example

require 'vendor/autoload.php';

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

// Set value for "firstkey"
// Command: set firstkey "first key set by PHP predis"
// Result: OK
$redisClient->set('firstkey', 'first key set by PHP predis');

// Get/retrieve value of "firstkey"
// Command: get firstkey
// Result: "first key set by PHP predis"
$firstKey = $redisClient->get('firstkey');

echo "Value of 'firstkey': " . $firstKey . "n";

// Try to get value of a key that does not exist
// Command: get wrongkey
// Result: nil
$wrongKey = $redisClient->get('wrongkey');

echo "Value of 'wrongkey': " . $wrongKey . "n";

Output:

Value of 'firstkey': first key set by PHP predis

Value of 'wrongkey':

Notes

  • The package used for this implementation is “Predis“.
  • Use the method “get” to get the value of a key. We just need to pass the key name as param to the method.
import redis

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

# Set value for 'firstkey'
# Command: set firstkey "First Key value set by Python Script"
# Result: OK
redisClient.set('firstkey', 'First Key value set by Python Script')

# Get value of 'firstkey'
# Command: get firstkey
# Result: "First Key value set by Python Script"
firstKey = redisClient.get('firstkey')

print('Value of the "firstkey": ' + firstKey)

# Get value of 'wrongkey', this key does not exist
# should return an empty response (None in case of python)
# Command: get wrongkey
# Result: nil
wrongKey = redisClient.get('wrongkey')

print('Value of the "wrong": ' + str(wrongKey))

Output:

Value of the "firstkey": First Key value set by Python Script

Value of the "wrong": None

Notes

  • The package used for this implementation is “redis“.
  • Use the method “get” of the client, and pass the key name to the method to get the value.
require 'redis'

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


# Set a key/value
# Command: set firstkey "some value"
# Result: OK
commandResult = redis.set("firstkey", "some value")

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


# Check the value of key firstkey
# Command: get firstkey
# Result: "some value"
commandResult = redis.get("firstkey")

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


# Check the value of key wrongkey (which does not exist in database)
# Command: get wrongkey
# Result: nil
commandResult = redis.get("wrongkey")

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

Output:

Command: set firstkey "some value" | Result: OK
Command: get firstkey | Result: some value
Command: get wrongkey | Result:

Notes

  • We need to use the method “get” from Ruby redis-rb gem, for getting string data from Redis.

Source Code

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

Related Commands

CommandDetails
MGET Command Details
GETEX Command Details
GETRANGE Command Details
GETDEL Command Details
SET Command Details

Leave a Comment


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