Redis Command: LINSERT

Summary

Command NameLINSERT
UsageInsert a list element
Group list
ACL Category@write
@list
@slow
Time ComplexityO(N)
** N is the number of elements that need to be
traversed from start, before inserting the element
FlagWRITE
DENYOOM
Arity5

Notes

  • If we want to insert a new list item after the first item(from Left/HEAD) then the time complexity will be O(1).
  • If we want to insert a new list item after the last list item(at the Right/TAIL), and the list has N elements, then the complexity will be O(N).

Signature

LINSERT <key> ( BEFORE | AFTER ) <reference_element> <item_to_insert>

Notes

  • The reference element(before/after which we want to insert the new element), is also called “pivot“.

Usage

Insert an element in the list, before or after a specific element. This command does not insert an element at a specific position/index of the list.

It searches for the reference element(pivot), and after the pivot element is found then the new element is inserted before/after that specific element. So finding the pivot element is important. If the pivot/reference is not found then the command fails.

Notes

  • In case the reference/pivot element is not found, then this command does not perform any operations. As the list is considered an empty list.
  • The reference/pivot element searching is case-sensitive. If the case does not match, then it is considered as not found.

Arguments

ParameterGroupDescriptionNameType
<key>Key name of the listkeykey
BEFOREwhereInsert new element before the reference/pivot elementbeforepure-token
AFTERwhereInsert new element after the reference/pivot elementafterpure-token
<reference_element>Before/after which element the new element should be insertedpivotstring
<item_to_insert>The new item to insert in the listelementstring

Notes

  • Only one of the “BEFORE” or “AFTER” should be used, to indicate the position where the item should be inserted.

Return Value

Return valueCase for the return valueType
List length (positive intiger)List length (positive integer)integer
Zero(0)If the key (list name key) does not existinteger
Negative One (-1)When the reference element(pivot) is not found in the listinteger
errorIf the key exists but the data type of the key is not a listerror

Notes

  • If key is not of type list, the following error message is returned-
    (error) WRONGTYPE Operation against a key holding the wrong kind of value

Command Examples

Here are a few examples of the LINSERT command usage-

# Redis LINSERT command examples

# Push some element in the list
127.0.0.1:6379> rpush bigboxlist one two three four five one testA two testB testC
(integer) 10

# Check list items
127.0.0.1:6379> lrange bigboxlist 0 -1
 1) "one"
 2) "two"
 3) "three"
 4) "four"
 5) "five"
 6) "one"
 7) "testA"
 8) "two"
 9) "testB"
10) "testC"

# Insert new element after "one"
127.0.0.1:6379> linsert bigboxlist after one "new element after one"
(integer) 11

# Check the list. The new item is after one
127.0.0.1:6379> lrange bigboxlist 0 -1
 1) "one"
 2) "new element after one"
 3) "two"
 4) "three"
 5) "four"
 6) "five"
 7) "one"
 8) "testA"
 9) "two"
10) "testB"
11) "testC"

# Insert before the item "one"
127.0.0.1:6379> linsert bigboxlist before one "new element before one"
(integer) 12

# Check the list. The new item is inserted before "one"
127.0.0.1:6379> lrange bigboxlist 0 -1
 1) "new element before one"
 2) "one"
 3) "new element after one"
 4) "two"
 5) "three"
 6) "four"
 7) "five"
 8) "one"
 9) "testA"
10) "two"
11) "testB"
12) "testC"

# Insert before "testC"
127.0.0.1:6379> linsert bigboxlist before testC "new element before testC"
(integer) 13

# Check list, the new inserted item is there
127.0.0.1:6379> lrange bigboxlist 0 -1
 1) "new element before one"
 2) "one"
 3) "new element after one"
 4) "two"
 5) "three"
 6) "four"
 7) "five"
 8) "one"
 9) "testA"
10) "two"
11) "testB"
12) "new element before testC"
13) "testC"

# Try to insert with wrong case of the existing/pivot item
# We are using "testc" here, but in the list we have "testC"
# We get -1, as the item is considered as not exist 
127.0.0.1:6379> linsert bigboxlist after testc "my new item"
(integer) -1

# Try to insert before/after a non existing item
# We get -1, and the operation failed
127.0.0.1:6379> linsert bigboxlist after "this item does not exist" "my new item"
(integer) -1

# Try to use LINSERT for a non existing key
# We get Zero(0) as result
127.0.0.1:6379> linsert nonexistingkey after somesampleitem "my new item"
(integer) 0

# Set a string value
127.0.0.1:6379> set mystr "some string value"
OK

# Try to use LINSERT on a string type key
# We get an error in response
127.0.0.1:6379> linsert mystr after a "my new item"
(error) WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • If the item exists multiple times, then the only first instance is considered. The new item will be inserted BEFORE/AFTER the first element.

Code Implementations

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

