Redis Command: STRLEN

Summary

Command NameSTRLEN
UsageGet length of string
Group string
ACL Category@read
@string
@fast
Time ComplexityO(1)
FlagREADONLY
FAST
Arity2

Signature

STRLEN <key>

Usage

Get the length of the saved string value of the <key>.

Arguments

ParameterDescriptionNameType
<key>Name of the keykeykey

Return Value

Return valueCase for the return valueType
Integer value(non zero)If the key exists and has a valid string value saved.integer
zero (0)If the key does not exist.
Or the value is an empty string
integer
errorIf value is not of type stringerror

Notes

  • If the type of the value in the provided key is not a string then the following error is returned-
    (error) WRONGTYPE Operation against a key holding the wrong kind of value

Examples

Here are a few examples of the STRLEN command usage-

# Redis STRLEN command examples

127.0.0.1:6379> set sitename bigboxcode
OK

# Get string length when the key is set
127.0.0.1:6379> strlen sitename
(integer) 10

# Try getting length of a non-existing key, it will return Zero(0)
127.0.0.1:6379> strlen wrongkey
(integer) 0

# Set empty string as value for a key
127.0.0.1:6379> set empkey ""
OK

# Try getting legnth of a key that has empty string storead as value. It will return Zero(0) as the length of the value is Zero(0)
127.0.0.1:6379> strlen empkey
(integer) 0

# Initate a list and add elements
127.0.0.1:6379> lpush mylist "first list item" "second list item"
(integer) 2

# Try to apply STRLEN command for the list
# An error is returned
127.0.0.1:6379> strlen mylist
(error) WRONGTYPE Operation against a key holding the wrong kind of value

Code Implementations

Here are the usage examples of the Redis STRLEN command in different programming languages.

// Redis STRLEN command example in Golang

package main

import (
	"context"
	"fmt"

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

var rdb *redis.Client
var ctx context.Context

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

	ctx = context.Background()
}

func main() {

	// Set value for key "sitename"
	// Command: set sitename bigboxcode
	// Result: OK
	setResult, err := rdb.Set(ctx, "sitename", "bigboxcode", 0).Result()

	if err != nil {
		fmt.Println("Command: set sitename bigboxcode | Error: " + err.Error())
	}

	fmt.Println("Command: set sitename bigboxcode | Result: " + setResult)

	// Get string length when the key is set
	// Command: strlen sitename
	// Result: (integer) 10
	lenResult, err := rdb.StrLen(ctx, "sitename").Result()

	if err != nil {
		fmt.Println("Command: strlen sitename | Error: " + err.Error())
	}

	fmt.Printf("Command: strlen sitename | Result: %vn", lenResult)

	// Try getting length of a non-existing key, it will return Zero(0)
	// Command: strlen wrongkey
	// Result: (integer) 0
	lenResult, err = rdb.StrLen(ctx, "wrongkey").Result()

	if err != nil {
		fmt.Println("Command: strlen wrongkey | Error: " + err.Error())
	}

	fmt.Printf("Command: strlen wrongkey | Result: %vn", lenResult)

	// Set empty string as value for a key
	// Command: set empkey ""
	// Result: OK
	setResult, err = rdb.Set(ctx, "empkey", "", 0).Result()

	if err != nil {
		fmt.Println("Command: set empkey "" | Error: " + err.Error())
	}

	fmt.Printf("Command: set empkey "" | Result: %vn", setResult)

	// Try getting legnth of a key that has empty string storead as value. It will return Zero(0) as the length of the value is Zero(0)
	// Command: strlen empkey
	// Result: (integer) 0
	lenResult, err = rdb.StrLen(ctx, "empkey").Result()

	if err != nil {
		fmt.Println("Command: strlen empkey | Error: " + err.Error())
	}

	fmt.Printf("Command: strlen empkey | Result: %vn", lenResult)

	// Initate a list and add elements
	// Command: lpush mylist "first list item" "second list item"
	// Result: (integer) 2
	listResult, err := rdb.LPush(ctx, "mylist", "first list item", "second list item").Result()

	if err != nil {
		fmt.Println("Command: lpush mylist "first list item" "second list item" | Error: " + err.Error())
	}

	fmt.Printf("Command: lpush mylist "first list item" "second list item" | Result: %vn", listResult)

	// Try to apply STRLEN command for the list
	// An error is returned
	// Command: strlen mylist
	// Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
	lenResult, err = rdb.StrLen(ctx, "mylist").Result()

	if err != nil {
		fmt.Println("Command: strlen mylist | Error: " + err.Error())
	}

	fmt.Printf("Command: strlen mylist | Result: %vn", lenResult)

}