// Redis LINSERT 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() {

	// Push some element in the list
	// Command: rpush bigboxlist one two three four five one testA two testB testC
	// Result: (integer) 10
	rpushResult, err := rdb.RPush(ctx, "bigboxlist", "one", "two", "three", "four", "five", "one", "testA", "two", "testB", "testC").Result()

	if err != nil {
		fmt.Println("Command: rpush bigboxlist one two three four five one testA two testB testC | Error: " + err.Error())
	}

	fmt.Printf("Command: rpush bigboxlist one two three four five one testA two testB testC | Result: %vn", rpushResult)

	// Check list items
	// Command: lrange bigboxlist 0 -1
	// Result:
	//      1) "one"
	//      2) "two"
	//      3) "three"
	//      4) "four"
	//      5) "five"
	//      6) "one"
	//      7) "testA"
	//      8) "two"
	//      9) "testB"
	//      10) "testC"
	lrangeResult, err := rdb.LRange(ctx, "bigboxlist", 0, -1).Result()

	if err != nil {
		fmt.Println("Command: lrange bigboxlist 0 -1 | Error: " + err.Error())
	}

	fmt.Println("Command: lrange bigboxlist 0 -1 | Result:")

	for _, item := range lrangeResult {
		fmt.Println(item)
	}

	// Insert new element after "one"
	// Command: linsert bigboxlist after one "new element after one"
	// Result: (integer) 11
	linsertResult, err := rdb.LInsert(ctx, "bigboxlist", "AFTER", "one", "new element after one").Result()

	if err != nil {
		fmt.Println("Command: linsert bigboxlist after one "new element after one" | Error: " + err.Error())
	}

	fmt.Printf("Command: linsert bigboxlist after one "new element after one" | Result: %vn", linsertResult)

	// Check the list. The new item is after one
	// Command: lrange bigboxlist 0 -1
	// Result:
	//      1) "one"
	//      2) "new element after one"
	//      3) "two"
	//      4) "three"
	//      5) "four"
	//      6) "five"
	//      7) "one"
	//      8) "testA"
	//      9) "two"
	//      10) "testB"
	//      11) "testC"
	lrangeResult, err = rdb.LRange(ctx, "bigboxlist", 0, -1).Result()

	if err != nil {
		fmt.Println("Command: lrange bigboxlist 0 -1 | Error: " + err.Error())
	}

	fmt.Println("Command: lrange bigboxlist 0 -1 | Result:")

	for _, item := range lrangeResult {
		fmt.Println(item)
	}

	// Insert before the item "one"
	// Command: linsert bigboxlist before one "new element before one"
	// Result: (integer) 12
	linsertResult, err = rdb.LInsertBefore(ctx, "bigboxlist", "one", "new element before one").Result()

	if err != nil {
		fmt.Println("Command: linsert bigboxlist before one "new element before one" | Error: " + err.Error())
	}

	fmt.Printf("Command: linsert bigboxlist before one "new element before one" | Result: %vn", linsertResult)

	// Check the list. The new item is inserted before "one"
	// Command: lrange bigboxlist 0 -1
	// Result:
	//      1) "new element before one"
	//      2) "one"
	//      3) "new element after one"
	//      4) "two"
	//      5) "three"
	//      6) "four"
	//      7) "five"
	//      8) "one"
	//      9) "testA"
	//      10) "two"
	//      11) "testB"
	//      12) "testC"
	lrangeResult, err = rdb.LRange(ctx, "bigboxlist", 0, -1).Result()

	if err != nil {
		fmt.Println("Command: lrange bigboxlist 0 -1 | Error: " + err.Error())
	}

	fmt.Println("Command: lrange bigboxlist 0 -1 | Result:")

	for _, item := range lrangeResult {
		fmt.Println(item)
	}

	// Insert before "testC"
	// Command: linsert bigboxlist before testC "new element before testC"
	// Result: (integer) 13
	linsertResult, err = rdb.LInsert(ctx, "bigboxlist", "BEFORE", "testC", "new element before testC").Result()

	if err != nil {
		fmt.Println("Command: linsert bigboxlist before testC "new element before testC" | Error: " + err.Error())
	}

	fmt.Printf("Command: linsert bigboxlist before testC "new element before testC" | Result: %vn", linsertResult)

	// Check list, the new inserted item is there
	// Command: lrange bigboxlist 0 -1
	// Result:
	//      1) "new element before one"
	//      2) "one"
	//      3) "new element after one"
	//      4) "two"
	//      5) "three"
	//      6) "four"
	//      7) "five"
	//      8) "one"
	//      9) "testA"
	//      10) "two"
	//      11) "testB"
	//      12) "new element before testC"
	//      13) "testC"
	lrangeResult, err = rdb.LRange(ctx, "bigboxlist", 0, -1).Result()

	if err != nil {
		fmt.Println("Command: lrange bigboxlist 0 -1 | Error: " + err.Error())
	}

	fmt.Println("Command: lrange bigboxlist 0 -1 | Result:")

	for _, item := range lrangeResult {
		fmt.Println(item)
	}

	// Try to insert with wrong case of the existing/pivot item
	// We are using "testc" here, but in the list we have "testC"
	// We get -1, as the item is considered as not exist
	// Command: linsert bigboxlist after testc "my new item"
	// Result: (integer) -1
	linsertResult, err = rdb.LInsert(ctx, "bigboxlist", "AFTER", "testc", "my new item").Result()

	if err != nil {
		fmt.Println("Command: linsert bigboxlist after testc "my new item" | Error: " + err.Error())
	}

	fmt.Printf("Command: linsert bigboxlist after testc "my new item" | Result: %vn", linsertResult)

	// Try to insert before/after a non existing item
	// We get -1, and the operation failed
	// Command: linsert bigboxlist after "this item does not exist" "my new item"
	// Result: (integer) -1
	linsertResult, err = rdb.LInsert(ctx, "bigboxlist", "AFTER", "this item does not exist", "my new item").Result()

	if err != nil {
		fmt.Println("Command: linsert bigboxlist after "this item does not exist" "my new item" | Error: " + err.Error())
	}

	fmt.Printf("Command: linsert bigboxlist after "this item does not exist" "my new item" | Result: %vn", linsertResult)

	// Try to use LINSERT for a non existing key
	// We get Zero(0) as result
	// Command: linsert nonexistingkey after somesampleitem "my new item"
	// Result: (integer) 0
	linsertResult, err = rdb.LInsert(ctx, "nonexistingkey", "AFTER", "somesampleitem", "my new item").Result()

	if err != nil {
		fmt.Println("Command: linsert nonexistingkey after somesampleitem "my new item" | Error: " + err.Error())
	}

	fmt.Printf("Command: linsert nonexistingkey after somesampleitem "my new item" | Result: %vn", linsertResult)

	// Set a string value
	// Command: set mystr "some string value"
	// Result: OK
	setResult, err := rdb.Set(ctx, "mystr", "some string value", 0).Result()

	if err != nil {
		fmt.Println("Command: set mystr "some string value" | Error: " + err.Error())
	}

	fmt.Println("Command: set mystr "some string value" | Result: " + setResult)

	// Try to use LINSERT on a string type key
	// We get an error in response
	// Command: linsert mystr after a "my new item"
	// Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
	linsertResult, err = rdb.LInsert(ctx, "mystr", "AFTER", "a", "my new item").Result()

	if err != nil {
		fmt.Println("Command: linsert mystr after a "my new item" | Error: " + err.Error())
	}

	fmt.Printf("Command: linsert mystr after a "my new item" | Result: %vn", linsertResult)

}

Output:

Command: rpush bigboxlist one two three four five one testA two testB testC | Result: 10

Command: lrange bigboxlist 0 -1 | Result:
one
two
three
four
five
one
testA
two
testB
testC

Command: linsert bigboxlist after one "new element after one" | Result: 11

Command: lrange bigboxlist 0 -1 | Result:
one
new element after one
two
three
four
five
one
testA
two
testB
testC

Command: linsert bigboxlist before one "new element before one" | Result: 12

Command: lrange bigboxlist 0 -1 | Result:
new element before one
one
new element after one
two
three
four
five
one
testA
two
testB
testC

Command: linsert bigboxlist before testC "new element before testC" | Result: 13

Command: lrange bigboxlist 0 -1 | Result:
new element before one
one
new element after one
two
three
four
five
one
testA
two
testB
new element before testC
testC

Command: linsert bigboxlist after testc "my new item" | Result: -1

Command: linsert bigboxlist after "this item does not exist" "my new item" | Result: -1

Command: linsert nonexistingkey after somesampleitem "my new item" | Result: 0

Command: set mystr "some string value" | Result: OK

Command: linsert mystr after a "my new item" | Error: WRONGTYPE Operation against a key holding the wrong kind of value
Command: linsert mystr after a "my new item" | Result: 0

Notes

  • Use “LInsert” method from redis-go module.
  • Signature of the method is-
    func (c cmdable) LInsert(ctx context.Context, key, op string, pivot, value interface{}) *IntCmd
  • There are other related methods to this LInsert for inserting before and after directly-
    func (c cmdable) LInsertBefore(ctx context.Context, key string, pivot, value interface{}) *IntCmd

    func (c cmdable) LInsertAfter(ctx context.Context, key string, pivot, value interface{}) *IntCmd
// Redis LINSERT 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();

/**
 * Push some element in the list
 *
 * Command: rpush bigboxlist one two three four five one testA two testB testC
 * Result: (integer) 10
 */
let commandResult = await redisClient.rPush("bigboxlist", [
  "one",
  "two",
  "three",
  "four",
  "five",
  "one",
  "testA",
  "two",
  "testB",
  "testC",
]);

console.log(
  "Command: rpush bigboxlist one two three four five one testA two testB testC | Result: " +
    commandResult
);

/**
 * Check list items
 *
 * Command: lrange bigboxlist 0 -1
 * Result:
 *      1) "one"
 *      2) "two"
 *      3) "three"
 *      4) "four"
 *      5) "five"
 *      6) "one"
 *      7) "testA"
 *      8) "two"
 *      9) "testB"
 *      10) "testC"
 */
commandResult = await redisClient.lRange("bigboxlist", 0, -1);

console.log("Command: lrange bigboxlist 0 -1 | Result:", commandResult);

/**
 * Insert new element after "one"
 *
 * Command: linsert bigboxlist after one "new element after one"
 * Result: (integer) 11
 */
commandResult = await redisClient.lInsert(
  "bigboxlist",
  "AFTER",
  "one",
  "new element after one"
);

console.log(
  'Command: linsert bigboxlist after one "new element after one" | Result: ' +
    commandResult
);

/**
 * Check the list. The new item is after one
 *
 * Command: lrange bigboxlist 0 -1
 * Result:
 *      1) "one"
 *      2) "new element after one"
 *      3) "two"
 *      4) "three"
 *      5) "four"
 *      6) "five"
 *      7) "one"
 *      8) "testA"
 *      9) "two"
 *      10) "testB"
 *      11) "testC"
 */
commandResult = await redisClient.lRange("bigboxlist", 0, -1);

console.log("Command: lrange bigboxlist 0 -1 | Result:", commandResult);

/**
 * Insert before the item "one"
 *
 * Command: linsert bigboxlist before one "new element before one"
 * Result: (integer) 12
 */
linsertResult = await redisClient.lInsert(
  "bigboxlist",
  "BEFORE",
  "one",
  "new element before one"
);

console.log(
  'Command: linsert bigboxlist before one "new element before one" | Result: ' +
    linsertResult
);

/**
 * Check the list. The new item is inserted before "one"
 *
 * Command: lrange bigboxlist 0 -1
 * Result:
 *      1) "new element before one"
 *      2) "one"
 *      3) "new element after one"
 *      4) "two"
 *      5) "three"
 *      6) "four"
 *      7) "five"
 *      8) "one"
 *      9) "testA"
 *      10) "two"
 *      11) "testB"
 *      12) "testC"
 */
commandResult = await redisClient.lRange("bigboxlist", 0, -1);

console.log("Command: lrange bigboxlist 0 -1 | Result:", commandResult);

/**
 * Insert before "testC"
 *
 * Command: linsert bigboxlist before testC "new element before testC"
 * Result: (integer) 13
 */
linsertResult = await redisClient.lInsert(
  "bigboxlist",
  "BEFORE",
  "testC",
  "new element before testC"
);

console.log(
  'Command: linsert bigboxlist before testC "new element before testC" | Result: ' +
    linsertResult
);

/**
 * Check list, the new inserted item is there
 *
 * Command: lrange bigboxlist 0 -1
 * Result:
 *      1) "new element before one"
 *      2) "one"
 *      3) "new element after one"
 *      4) "two"
 *      5) "three"
 *      6) "four"
 *      7) "five"
 *      8) "one"
 *      9) "testA"
 *      10) "two"
 *      11) "testB"
 *      12) "new element before testC"
 *      13) "testC"
 */
commandResult = await redisClient.lRange("bigboxlist", 0, -1);

console.log("Command: lrange bigboxlist 0 -1 | Result:", commandResult);

/**
 * Try to insert with wrong case of the existing/pivot item
 * We are using "testc" here, but in the list we have "testC"
 * We get -1, as the item is considered as not exist
 *
 * Command: linsert bigboxlist after testc "my new item"
 * Result: (integer) -1
 */
linsertResult = await redisClient.lInsert(
  "bigboxlist",
  "AFTER",
  "testc",
  "my new item"
);

console.log(
  'Command: linsert bigboxlist after testc "my new item" | Result: ' +
    linsertResult
);

/**
 * Try to insert before/after a non existing item
 * We get -1, and the operation failed
 *
 * Command: linsert bigboxlist after "this item does not exist" "my new item"
 * Result: (integer) -1
 */
linsertResult = await redisClient.lInsert(
  "bigboxlist",
  "AFTER",
  "this item does not exist",
  "my new item"
);

console.log(
  'Command: linsert bigboxlist after "this item does not exist" "my new item" | Result: ' +
    linsertResult
);

/**
 * Try to use LINSERT for a non existing key
 * We get Zero(0) as result
 *
 * Command: linsert nonexistingkey after somesampleitem "my new item"
 * Result: (integer) 0
 */
linsertResult = await redisClient.lInsert(
  "nonexistingkey",
  "AFTER",
  "somesampleitem",
  "my new item"
);

console.log(
  'Command: linsert nonexistingkey after somesampleitem "my new item" | Result: ' +
    linsertResult
);

/**
 * Set a string value
 *
 * Command: set mystr "some string value"
 * Result: OK
 */
commandResult = await redisClient.set("mystr", "some string value");

console.log(
  'Command: set mystr "some string value" | Result: ' + commandResult
);

/**
 * Try to use LINSERT on a string type key
 * We get an error in response
 *
 * Command: linsert mystr after a "my new item"
 * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
 */
try {
  linsertResult = await redisClient.lInsert(
    "mystr",
    "AFTER",
    "a",
    "my new item"
  );

  console.log(
    'Command: linsert mystr after a "my new item" | Result: ' + linsertResult
  );
} catch (e) {
  console.log('Command: linsert mystr after a "my new item" | Error: ', e);
}

process.exit(0);

Output:

Command: rpush bigboxlist one two three four five "test a" "test b" "test c" "second last item" "last item" | Result: 10

Command: lrange bigboxlist 0 -1 | Result:  [
  'one',
  'two',
  'three',
  'four',
  'five',
  'test a',
  'test b',
  'test c',
  'second last item',
  'last item'
]

Command: lindex bigboxlist 0 | Result: one

Command: lindex bigboxlist 1 | Result: two

Command: lindex bigboxlist 5 | Result: test a

Command: lindex bigboxlist -1 | Result: last item

Command: lindex bigboxlist -2 | Result: second last item

Command: lindex bigboxlist 100000000 | Result: null
Command: lindex bigboxlist -99999999 | Result: null

Command: lindex nonexistingkey 0 | Result: null

Command: set firststr "some string value here" | Result: OK
Command: lindex firststr 0 | Error:  [ErrorReply: WRONGTYPE Operation against a key holding the wrong kind of value]

Notes

  • Use the function “lInsert” from the package node-redis.
// Redis LINSERT command example in Java

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.args.ListPosition;