Output:

Command: set sitename bigboxcode | Result: OK
Command: strlen sitename | Result: 10

Command: strlen wrongkey | Result: 0

Command: set empkey "" | Result: OK
Command: strlen empkey | Result: 0

Command: lpush mylist "first list item" "second list item" | Result: 2
Command: strlen mylist | Error: WRONGTYPE Operation against a key holding the wrong kind of value
Command: strlen mylist | Result: 0

Notes

  • Use “Strlen” method from redis-go module.
  • Signature of the method is-
    StrLen(ctx context.Context, key string) *IntCmd
// Redis STRLEN 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 key "sitename"
 * Command: set sitename bigboxcode
 * Result: OK
 */
let commandResult = await redisClient.set("sitename", "bigboxcode");

console.log("Command: set sitename bigboxcode | Result: " + commandResult);

/**
 * Get string length when the key is set
 * Command: strlen sitename
 * Result: (integer) 10
 */
commandResult = await redisClient.strLen("sitename");

console.log("Command: strlen sitename | Result: " + commandResult);

/**
 * Try getting length of a non-existing key, it will return Zero(0)
 * Command: strlen wrongkey
 * Result: (integer) 0
 */
commandResult = await redisClient.strLen("wrongkey");

console.log("Command: strlen wrongkey | Result: " + commandResult);

/**
 * Set empty string as value for a key
 * Command: set empkey ""
 * Result: OK
 */
commandResult = await redisClient.set("empkey", "");

console.log("Command: set empkey "" | Result: " + commandResult);

/**
 * Try getting legnth of a key that has empty string storead as value. It will return Zero(0) as the length of the value is Zero(0)
 * Command: strlen empkey
 * Result: (integer) 0
 */
commandResult = await redisClient.strLen("empkey");

console.log("Command: strlen empkey | Result: " + commandResult);

/**
 * Initate a list and add elements
 * Command: lpush mylist "first list item" "second list item"
 * Result: (integer) 2
 */
commandResult = await redisClient.lPush("mylist", ["first list item", "second list item"]);

console.log("Command: lpush mylist "first list item" "second list item" | Result: " + commandResult);

/**
 * Try to apply STRLEN command for the list
 * An error is returned
 * Command: strlen mylist
 * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
 */
try {
    commandResult = await redisClient.strLen("mylist");

    console.log("Command: strlen mylist | Result: " + commandResult);
} catch (e) {
    console.log("Command: strlen mylist | Error: ", e);
}

process.exit(0);

Output:

Command: set sitename bigboxcode | Result: OK
Command: strlen sitename | Result: 10

Command: strlen wrongkey | Result: 0

Command: set empkey "" | Result: OK
Command: strlen empkey | Result: 0

Command: lpush mylist "first list item" "second list item" | Result: 2
Command: strlen mylist | Error:  [ErrorReply: WRONGTYPE Operation against a key holding the wrong kind of value]