import java.util.List;

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

        try (Jedis jedis = jedisPool.getResource()) {

            /**
             * Push some element in the list
             *
             * Command: rpush bigboxlist one two three four five one testA two testB testC
             * Result: (integer) 10
             */
            long rpushResult = jedis.rpush("bigboxlist", "one", "two", "three", "four", "five", "one", "testA", "two", "testB", "testC");

            System.out.println("Command: rpush bigboxlist one two three four five one testA two testB testC | Result: " + rpushResult);

            /**
             * Check list items
             *
             * Command: lrange bigboxlist 0 -1
             * Result:
             *      1) "one"
             *      2) "two"
             *      3) "three"
             *      4) "four"
             *      5) "five"
             *      6) "one"
             *      7) "testA"
             *      8) "two"
             *      9) "testB"
             *      10) "testC"
             */
            List<String> lrangeResult = jedis.lrange("bigboxlist", 0, -1);

            System.out.println("Command: lrange bigboxlist 0 -1 | Result:");

            for (String item : lrangeResult) {
                System.out.println(item);
            }

            /**
             * Insert new element after "one"
             *
             * Command: linsert bigboxlist after one "new element after one"
             * Result: (integer) 11
             */
            long linsertResult = jedis.linsert("bigboxlist", ListPosition.AFTER, "one", "new element after one");

            System.out.println("Command: linsert bigboxlist after one "new element after one" | Result: " + linsertResult);

            /**
             * Check the list. The new item is after one
             *
             * Command: lrange bigboxlist 0 -1
             * Result:
             *      1) "one"
             *      2) "new element after one"
             *      3) "two"
             *      4) "three"
             *      5) "four"
             *      6) "five"
             *      7) "one"
             *      8) "testA"
             *      9) "two"
             *      10) "testB"
             *      11) "testC"
             */
            lrangeResult = jedis.lrange("bigboxlist", 0, -1);

            System.out.println("Command: lrange bigboxlist 0 -1 | Result:");

            for (String item : lrangeResult) {
                System.out.println(item);
            }

            /**
             * Insert before the item "one"
             *
             * Command: linsert bigboxlist before one "new element before one"
             * Result: (integer) 12
             */
            linsertResult = jedis.linsert("bigboxlist", ListPosition.BEFORE, "one", "new element before one");

            System.out.println("Command: linsert bigboxlist before one "new element before one" | Result: " + linsertResult);

            /**
             * Check the list. The new item is inserted before "one"
             *
             * Command: lrange bigboxlist 0 -1
             * Result:
             *      1) "new element before one"
             *      2) "one"
             *      3) "new element after one"
             *      4) "two"
             *      5) "three"
             *      6) "four"
             *      7) "five"
             *      8) "one"
             *      9) "testA"
             *      10) "two"
             *      11) "testB"
             *      12) "testC"
             */
            lrangeResult = jedis.lrange("bigboxlist", 0, -1);

            System.out.println("Command: lrange bigboxlist 0 -1 | Result:");

            for (String item : lrangeResult) {
                System.out.println(item);
            }

            /**
             * Insert before "testC"
             *
             * Command: linsert bigboxlist before testC "new element before testC"
             * Result: (integer) 13
             */
            linsertResult = jedis.linsert("bigboxlist", ListPosition.BEFORE, "testC", "new element before testC");

            System.out.println("Command: linsert bigboxlist before testC "new element before testC" | Result: " + linsertResult);

            /**
             * Check list, the new inserted item is there
             *
             * Command: lrange bigboxlist 0 -1
             * Result:
             *      1) "new element before one"
             *      2) "one"
             *      3) "new element after one"
             *      4) "two"
             *      5) "three"
             *      6) "four"
             *      7) "five"
             *      8) "one"
             *      9) "testA"
             *      10) "two"
             *      11) "testB"
             *      12) "new element before testC"
             *      13) "testC"
             */
            lrangeResult = jedis.lrange("bigboxlist", 0, -1);

            System.out.println("Command: lrange bigboxlist 0 -1 | Result:");

            for (String item : lrangeResult) {
                System.out.println(item);
            }

            /**
             * Try to insert with wrong case of the existing/pivot item
             * We are using "testc" here, but in the list we have "testC"
             * We get -1, as the item is considered as not exist
             *
             * Command: linsert bigboxlist after testc "my new item"
             * Result: (integer) -1
             */
            linsertResult = jedis.linsert("bigboxlist", ListPosition.AFTER, "testc", "my new item");

            System.out.println("Command: linsert bigboxlist after testc "my new item" | Result: " + linsertResult);

            /**
             * Try to insert before/after a non existing item
             * We get -1, and the operation failed
             *
             * Command: linsert bigboxlist after "this item does not exist" "my new item"
             * Result: (integer) -1
             */
            linsertResult = jedis.linsert("bigboxlist", ListPosition.AFTER, "this item does not exist", "my new item");

            System.out.println("Command: linsert bigboxlist after "this item does not exist" "my new item" | Result: " + linsertResult);

            /**
             * Try to use LINSERT for a non existing key
             * We get Zero(0) as result
             *
             * Command: linsert nonexistingkey after somesampleitem "my new item"
             * Result: (integer) 0
             */
            linsertResult = jedis.linsert("nonexistingkey", ListPosition.AFTER, "somesampleitem", "my new item");

            System.out.println("Command: linsert nonexistingkey after somesampleitem "my new item" | Result: " + linsertResult);

            /**
             * Set a string value
             *
             * Command: set mystr "some string value"
             * Result: OK
             */
            String setResult = jedis.set("mystr", "some string value");

            System.out.println("Command: set mystr "some string value" | Result: " + setResult);

            /**
             * Try to use LINSERT on a string type key
             * We get an error in response
             *
             * Command: linsert mystr after a "my new item"
             * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
             */
            try {
                linsertResult = jedis.linsert("mystr", ListPosition.AFTER, "a", "my new item");

                System.out.println("Command: linsert mystr after a "my new item" | Result: " + linsertResult);
            } catch(Exception e) {
                System.out.println("Command: linsert mystr after a "my new item" | Error: " + e.getMessage());
            }
                        
        }

        jedisPool.close();
    }
}

Output:

Command: rpush bigboxlist one two three four five one testA two testB testC | Result: 10

Command: lrange bigboxlist 0 -1 | Result:
one
two
three
four
five
one
testA
two
testB
testC

Command: linsert bigboxlist after one "new element after one" | Result: 11

Command: lrange bigboxlist 0 -1 | Result:
one
new element after one
two
three
four
five
one
testA
two
testB
testC

Command: linsert bigboxlist before one "new element before one" | Result: 12

Command: lrange bigboxlist 0 -1 | Result:
new element before one
one
new element after one
two
three
four
five
one
testA
two
testB
testC

Command: linsert bigboxlist before testC "new element before testC" | Result: 13

Command: lrange bigboxlist 0 -1 | Result:
new element before one
one
new element after one
two
three
four
five
one
testA
two
testB
new element before testC
testC

Command: linsert bigboxlist after testc "my new item" | Result: -1

Command: linsert bigboxlist after "this item does not exist" "my new item" | Result: -1

Command: linsert nonexistingkey after somesampleitem "my new item" | Result: 0

Command: set mystr "some string value" | Result: OK

Command: linsert mystr after a "my new item" | Error: WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use method “linsert” from Jedis package.
  • Signature of the method is-
    public long linsert(final String key, final ListPosition where, final String pivot, final String value)
// Redis LINSERT command examples in C#

using StackExchange.Redis;

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

            /**
             * Push some element in the list
             *
             * Command: rpush bigboxlist one two three four five one testA two testB testC
             * Result: (integer) 10
             */
            long rpushResult = rdb.ListRightPush("bigboxlist", new RedisValue[] { "one", "two", "three", "four", "five", "one", "testA", "two", "testB", "testC" });

            Console.WriteLine("Command: rpush bigboxlist one two three four five one testA two testB testC | Result: " + rpushResult);

            /**
             * Check list items
             *
             * Command: lrange bigboxlist 0 -1
             * Result:
             *      1) "one"
             *      2) "two"
             *      3) "three"
             *      4) "four"
             *      5) "five"
             *      6) "one"
             *      7) "testA"
             *      8) "two"
             *      9) "testB"
             *      10) "testC"
             */
            RedisValue[] lrangeResult = rdb.ListRange("bigboxlist", 0, -1);
            Console.WriteLine("Command: lrange bigboxlist 0 -1 | Result:");

            foreach (var item in lrangeResult)
            {
                Console.WriteLine(item);
            }

            /**
             * Insert new element after "one"
             *
             * Command: linsert bigboxlist after one "new element after one"
             * Result: (integer) 11
             */
            long linsertResult = rdb.ListInsertAfter("bigboxlist", "one", "new element after one");

            Console.WriteLine("Command: linsert bigboxlist after one "new element after one" | Result: " + linsertResult);

            /**
             * Check the list. The new item is after one
             *
             * Command: lrange bigboxlist 0 -1
             * Result:
             *      1) "one"
             *      2) "new element after one"
             *      3) "two"
             *      4) "three"
             *      5) "four"
             *      6) "five"
             *      7) "one"
             *      8) "testA"
             *      9) "two"
             *      10) "testB"
             *      11) "testC"
             */
            lrangeResult = rdb.ListRange("bigboxlist", 0, -1);

            Console.WriteLine("Command: lrange bigboxlist 0 -1 | Result:");

            foreach (var item in lrangeResult)
            {
                Console.WriteLine(item);
            }

            /**
             * Insert before the item "one"
             *
             * Command: linsert bigboxlist before one "new element before one"
             * Result: (integer) 12
             */
            linsertResult = rdb.ListInsertBefore("bigboxlist", "one", "new element before one");

            Console.WriteLine("Command: linsert bigboxlist before one "new element before one" | Result: " + linsertResult);

            /**
             * Check the list. The new item is inserted before "one"
             *
             * Command: lrange bigboxlist 0 -1
             * Result:
             *      1) "new element before one"
             *      2) "one"
             *      3) "new element after one"
             *      4) "two"
             *      5) "three"
             *      6) "four"
             *      7) "five"
             *      8) "one"
             *      9) "testA"
             *      10) "two"
             *      11) "testB"
             *      12) "testC"
             */
            lrangeResult = rdb.ListRange("bigboxlist", 0, -1);

            Console.WriteLine("Command: lrange bigboxlist 0 -1 | Result:");

            foreach (var item in lrangeResult)
            {
                Console.WriteLine(item);
            }

            /**
             * Insert before "testC"
             *
             * Command: linsert bigboxlist before testC "new element before testC"
             * Result: (integer) 13
             */
            linsertResult = rdb.ListInsertBefore("bigboxlist", "testC", "new element before testC");

            Console.WriteLine("Command: linsert bigboxlist before testC "new element before testC" | Result: " + linsertResult);

            /**
             * Check list, the new inserted item is there
             *
             * Command: lrange bigboxlist 0 -1
             * Result:
             *      1) "new element before one"
             *      2) "one"
             *      3) "new element after one"
             *      4) "two"
             *      5) "three"
             *      6) "four"
             *      7) "five"
             *      8) "one"
             *      9) "testA"
             *      10) "two"
             *      11) "testB"
             *      12) "new element before testC"
             *      13) "testC"
             */
            lrangeResult = rdb.ListRange("bigboxlist", 0, -1);

            Console.WriteLine("Command: lrange bigboxlist 0 -1 | Result:");

            foreach (var item in lrangeResult)
            {
                Console.WriteLine(item);
            }

            /**
             * Try to insert with wrong case of the existing/pivot item
             * We are using "testc" here, but in the list we have "testC"
             * We get -1, as the item is considered as not exist
             *
             * Command: linsert bigboxlist after testc "my new item"
             * Result: (integer) -1
             */
            linsertResult = rdb.ListInsertAfter("bigboxlist", "testc", "my new item");

            Console.WriteLine("Command: linsert bigboxlist after testc "my new item" | Result: " + linsertResult);

            /**
             * Try to insert before/after a non existing item
             * We get -1, and the operation failed
             *
             * Command: linsert bigboxlist after "this item does not exist" "my new item"
             * Result: (integer) -1
             */
            linsertResult = rdb.ListInsertAfter("bigboxlist", "this item does not exist", "my new item");

            Console.WriteLine("Command: linsert bigboxlist after "this item does not exist" "my new item" | Result: " + linsertResult);

            /**
             * Try to use LINSERT for a non existing key
             * We get Zero(0) as result
             *
             * Command: linsert nonexistingkey after somesampleitem "my new item"
             * Result: (integer) 0
             */
            linsertResult = rdb.ListInsertAfter("nonexistingkey", "somesampleitem", "my new item");

            Console.WriteLine("Command: linsert nonexistingkey after somesampleitem "my new item" | Result: " + linsertResult);

            /**
             * Set a string value
             *
             * Command: set mystr "some string value"
             * Result: OK
             */
            bool setResult = rdb.StringSet("mystr", "some string value");

            Console.WriteLine("Command: set mystr "some string value" | Result: " + setResult);

            /**
             * Try to use LINSERT on a string type key
             * We get an error in response
             *
             * Command: linsert mystr after a "my new item"
             * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
             */
            try
            {
                linsertResult = rdb.ListInsertAfter("mystr", "a", "my new item");

                Console.WriteLine("Command: linsert mystr after a "my new item" | Result: " + linsertResult);
            }
            catch (Exception e)
            {
                Console.WriteLine("Command: linsert mystr after a "my new item" | Error: " + e.Message);
            }
        }
    }
}

Output:

Command: rpush bigboxlist one two three four five one testA two testB testC | Result: 10

Command: lrange bigboxlist 0 -1 | Result:
one
two
three
four
five
one
testA
two
testB
testC

Command: linsert bigboxlist after one "new element after one" | Result: 11

Command: lrange bigboxlist 0 -1 | Result:
one
new element after one
two
three
four
five
one
testA
two
testB
testC

Command: linsert bigboxlist before one "new element before one" | Result: 12

Command: lrange bigboxlist 0 -1 | Result:
new element before one
one
new element after one
two
three
four
five
one
testA
two
testB
testC

Command: linsert bigboxlist before testC "new element before testC" | Result: 13

Command: lrange bigboxlist 0 -1 | Result:
new element before one
one
new element after one
two
three
four
five
one
testA
two
testB
new element before testC
testC

Command: linsert bigboxlist after testc "my new item" | Result: -1

Command: linsert bigboxlist after "this item does not exist" "my new item" | Result: -1

Command: linsert nonexistingkey after somesampleitem "my new item" | Result: 0

Command: set mystr "some string value" | Result: True
Command: linsert mystr after a "my new item" | Error: WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use the methods “ListInsertAfter” and “ListInsertBefore” from StackExchange.Redis.
  • Signature of these methods is-
    long ListInsertAfter(RedisKey key, RedisValue pivot, RedisValue value, CommandFlags flags = CommandFlags.None)
    long ListInsertBefore(RedisKey key, RedisValue pivot, RedisValue value, CommandFlags flags = CommandFlags.None)