Notes

  • Use function “strLen” for getting the Redis string length.
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

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

        try (Jedis jedis = jedisPool.getResource()) {
            /**
             * Set value for key "sitename"
             * Command: set sitename bigboxcode
             * Result: OK
             */
            String setResult = jedis.set("sitename", "bigboxcode");

            System.out.println("Command: set sitename bigboxcode | Result: " + setResult);

            /**
             * Get string length when the key is set
             * Command: strlen sitename
             * Result: (integer) 10
             */
            long lenResult = jedis.strlen("sitename");

            System.out.println("Command: strlen sitename | Result: " + lenResult);

            /**
             * Try getting length of a non-existing key, it will return Zero(0)
             * Command: strlen wrongkey
             * Result: (integer) 0
             */
            lenResult = jedis.strlen("wrongkey");

            System.out.println("Command: strlen wrongkey | Result: " + lenResult);

            /**
             * Set empty string as value for a key
             * Command: set empkey ""
             * Result: OK
             */
            setResult = jedis.set("empkey", "");

            System.out.println("Command: set empkey "" | Result: " + setResult);

            /**
             * Try getting legnth of a key that has empty string storead as value. It will return Zero(0) as the length of the value is Zero(0)
             * Command: strlen empkey
             * Result: (integer) 0
             */
            lenResult = jedis.strlen("empkey");

            System.out.println("Command: strlen empkey | Result: " + lenResult);

            /**
             * Initate a list and add elements
             * Command: lpush mylist "first list item" "second list item"
             * Result: (integer) 2
             */
            long listResult = jedis.lpush("mylist", "first list item", "second list item");

            System.out.println("Command: lpush mylist "first list item" "second list item" | Result: " + listResult);

            /**
             * Try to apply STRLEN command for the list
             * An error is returned
             * Command: strlen mylist
             * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
             */
            try {
                lenResult = jedis.strlen("mylist");

                System.out.println("Command: strlen mylist | Result: " + lenResult);
            } catch (Exception e) {
                System.out.println("Command: strlen mylist | Error: " + e.getMessage());
            }

        }

        jedisPool.close();
    }
}

Output:

Command: set sitename bigboxcode | Result: OK
Command: strlen sitename | Result: 10

Command: strlen wrongkey | Result: 0

Command: set empkey "" | Result: OK
Command: strlen empkey | Result: 0

Command: lpush mylist "first list item" "second list item" | Result: 2
Command: strlen mylist | Error: WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use method “strlen” from Jedis package.
  • Signature of the “strlen” is-
    public long strlen(final String key)
    or
    long strlen(byte[] key)
// Redis STRLEN command examples in C#

using StackExchange.Redis;

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

            /**
             * Set value for key "sitename"
             * Command: set sitename bigboxcode
             * Result: OK
             */
            bool setResult = rdb.StringSet("sitename", "bigboxcode");

            Console.WriteLine("Command: set sitename bigboxcode | Result: " + setResult);

            /**
             * Get string length when the key is set
             * Command: strlen sitename
             * Result: (integer) 10
             */
            long lenResult = rdb.StringLength("sitename");

            Console.WriteLine("Command: strlen sitename | Result: " + lenResult);

            /**
             * Try getting length of a non-existing key, it will return Zero(0)
             * Command: strlen wrongkey
             * Result: (integer) 0
             */
            lenResult = rdb.StringLength("wrongkey");

            Console.WriteLine("Command: strlen wrongkey | Result: " + lenResult);

            /**
             * Set empty string as value for a key
             * Command: set empkey ""
             * Result: OK
             */
            setResult = rdb.StringSet("empkey", "");

            Console.WriteLine("Command: set empkey "" | Result: " + setResult);

            /**
             * Try getting legnth of a key that has empty string storead as value. It will return Zero(0) as the length of the value is Zero(0)
             * Command: strlen empkey
             * Result: (integer) 0
             */
            lenResult = rdb.StringLength("empkey");

            Console.WriteLine("Command: strlen empkey | Result: " + lenResult);

            /**
             * Initate a list and add elements
             * Command: lpush mylist "first list item"
             * Result: (integer) 2
             */
            long listResult = rdb.ListLeftPush("mylist", "first list item");

            Console.WriteLine("Command: lpush mylist "first list item" | Result: " + listResult);

            /**
             * Try to apply STRLEN command for the list
             * An error is returned
             * Command: strlen mylist
             * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
             */
            try
            {
                lenResult = rdb.StringLength("mylist");

                Console.WriteLine("Command: strlen mylist | Result: " + lenResult);
            }
            catch (Exception e)
            {
                Console.WriteLine("Command: strlen mylist | Error: " + e.Message);
            }
        }
    }
}