<?php
// Redis LINSERT command example in PHP

require 'vendor/autoload.php';

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


/**
 * Push some element in the list
 *
 * Command: rpush bigboxlist one two three four five one testA two testB testC
 * Result: (integer) 10
 */
$commandResult = $redisClient->rpush("bigboxlist", [
    "one",
    "two",
    "three",
    "four",
    "five",
    "one",
    "testA",
    "two",
    "testB",
    "testC",
]);

echo "Command: rpush bigboxlist one two three four five one testA two testB testC | Result: " . $commandResult . "n";

/**
 * Check list items
 *
 * Command: lrange bigboxlist 0 -1
 * Result:
 *      1) "one"
 *      2) "two"
 *      3) "three"
 *      4) "four"
 *      5) "five"
 *      6) "one"
 *      7) "testA"
 *      8) "two"
 *      9) "testB"
 *      10) "testC"
 */
$commandResult = $redisClient->lrange("bigboxlist", 0, -1);

echo "Command: lrange bigboxlist 0 -1 | Result:n";
print_r($commandResult);

/**
 * Insert new element after "one"
 *
 * Command: linsert bigboxlist after one "new element after one"
 * Result: (integer) 11
 */
$commandResult = $redisClient->linsert(
    "bigboxlist",
    "AFTER",
    "one",
    "new element after one"
);

echo 'Command: linsert bigboxlist after one "new element after one" | Result: ' . $commandResult . "n";

/**
 * Check the list. The new item is after one
 *
 * Command: lrange bigboxlist 0 -1
 * Result:
 *      1) "one"
 *      2) "new element after one"
 *      3) "two"
 *      4) "three"
 *      5) "four"
 *      6) "five"
 *      7) "one"
 *      8) "testA"
 *      9) "two"
 *      10) "testB"
 *      11) "testC"
 */
$commandResult = $redisClient->lrange("bigboxlist", 0, -1);

echo "Command: lrange bigboxlist 0 -1 | Result:";
print_r($commandResult);

/**
 * Insert before the item "one"
 *
 * Command: linsert bigboxlist before one "new element before one"
 * Result: (integer) 12
 */
$commandResult = $redisClient->linsert(
    "bigboxlist",
    "BEFORE",
    "one",
    "new element before one"
);

echo 'Command: linsert bigboxlist before one "new element before one" | Result: ' . $commandResult . "n";

/**
 * Check the list. The new item is inserted before "one"
 *
 * Command: lrange bigboxlist 0 -1
 * Result:
 *      1) "new element before one"
 *      2) "one"
 *      3) "new element after one"
 *      4) "two"
 *      5) "three"
 *      6) "four"
 *      7) "five"
 *      8) "one"
 *      9) "testA"
 *      10) "two"
 *      11) "testB"
 *      12) "testC"
 */
$commandResult = $redisClient->lrange("bigboxlist", 0, -1);

echo "Command: lrange bigboxlist 0 -1 | Result:";
print_r($commandResult);

/**
 * Insert before "testC"
 *
 * Command: linsert bigboxlist before testC "new element before testC"
 * Result: (integer) 13
 */
$commandResult = $redisClient->linsert(
    "bigboxlist",
    "BEFORE",
    "testC",
    "new element before testC"
);

echo 'Command: linsert bigboxlist before testC "new element before testC" | Result: ' . $commandResult . "n";

/**
 * Check list, the new inserted item is there
 *
 * Command: lrange bigboxlist 0 -1
 * Result:
 *      1) "new element before one"
 *      2) "one"
 *      3) "new element after one"
 *      4) "two"
 *      5) "three"
 *      6) "four"
 *      7) "five"
 *      8) "one"
 *      9) "testA"
 *      10) "two"
 *      11) "testB"
 *      12) "new element before testC"
 *      13) "testC"
 */
$commandResult = $redisClient->lrange("bigboxlist", 0, -1);

echo "Command: lrange bigboxlist 0 -1 | Result:";
print_r($commandResult);

/**
 * Try to insert with wrong case of the existing/pivot item
 * We are using "testc" here, but in the list we have "testC"
 * We get -1, as the item is considered as not exist
 *
 * Command: linsert bigboxlist after testc "my new item"
 * Result: (integer) -1
 */
$commandResult = $redisClient->linsert(
    "bigboxlist",
    "AFTER",
    "testc",
    "my new item"
);

echo 'Command: linsert bigboxlist after testc "my new item" | Result: ' . $commandResult . "n";

/**
 * Try to insert before/after a non existing item
 * We get -1, and the operation failed
 *
 * Command: linsert bigboxlist after "this item does not exist" "my new item"
 * Result: (integer) -1
 */
$commandResult = $redisClient->linsert(
    "bigboxlist",
    "AFTER",
    "this item does not exist",
    "my new item"
);

echo 'Command: linsert bigboxlist after "this item does not exist" "my new item" | Result: ' . $commandResult . "n";

/**
 * Try to use LINSERT for a non existing key
 * We get Zero(0) as result
 *
 * Command: linsert nonexistingkey after somesampleitem "my new item"
 * Result: (integer) 0
 */
$commandResult = $redisClient->linsert(
    "nonexistingkey",
    "AFTER",
    "somesampleitem",
    "my new item"
);

echo 'Command: linsert nonexistingkey after somesampleitem "my new item" | Result: ' . $commandResult . "n";

/**
 * Set a string value
 *
 * Command: set mystr "some string value"
 * Result: OK
 */
$commandResult = $redisClient->set("mystr", "some string value");

echo 'Command: set mystr "some string value" | Result: ' . $commandResult . "n";

/**
 * Try to use LINSERT on a string type key
 * We get an error in response
 *
 * Command: linsert mystr after a "my new item"
 * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
 */
try {
    $commandResult = $redisClient->linsert(
        "mystr",
        "AFTER",
        "a",
        "my new item"
    );

    echo 'Command: linsert mystr after a "my new item" | Result: ' . $commandResult . "n";
} catch (Exception $e) {
    echo 'Command: linsert mystr after a "my new item" | Error: ' . $e->getMessage() . "n";
}

Output:

Command: rpush bigboxlist one two three four five one testA two testB testC | Result: 10

Command: lrange bigboxlist 0 -1 | Result:
Array
(
    [0] => one
    [1] => two
    [2] => three
    [3] => four
    [4] => five
    [5] => one
    [6] => testA
    [7] => two
    [8] => testB
    [9] => testC
)

Command: linsert bigboxlist after one "new element after one" | Result: 11

Command: lrange bigboxlist 0 -1 | Result:Array
(
    [0] => one
    [1] => new element after one
    [2] => two
    [3] => three
    [4] => four
    [5] => five
    [6] => one
    [7] => testA
    [8] => two
    [9] => testB
    [10] => testC
)

Command: linsert bigboxlist before one "new element before one" | Result: 12

Command: lrange bigboxlist 0 -1 | Result:Array
(
    [0] => new element before one
    [1] => one
    [2] => new element after one
    [3] => two
    [4] => three
    [5] => four
    [6] => five
    [7] => one
    [8] => testA
    [9] => two
    [10] => testB
    [11] => testC
)

Command: linsert bigboxlist before testC "new element before testC" | Result: 13

Command: lrange bigboxlist 0 -1 | Result:Array
(
    [0] => new element before one
    [1] => one
    [2] => new element after one
    [3] => two
    [4] => three
    [5] => four
    [6] => five
    [7] => one
    [8] => testA
    [9] => two
    [10] => testB
    [11] => new element before testC
    [12] => testC
)

Command: linsert bigboxlist after testc "my new item" | Result: -1

Command: linsert bigboxlist after "this item does not exist" "my new item" | Result: -1

Command: linsert nonexistingkey after somesampleitem "my new item" | Result: 0

Command: set mystr "some string value" | Result: OK
Command: linsert mystr after a "my new item" | Error: WRONGTYPE Operation against a key holding the wrong kind of value

Notes

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

import redis
import time

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


# Push some element in the list
# Command: rpush bigboxlist one two three four five one testA two testB testC
# Result: (integer) 10
commandResult = redisClient.rpush(
    "bigboxlist",
    "one",
    "two",
    "three",
    "four",
    "five",
    "one",
    "testA",
    "two",
    "testB",
    "testC",
);

print("Command: rpush bigboxlist one two three four five one testA two testB testC | Result: {}".format(commandResult))

# Check list items
# Command: lrange bigboxlist 0 -1
# Result:
#      1) "one"
#      2) "two"
#      3) "three"
#      4) "four"
#      5) "five"
#      6) "one"
#      7) "testA"
#      8) "two"
#      9) "testB"
#      10) "testC"
commandResult = redisClient.lrange("bigboxlist", 0, -1);

print("Command: lrange bigboxlist 0 -1 | Result:{}".format(commandResult))

# Insert new element after "one"
# Command: linsert bigboxlist after one "new element after one"
# Result: (integer) 11
commandResult = redisClient.linsert(
    "bigboxlist",
    "AFTER",
    "one",
    "new element after one"
)

print("Command: linsert bigboxlist after one "new element after one" | Result: {}".format(commandResult))

# Check the list. The new item is after one
# Command: lrange bigboxlist 0 -1
# Result:
#      1) "one"
#      2) "new element after one"
#      3) "two"
#      4) "three"
#      5) "four"
#      6) "five"
#      7) "one"
#      8) "testA"
#      9) "two"
#      10) "testB"
#      11) "testC"
commandResult = redisClient.lrange("bigboxlist", 0, -1);

print("Command: lrange bigboxlist 0 -1 | Result: {}".format(commandResult))

# Insert before the item "one"
# Command: linsert bigboxlist before one "new element before one"
# Result: (integer) 12
commandResult = redisClient.linsert(
    "bigboxlist",
    "BEFORE",
    "one",
    "new element before one"
)

print("Command: linsert bigboxlist before one "new element before one" | Result: {}".format(commandResult))

# Check the list. The new item is inserted before "one"
# Command: lrange bigboxlist 0 -1
# Result:
#      1) "new element before one"
#      2) "one"
#      3) "new element after one"
#      4) "two"
#      5) "three"
#      6) "four"
#      7) "five"
#      8) "one"
#      9) "testA"
#      10) "two"
#      11) "testB"
#      12) "testC"
commandResult = redisClient.lrange("bigboxlist", 0, -1)

print("Command: lrange bigboxlist 0 -1 | Result:{}".format(commandResult))

# Insert before "testC"
# Command: linsert bigboxlist before testC "new element before testC"
# Result: (integer) 13
commandResult = redisClient.linsert(
    "bigboxlist",
    "BEFORE",
    "testC",
    "new element before testC"
)

print("Command: linsert bigboxlist before testC "new element before testC" | Result: {}".format(commandResult))

# Check list, the new inserted item is there
# Command: lrange bigboxlist 0 -1
# Result:
#      1) "new element before one"
#      2) "one"
#      3) "new element after one"
#      4) "two"
#      5) "three"
#      6) "four"
#      7) "five"
#      8) "one"
#      9) "testA"
#      10) "two"
#      11) "testB"
#      12) "new element before testC"
#      13) "testC"
commandResult = redisClient.lrange("bigboxlist", 0, -1);

print("Command: lrange bigboxlist 0 -1 | Result: {}".format(commandResult))

# Try to insert with wrong case of the existing/pivot item
# We are using "testc" here, but in the list we have "testC"
# We get -1, as the item is considered as not exist
# Command: linsert bigboxlist after testc "my new item"
# Result: (integer) -1
commandResult = redisClient.linsert(
    "bigboxlist",
    "AFTER",
    "testc",
    "my new item"
)

print("Command: linsert bigboxlist after testc "my new item" | Result: {}".format(commandResult))

# Try to insert before/after a non existing item
# We get -1, and the operation failed
# Command: linsert bigboxlist after "this item does not exist" "my new item"
# Result: (integer) -1
commandResult = redisClient.linsert(
    "bigboxlist",
    "AFTER",
    "this item does not exist",
    "my new item"
)

print("Command: linsert bigboxlist after "this item does not exist" "my new item" | Result: {}".format(commandResult))

# Try to use LINSERT for a non existing key
# We get Zero(0) as result
# Command: linsert nonexistingkey after somesampleitem "my new item"
# Result: (integer) 0
commandResult = redisClient.linsert(
    "nonexistingkey",
    "AFTER",
    "somesampleitem",
    "my new item"
)

print("Command: linsert nonexistingkey after somesampleitem "my new item" | Result: {}".format(commandResult))

# Set a string value
# Command: set mystr "some string value"
# Result: OK
commandResult = redisClient.set("mystr", "some string value")

print("Command: set mystr "some string value" | Result: {}".format(commandResult))

# Try to use LINSERT on a string type key
# We get an error in response
# Command: linsert mystr after a "my new item"
# Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
try:
    commandResult = redisClient.linsert(
        "mystr",
        "AFTER",
        "a",
        "my new item"
    );

    print("Command: linsert mystr after a "my new item" | Result: {}".format(commandResult))
except Exception as error:
    print("Command: linsert mystr after a "my new item" | Error:", error)

Output:

Command: rpush bigboxlist one two three four five one testA two testB testC | Result: 10
Command: lrange bigboxlist 0 -1 | Result:['one', 'two', 'three', 'four', 'five', 'one', 'testA', 'two', 'testB', 'testC']

Command: linsert bigboxlist after one "new element after one" | Result: 11
Command: lrange bigboxlist 0 -1 | Result: ['one', 'new element after one', 'two', 'three', 'four', 'five', 'one', 'testA', 'two', 'testB', 'testC']

Command: linsert bigboxlist before one "new element before one" | Result: 12
Command: lrange bigboxlist 0 -1 | Result:['new element before one', 'one', 'new element after one', 'two', 'three', 'four', 'five', 'one', 'testA', 'two', 'testB', 'testC']

Command: linsert bigboxlist before testC "new element before testC" | Result: 13
Command: lrange bigboxlist 0 -1 | Result: ['new element before one', 'one', 'new element after one', 'two', 'three', 'four', 'five', 'one', 'testA', 'two', 'testB', 'new element before testC', 'testC']

Command: linsert bigboxlist after testc "my new item" | Result: -1

Command: linsert bigboxlist after "this item does not exist" "my new item" | Result: -1

Command: linsert nonexistingkey after somesampleitem "my new item" | Result: 0