Output:

Command: set sitename bigboxcode | Result: True
Command: strlen sitename | Result: 10

Command: strlen wrongkey | Result: 0

Command: set empkey "" | Result: True
Command: strlen empkey | Result: 0

Command: lpush mylist "first list item" | Result: 1
Command: strlen mylist | Error: WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use the method “StringLength” from StackExchange.Redis.
  • Signature of the method is-
    long StringLength(RedisKey key, CommandFlags flags = CommandFlags.None)
<?php
// Redis STRLEN command example in PHP

require 'vendor/autoload.php';

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


/**
 * Set value for key "sitename"
 * Command: set sitename bigboxcode
 * Result: OK
 */
$commandResult = $redisClient->set("sitename", "bigboxcode");

echo "Command: set sitename bigboxcode | Result: " . $commandResult . "n";

/**
 * Get string length when the key is set
 * Command: strlen sitename
 * Result: (integer) 10
 */
$commandResult = $redisClient->strlen("sitename");

echo "Command: strlen sitename | Result: " . $commandResult . "n";

/**
 * Try getting length of a non-existing key, it will return Zero(0)
 * Command: strlen wrongkey
 * Result: (integer) 0
 */
$commandResult = $redisClient->strlen("wrongkey");

echo "Command: strlen wrongkey | Result: " . $commandResult . "n";

/**
 * Set empty string as value for a key
 * Command: set empkey ""
 * Result: OK
 */
$commandResult = $redisClient->set("empkey", "");

echo "Command: set empkey "" | Result: " . $commandResult . "n";

/**
 * Try getting legnth of a key that has empty string storead as value. It will return Zero(0) as the length of the value is Zero(0)
 * Command: strlen empkey
 * Result: (integer) 0
 */
$commandResult = $redisClient->strlen("empkey");

echo "Command: strlen empkey | Result: " . $commandResult . "n";

/**
 * Initate a list and add elements
 * Command: lpush mylist "first list item" "second list item"
 * Result: (integer) 2
 */
$commandResult = $redisClient->lpush("mylist", ["first list item", "second list item"]);

echo "Command: lpush mylist "first list item" "second list item" | Result: " . $commandResult . "n";

/**
 * Try to apply STRLEN command for the list
 * An error is returned
 * Command: strlen mylist
 * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
 */
try {
    $commandResult = $redisClient->strlen("mylist");

    echo "Command: strlen mylist | Result: " . $commandResult . "n";
} catch (Exception $e) {
    echo "Command: strlen mylist | Error: " . $e->getMessage() . "n";
}

Output:

Command: set sitename bigboxcode | Result: OK
Command: strlen sitename | Result: 10

Command: strlen wrongkey | Result: 0

Command: set empkey "" | Result: OK
Command: strlen empkey | Result: 0

Command: lpush mylist "first list item" "second list item" | Result: 2
Command: strlen mylist | Error: WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use the method “strlen” of predis.
  • Signature of the method is-
    strlen(string $key): int
# Redis STRLEN command example in Python

import redis
import time

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


# Set value for key "sitename"
# Command: set sitename bigboxcode
# Result: OK
commandResult = redisClient.set("sitename", "bigboxcode")

print("Command: set sitename bigboxcode | Result: {}".format(commandResult))

# Get string length when the key is set
# Command: strlen sitename
# Result: (integer) 10
commandResult = redisClient.strlen("sitename")

print("Command: strlen sitename | Result: {}".format(commandResult))