Command: set mystr "some string value" | Result: True
Command: linsert mystr after a "my new item" | Error: WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use method “linsert” from redis-py.
  • Signature of the method is –
    def linsert(self, name: str, where: str, refvalue: str, value: str) -> Union[Awaitable[int], int]
# Redis LINSERT command example in Ruby

require 'redis'

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


# Push some element in the list
# Command: rpush bigboxlist one two three four five one testA two testB testC
# Result: (integer) 10
commandResult = redis.rpush("bigboxlist", [
    "one",
    "two",
    "three",
    "four",
    "five",
    "one",
    "testA",
    "two",
    "testB",
    "testC",
]);

print("Command: rpush bigboxlist one two three four five one testA two testB testC | Result: ", commandResult, "n")

# Check list items
# Command: lrange bigboxlist 0 -1
# Result:
#      1) "one"
#      2) "two"
#      3) "three"
#      4) "four"
#      5) "five"
#      6) "one"
#      7) "testA"
#      8) "two"
#      9) "testB"
#      10) "testC"
commandResult = redis.lrange("bigboxlist", 0, -1);

print("Command: lrange bigboxlist 0 -1 | Result:", commandResult, "n")

# Insert new element after "one"
# Command: linsert bigboxlist after one "new element after one"
# Result: (integer) 11
commandResult = redis.linsert(
    "bigboxlist",
    "AFTER",
    "one",
    "new element after one"
)

print("Command: linsert bigboxlist after one "new element after one" | Result: ", commandResult, "n")

# Check the list. The new item is after one
# Command: lrange bigboxlist 0 -1
# Result:
#      1) "one"
#      2) "new element after one"
#      3) "two"
#      4) "three"
#      5) "four"
#      6) "five"
#      7) "one"
#      8) "testA"
#      9) "two"
#      10) "testB"
#      11) "testC"
commandResult = redis.lrange("bigboxlist", 0, -1);

print("Command: lrange bigboxlist 0 -1 | Result11: ", commandResult, "n")

# Insert before the item "one"
# Command: linsert bigboxlist before one "new element before one"
# Result: (integer) 12
commandResult = redis.linsert(
    "bigboxlist",
    "BEFORE",
    "one",
    "new element before one"
)

print("Command: linsert bigboxlist before one "new element before one" | Result: ", commandResult, "n")

# Check the list. The new item is inserted before "one"
# Command: lrange bigboxlist 0 -1
# Result:
#      1) "new element before one"
#      2) "one"
#      3) "new element after one"
#      4) "two"
#      5) "three"
#      6) "four"
#      7) "five"
#      8) "one"
#      9) "testA"
#      10) "two"
#      11) "testB"
#      12) "testC"
commandResult = redis.lrange("bigboxlist", 0, -1)

print("Command: lrange bigboxlist 0 -1 | Result:", commandResult, "n")

# Insert before "testC"
# Command: linsert bigboxlist before testC "new element before testC"
# Result: (integer) 13
commandResult = redis.linsert(
    "bigboxlist",
    "BEFORE",
    "testC",
    "new element before testC"
)

print("Command: linsert bigboxlist before testC "new element before testC" | Result: ", commandResult, "n")

# Check list, the new inserted item is there
# Command: lrange bigboxlist 0 -1
# Result:
#      1) "new element before one"
#      2) "one"
#      3) "new element after one"
#      4) "two"
#      5) "three"
#      6) "four"
#      7) "five"
#      8) "one"
#      9) "testA"
#      10) "two"
#      11) "testB"
#      12) "new element before testC"
#      13) "testC"
commandResult = redis.lrange("bigboxlist", 0, -1);

print("Command: lrange bigboxlist 0 -1 | Result: ", commandResult, "n")

# Try to insert with wrong case of the existing/pivot item
# We are using "testc" here, but in the list we have "testC"
# We get -1, as the item is considered as not exist
# Command: linsert bigboxlist after testc "my new item"
# Result: (integer) -1
commandResult = redis.linsert(
    "bigboxlist",
    "AFTER",
    "testc",
    "my new item"
)

print("Command: linsert bigboxlist after testc "my new item" | Result: ", commandResult, "n")

# Try to insert before/after a non existing item
# We get -1, and the operation failed
# Command: linsert bigboxlist after "this item does not exist" "my new item"
# Result: (integer) -1
commandResult = redis.linsert(
    "bigboxlist",
    "AFTER",
    "this item does not exist",
    "my new item"
)

print("Command: linsert bigboxlist after "this item does not exist" "my new item" | Result: ", commandResult, "n")

# Try to use LINSERT for a non existing key
# We get Zero(0) as result
# Command: linsert nonexistingkey after somesampleitem "my new item"
# Result: (integer) 0
commandResult = redis.linsert(
    "nonexistingkey",
    "AFTER",
    "somesampleitem",
    "my new item"
)

print("Command: linsert nonexistingkey after somesampleitem "my new item" | Result: ", commandResult, "n")

# Set a string value
# Command: set mystr "some string value"
# Result: OK
commandResult = redis.set("mystr", "some string value")

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

# Try to use LINSERT on a string type key
# We get an error in response
# Command: linsert mystr after a "my new item"
# Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
begin
    commandResult = redis.linsert(
        "mystr",
        "AFTER",
        "a",
        "my new item"
    );

    print("Command: linsert mystr after a "my new item" | Result: ", commandResult, "n")
rescue => error
    print("Command: linsert mystr after a "my new item" | Error:", error)
end

Output:

Command: rpush bigboxlist one two three four five one testA two testB testC | Result: 10
Command: lrange bigboxlist 0 -1 | Result:["one", "two", "three", "four", "five", "one", "testA", "two", "testB", "testC"]

Command: linsert bigboxlist after one "new element after one" | Result: 11
Command: lrange bigboxlist 0 -1 | Result11: ["one", "new element after one", "two", "three", "four", "five", "one", "testA", "two", "testB", "testC"]

Command: linsert bigboxlist before one "new element before one" | Result: 12
Command: lrange bigboxlist 0 -1 | Result:["new element before one", "one", "new element after one", "two", "three", "four", "five", "one", "testA", "two", "testB", "testC"]

Command: linsert bigboxlist before testC "new element before testC" | Result: 13
Command: lrange bigboxlist 0 -1 | Result: ["new element before one", "one", "new element after one", "two", "three", "four", "five", "one", "testA", "two", "testB", "new element before testC", "testC"]

Command: linsert bigboxlist after testc "my new item" | Result: -1

Command: linsert bigboxlist after "this item does not exist" "my new item" | Result: -1

Command: linsert nonexistingkey after somesampleitem "my new item" | Result: 0

Command: set mystr "some string value" | Result: OK
Command: linsert mystr after a "my new item" | Error:WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use method “linsert” from the redis-rb.
  • Signature of the method is-

    # @param [String] key
    # @param [String, Symbol] where `BEFORE` or `AFTER`
    # @param [String] pivot reference element
    # @param [String] value
    # @return [Integer] length of the list after the insert operation, or `-1`
    #   when the element `pivot` was not found

    def linsert(key, where, pivot, value)

Source Code

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

Related Commands

CommandDetails
LPUSH Command Details
RPUSH Command Details
LRANGE Command Details

Leave a Comment


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