# Try getting length of a non-existing key, it will return Zero(0)
# Command: strlen wrongkey
# Result: (integer) 0
commandResult = redisClient.strlen("wrongkey")

print("Command: strlen wrongkey | Result: {}".format(commandResult))

# Set empty string as value for a key
# Command: set empkey ""
# Result: OK
commandResult = redisClient.set("empkey", "")

print("Command: set empkey "" | Result: {}".format(commandResult))

# Try getting legnth of a key that has empty string storead as value. It will return Zero(0) as the length of the value is Zero(0)
# Command: strlen empkey
# Result: (integer) 0
commandResult = redisClient.strlen("empkey")

print("Command: strlen empkey | Result: {}".format(commandResult))

# Initate a list and add elements
# Command: lpush mylist "first list item" "second list item"
# Result: (integer) 2
commandResult = redisClient.lpush(
    "mylist", "first list item", "second list item")

print("Command: lpush mylist "first list item" "second list item" | Result: {}".format(commandResult))

# Try to apply STRLEN command for the list
# An error is returned
# Command: strlen mylist
# Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
try:
    commandResult = redisClient.strlen("mylist")

    print("Command: strlen mylist | Result: {}".format(commandResult))
except Exception as error:
    print("Command: strlen mylist | Error: ", error)

Output:

Command: set sitename bigboxcode | Result: True
Command: strlen sitename | Result: 10

Command: strlen wrongkey | Result: 0

Command: set empkey "" | Result: True
Command: strlen empkey | Result: 0

Command: lpush mylist "first list item" "second list item" | Result: 2
Command: strlen mylist | Error:  WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use method “strlen” from redis-py.
  • Signature of the method is –
    def strlen(self, name: KeyT) -> ResponseT
# Redis STRLEN command example in Ruby

require 'redis'

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


# Set value for key "sitename"
# Command: set sitename bigboxcode
# Result: OK
commandResult = redis.set("sitename", "bigboxcode")

print("Command: set sitename bigboxcode | Result: ", commandResult, "n")

# Get string length when the key is set
# Command: strlen sitename
# Result: (integer) 10
commandResult = redis.strlen("sitename")

print("Command: strlen sitename | Result: ", commandResult, "n")

# Try getting length of a non-existing key, it will return Zero(0)
# Command: strlen wrongkey
# Result: (integer) 0
commandResult = redis.strlen("wrongkey")

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

# Set empty string as value for a key
# Command: set empkey ""
# Result: OK
commandResult = redis.set("empkey", "")

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

# Try getting legnth of a key that has empty string storead as value. It will return Zero(0) as the length of the value is Zero(0)
# Command: strlen empkey
# Result: (integer) 0
commandResult = redis.strlen("empkey")

print("Command: strlen empkey | Result: ", commandResult, "n")

# Initate a list and add elements
# Command: lpush mylist "first list item" "second list item"
# Result: (integer) 2
commandResult = redis.lpush(
    "mylist", ["first list item", "second list item"])

print("Command: lpush mylist "first list item" "second list item" | Result: ", commandResult, "n")

# Try to apply STRLEN command for the list
# An error is returned
# Command: strlen mylist
# Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
begin
    commandResult = redis.strlen("mylist")

    print("Command: strlen mylist | Result: ", commandResult, "n")
rescue => e
    print("Command: strlen mylist | Error: ", e, "n")
end

Output:

Command: set sitename bigboxcode | Result: OK
Command: strlen sitename | Result: 10

Command: strlen wrongkey | Result: 0

Command: set empkey "" | Result: OK
Command: strlen empkey | Result: 0

Command: lpush mylist "first list item" "second list item" | Result: 2
Command: strlen mylist | Error: WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use method “strlen” from the redis-rb.
  • Signature of the “getrange” method is-
    def strlen(key)

Source Code

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

Related Commands

CommandDetails
GETRANGE Command Details
LCS Command Details

Leave a Comment


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